Salome HOME
Add the job command
[tools/sat.git] / src / environment.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2013  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 subprocess
21 import string
22 import sys
23
24 import src
25
26 class Environ:
27     '''Class to manage the environment context
28     '''
29     def __init__(self, environ=None):
30         '''Initialization. If the environ argument is passed, the environment
31            will be add to it, else it is the external environment.
32            
33         :param environ dict:  
34         '''
35         if environ is not None:
36             self.environ = environ
37         else:
38             self.environ = os.environ
39
40     def __repr__(self):
41         """easy non exhaustive quick resume for debug print
42         """
43         res={}
44         res["environ"]=self.environ
45         return self.__class__.__name__ + str(res)[0:-1] + " ...etc...}"
46
47     def _expandvars(self, value):
48         '''replace some $VARIABLE into its actual value in the environment
49         
50         :param value str: the string to be replaced
51         :return: the replaced variable
52         :rtype: str
53         '''
54         if "$" in value:
55             # The string.Template class is a string class 
56             # for supporting $-substitutions
57             zt = string.Template(value)
58             try:
59                 value = zt.substitute(self.environ)
60             except KeyError as exc:
61                 raise src.SatException(_("Missing definition "
62                                          "in environment: %s") % str(exc))
63         return value
64
65     def append_value(self, key, value, sep=os.pathsep):
66         '''append value to key using sep
67         
68         :param key str: the environment variable to append
69         :param value str: the value to append to key
70         :param sep str: the separator string
71         '''
72         # check if the key is already in the environment
73         if key in self.environ:
74             value_list = self.environ[key].split(sep)
75             # Check if the value is already in the key value or not
76             if not value in value_list:
77                 value_list.append(value)
78             else:
79                 value_list.append(value_list.pop(value_list.index(value)))
80             self.set(key, sep.join(value_list))
81         else:
82             self.set(key, value)
83
84     def append(self, key, value, sep=os.pathsep):
85         '''Same as append_value but the value argument can be a list
86         
87         :param key str: the environment variable to append
88         :param value str or list: the value(s) to append to key
89         :param sep str: the separator string
90         '''
91         if isinstance(value, list):
92             for v in value:
93                 self.append_value(key, v, sep)
94         else:
95             self.append_value(key, value, sep)
96
97     def prepend_value(self, key, value, sep=os.pathsep):
98         '''prepend value to key using sep
99         
100         :param key str: the environment variable to prepend
101         :param value str: the value to prepend to key
102         :param sep str: the separator string
103         '''
104         if key in self.environ:
105             value_list = self.environ[key].split(sep)
106             if not value in value_list:
107                 value_list.insert(0, value)
108             else:
109                 value_list.insert(0, value_list.pop(value_list.index(value)))
110             self.set(key, sep.join(value_list))
111         else:
112             self.set(key, value)
113
114     def prepend(self, key, value, sep=os.pathsep):
115         '''Same as prepend_value but the value argument can be a list
116         
117         :param key str: the environment variable to prepend
118         :param value str or list: the value(s) to prepend to key
119         :param sep str: the separator string
120         '''
121         if isinstance(value, list):
122             for v in value:
123                 self.prepend_value(key, v, sep)
124         else:
125             self.prepend_value(key, value, sep)
126
127     def is_defined(self, key):
128         '''Check if the key exists in the environment
129         
130         :param key str: the environment variable to check
131         '''
132         return key in self.environ.keys()
133
134     def set(self, key, value):
135         '''Set the environment variable "key" to value "value"
136         
137         :param key str: the environment variable to set
138         :param value str: the value
139         '''
140         self.environ[key] = self._expandvars(value)
141
142     def get(self, key):
143         '''Get the value of the environment variable "key"
144         
145         :param key str: the environment variable
146         '''
147         if key in self.environ:
148             return self.environ[key]
149         else:
150             return ""
151
152     def command_value(self, key, command):
153         '''Get the value given by the system command "command" 
154            and put it in the environment variable key
155         
156         :param key str: the environment variable
157         :param command str: the command to execute
158         '''
159         value = subprocess.Popen(command,
160                                  shell=True,
161                                  stdout=subprocess.PIPE,
162                                  env=self.environ).communicate()[0]
163         self.environ[key] = value
164
165
166 class SalomeEnviron:
167     """Class to manage the environment of SALOME.
168     """
169
170     def __init__(self, cfg, environ, forBuild=False):
171         '''Initialization.
172
173         :param cfg Config: the global config
174         :param environ Environ: the Environ instance where 
175                                 to store the environment variables
176         :param forBuild bool: If true, it is a launch environment, 
177                               else a build one
178         '''
179         self.environ = environ
180         self.cfg = cfg
181         self.forBuild = forBuild
182         self.silent = False
183
184     def __repr__(self):
185         """easy non exhaustive quick resume for debug print"""
186         res={}
187         res["environ"]=str(self.environ)
188         res["forBuild"]=self.forBuild
189         return self.__class__.__name__ + str(res)[0:-1] + " ...etc...}"
190
191     def append(self, key, value, sep=os.pathsep):
192         '''append value to key using sep
193         
194         :param key str: the environment variable to append
195         :param value str: the value to append to key
196         :param sep str: the separator string
197         '''
198         return self.environ.append(key, value, sep)
199
200     def prepend(self, key, value, sep=os.pathsep):
201         '''prepend value to key using sep
202         
203         :param key str: the environment variable to prepend
204         :param value str: the value to prepend to key
205         :param sep str: the separator string
206         '''
207         return self.environ.prepend(key, value, sep)
208
209     def is_defined(self, key):
210         '''Check if the key exists in the environment
211         
212         :param key str: the environment variable to check
213         '''
214         return self.environ.is_defined(key)
215
216     def get(self, key):
217         '''Get the value of the environment variable "key"
218         
219         :param key str: the environment variable
220         '''
221         return self.environ.get(key)
222
223     def set(self, key, value):
224         '''Set the environment variable "key" to value "value"
225         
226         :param key str: the environment variable to set
227         :param value str: the value
228         '''
229         # check if value needs to be evaluated
230         if value is not None and value.startswith("`") and value.endswith("`"):
231             res = subprocess.Popen("echo %s" % value,
232                                    shell=True,
233                                    stdout=subprocess.PIPE).communicate()
234             value = res[0].strip()
235
236         return self.environ.set(key, value)
237
238     def dump(self, out):
239         """Write the environment to out
240         
241         :param out file: the stream where to write the environment
242         """
243         for k in self.environ.environ.keys():
244             try:
245                 value = self.get(k)
246             except:
247                 value = "?"
248             out.write("%s=%s\n" % (k, value))
249
250     def add_line(self, nb_line):
251         """Add empty lines to the out stream (in case of file generation)
252         
253         :param nb_line int: the number of empty lines to add
254         """
255         if 'add_line' in dir(self.environ):
256             self.environ.add_line(nb_line)
257
258     def add_comment(self, comment):
259         """Add a commentary to the out stream (in case of file generation)
260         
261         :param comment str: the commentary to add
262         """
263         if 'add_comment' in dir(self.environ):
264             self.environ.add_comment(comment)
265
266     def add_warning(self, warning):
267         """Add a warning to the out stream (in case of file generation)
268         
269         :param warning str: the warning to add
270         """
271         if 'add_warning' in dir(self.environ):
272             self.environ.add_warning(warning)
273
274     def finish(self, required):
275         """Add a final instruction in the out file (in case of file generation)
276         
277         :param required bool: Do nothing if required is False
278         """
279         if 'finish' in dir(self.environ):
280             self.environ.add_line(1)
281             self.environ.add_comment("clean all the path")
282             self.environ.finish(required)
283
284     def set_python_libdirs(self):
285         """Set some generic variables for python library paths
286         """
287         ver = self.get('PYTHON_VERSION')
288         self.set('PYTHON_LIBDIR0', os.path.join('lib',
289                                                 'python' + ver,
290                                                 'site-packages'))
291         self.set('PYTHON_LIBDIR1', os.path.join('lib64',
292                                                 'python' + ver,
293                                                 'site-packages'))
294           
295         self.python_lib0 = self.get('PYTHON_LIBDIR0')
296         self.python_lib1 = self.get('PYTHON_LIBDIR1')
297
298     def get_names(self, lProducts):
299         """Get the products name to add in SALOME_MODULES environment variable
300            It is the name of the product, except in the case where the is a 
301            component name. And it has to be in SALOME_MODULES variable only 
302            if has_gui = "yes"
303         
304         :param lProducts list: List of products to potentially add
305         """
306         lProdHasGui = [p for p in lProducts if 'type ' in 
307                     src.product.get_product_config(self.cfg, p) and 
308                     src.product.get_product_config(self.cfg, p).type=='salome']
309         lProdName = []
310         for ProdName in lProdHasGui:
311             pi = src.product.get_product_config(self.cfg, ProdName)
312             if 'component_name' in pi:
313                 lProdName.append(pi.component_name)
314             else:
315                 lProdName.append(ProdName)
316         return lProdName
317
318     def set_application_env(self, logger):
319         """Sets the environment defined in the APPLICATION file.
320         
321         :param logger Logger: The logger instance to display messages
322         """
323         
324         # Set the variables defined in the "environ" section
325         if 'environ' in self.cfg.APPLICATION:
326             self.add_comment("APPLICATION environment")
327             for p in self.cfg.APPLICATION.environ:
328                 self.set(p, self.cfg.APPLICATION.environ[p])
329             self.add_line(1)
330
331         # If there is an "environ_script" section, load the scripts
332         if 'environ_script' in self.cfg.APPLICATION:
333             for pscript in self.cfg.APPLICATION.environ_script:
334                 self.add_comment("script %s" % pscript)
335                 sname = pscript.replace(" ", "_")
336                 self.run_env_script("APPLICATION_%s" % sname,
337                                 self.cfg.APPLICATION.environ_script[pscript],
338                                 logger)
339                 self.add_line(1)
340         
341         # If there is profile (SALOME), then define additional variables
342         if 'profile' in self.cfg.APPLICATION:
343             profile_product = self.cfg.APPLICATION.profile.product
344             product_info_profile = src.product.get_product_config(self.cfg,
345                                                             profile_product)
346             profile_share_salome = os.path.join(product_info_profile.install_dir,
347                                                 "share",
348                                                 "salome" )
349             self.set( "SUITRoot", profile_share_salome )
350             self.set( "SalomeAppConfig",
351                       os.path.join(profile_share_salome,
352                                    "resources",
353                                    profile_product.lower() ) )
354         
355         # The list of products to launch
356         lProductsName = self.get_names(self.cfg.APPLICATION.products.keys())
357         
358         self.set( "SALOME_MODULES",    ','.join(lProductsName))
359
360     def set_salome_minimal_product_env(self, product_info, logger):
361         """Sets the minimal environment for a SALOME product.
362            xxx_ROOT_DIR and xxx_SRC_DIR
363         
364         :param product_info Config: The product description
365         :param logger Logger: The logger instance to display messages        
366         """
367         # set root dir
368         root_dir = product_info.name + "_ROOT_DIR"
369         if not self.is_defined(root_dir):
370             if 'install_dir' in product_info and product_info.install_dir:
371                 self.set(root_dir, product_info.install_dir)
372             elif not self.silent:
373                 logger.write("  " + _("No install_dir for product %s\n") %
374                               product_info.name, 5)
375
376         # set source dir, unless no source dir
377         if not src.product.product_is_fixed(product_info):
378             src_dir = product_info.name + "_SRC_DIR"
379             if not self.is_defined(src_dir):
380                 self.set(src_dir, product_info.source_dir)
381
382     def set_salome_generic_product_env(self, product):
383         """Sets the generic environment for a SALOME product.
384         
385         :param product str: The product name    
386         """
387         # get the product descritption
388         pi = src.product.get_product_config(self.cfg, product)
389         # Construct XXX_ROOT_DIR
390         env_root_dir = self.get(pi.name + "_ROOT_DIR")
391         l_binpath_libpath = []
392
393         # create additional ROOT_DIR for CPP components
394         if 'component_name' in pi:
395             compo_name = pi.component_name
396             if compo_name + "CPP" == product:
397                 compo_root_dir = compo_name + "_ROOT_DIR"
398                 envcompo_root_dir = os.path.join(
399                             self.cfg.TOOLS.common.install_root, compo_name )
400                 self.set(compo_root_dir ,  envcompo_root_dir)
401                 bin_path = os.path.join(envcompo_root_dir, 'bin', 'salome')
402                 lib_path = os.path.join(envcompo_root_dir, 'lib', 'salome')
403                 l_binpath_libpath.append( (bin_path, lib_path) )
404
405         appliname = 'salome'
406         if (src.get_cfg_param(pi, 'product_type', 'SALOME').upper() 
407                             not in [ "SALOME", "SMESH_PLUGIN", "SAMPLE" ]):
408             appliname = ''
409
410         # Construct the paths to prepend to PATH and LD_LIBRARY_PATH and 
411         # PYTHONPATH
412         bin_path = os.path.join(env_root_dir, 'bin', appliname)
413         lib_path = os.path.join(env_root_dir, 'lib', appliname)
414         l_binpath_libpath.append( (bin_path, lib_path) )
415
416         for bin_path, lib_path in l_binpath_libpath:
417             if not self.forBuild:
418                 self.prepend('PATH', bin_path)
419                 if src.architecture.is_windows():
420                     self.prepend('PATH', lib_path)
421                 else :
422                     self.prepend('LD_LIBRARY_PATH', lib_path)
423
424             l = [ bin_path, lib_path,
425                   os.path.join(env_root_dir, self.python_lib0, appliname),
426                   os.path.join(env_root_dir, self.python_lib1, appliname)
427                 ]
428             self.prepend('PYTHONPATH', l)
429
430     def load_cfg_environment(self, cfg_env):
431         """Loads environment defined in cfg_env 
432         
433         :param cfg_env Config: A config containing an environment    
434         """
435         # Loop on cfg_env values
436         for env_def in cfg_env:
437             val = cfg_env[env_def]
438             
439             # if it is env_script, do not do anything (reserved keyword)
440             if env_def == "env_script":
441                 continue
442             
443             # if it is a dict, do not do anything
444             if isinstance(val, src.pyconf.Mapping):
445                 continue
446
447             # if it is a list, loop on its values
448             if isinstance(val, src.pyconf.Sequence):
449                 # transform into list of strings
450                 l_val = []
451                 for item in val:
452                     l_val.append(item)
453                 val = l_val
454
455             # "_" means that the value must be prepended
456             if env_def.startswith("_"):
457                 # separator exception for PV_PLUGIN_PATH
458                 if env_def[1:] == 'PV_PLUGIN_PATH':
459                     self.prepend(env_def[1:], val, ';')
460                 else:
461                     self.prepend(env_def[1:], val)
462             elif env_def.endswith("_"):
463                 # separator exception for PV_PLUGIN_PATH
464                 if env_def[:-1] == 'PV_PLUGIN_PATH':
465                     self.append(env_def[:-1], val, ';')
466                 else:
467                     self.append(env_def[:-1], val)
468             else:
469                 self.set(env_def, val)
470
471     def set_a_product(self, product, logger):
472         """Sets the environment of a product. 
473         
474         :param product str: The product name
475         :param logger Logger: The logger instance to display messages
476         """
477         
478         # Get the informations corresponding to the product
479         pi = src.product.get_product_config(self.cfg, product)
480         
481         # Do not define environment if the product is native
482         if src.product.product_is_native(pi):
483             return
484         
485         if not self.silent:
486             logger.write(_("Setting environment for %s\n") % product, 4)
487
488         self.add_line(1)
489         self.add_comment('setting environ for ' + product)
490
491         # Put the environment define in the configuration of the product
492         if "environ" in pi:
493             self.load_cfg_environment(pi.environ)
494             if self.forBuild and "build" in pi.environ:
495                 self.load_cfg_environment(pi.environ.build)
496             if not self.forBuild and "launch" in pi.environ:
497                 self.load_cfg_environment(pi.environ.launch)
498             # if product_info defines a env_scripts, load it
499             if 'env_script' in pi.environ:
500                 self.run_env_script(pi, logger)
501
502         # Set an additional environment for SALOME products
503         if src.product.product_is_salome(pi):
504             # set environment using definition of the product
505             self.set_salome_minimal_product_env(pi, logger)
506             self.set_salome_generic_product_env(product)
507             
508
509     def run_env_script(self, product_info, logger=None):
510         """Runs an environment script. 
511         
512         :param product_info Config: The product description
513         :param logger Logger: The logger instance to display messages
514         """
515         env_script = product_info.environ.env_script
516         # Check that the script exists
517         if not os.path.exists(env_script):
518             raise src.SatException(_("Environment script not found: %s") % 
519                                    env_script)
520
521         if not self.silent and logger is not None:
522             logger.write("  ** load %s\n" % env_script, 4)
523
524         # import the script and run the set_env function
525         try:
526             import imp
527             pyproduct = imp.load_source(product_info.name + "_env_script",
528                                         env_script)
529             pyproduct.set_env(self, product_info.install_dir,
530                               product_info.version)
531         except:
532             __, exceptionValue, exceptionTraceback = sys.exc_info()
533             print(exceptionValue)
534             import traceback
535             traceback.print_tb(exceptionTraceback)
536             traceback.print_exc()
537
538     def run_simple_env_script(self, script_path, logger=None):
539         """Runs an environment script. Same as run_env_script, but with a 
540            script path as parameter.
541         
542         :param script_path str: a path to an environment script
543         :param logger Logger: The logger instance to display messages
544         """
545         # Check that the script exists
546         if not os.path.exists(script_path):
547             raise src.SatException(_("Environment script not found: %s") % 
548                                    script_path)
549
550         if not self.silent and logger is not None:
551             logger.write("  ** load %s\n" % script_path, 4)
552
553         script_basename = os.path.basename(script_path)
554         if script_basename.endswith(".py"):
555             script_basename = script_basename[:-len(".py")]
556
557         # import the script and run the set_env function
558         try:
559             import imp
560             pyproduct = imp.load_source(script_basename + "_env_script",
561                                         script_path)
562             pyproduct.load_env(self)
563         except:
564             __, exceptionValue, exceptionTraceback = sys.exc_info()
565             print(exceptionValue)
566             import traceback
567             traceback.print_tb(exceptionTraceback)
568             traceback.print_exc()
569
570     def set_products(self, logger, src_root=None):
571         """Sets the environment for all the products. 
572         
573         :param logger Logger: The logger instance to display messages
574         :param src_root src: the application working directory
575         """
576         self.add_line(1)
577         self.add_comment('setting environ for all products')
578
579         self.set_python_libdirs()
580
581         # Set the application working directory
582         if src_root is None:
583             src_root = self.cfg.APPLICATION.workdir
584         self.set('SRC_ROOT', src_root)
585
586         # SALOME variables
587         appli_name = "APPLI"
588         if "APPLI" in self.cfg and "application_name" in self.cfg.APPLI:
589             appli_name = self.cfg.APPLI.application_name
590         self.set("SALOME_APPLI_ROOT",
591                  os.path.join(self.cfg.APPLICATION.workdir, appli_name))
592
593         # The loop on the products
594         for product in self.cfg.APPLICATION.products.keys():
595             self.set_a_product(product, logger)
596             self.finish(False)
597  
598     def set_full_environ(self, logger, env_info):
599         """Sets the full environment for products 
600            specified in env_info dictionary. 
601         
602         :param logger Logger: The logger instance to display messages
603         :param env_info list: the list of products
604         """
605         # set product environ
606         self.set_application_env(logger)
607
608         self.set_python_libdirs()
609
610         # set products        
611         for product in env_info:
612             self.set_a_product(product, logger)
613
614 class FileEnvWriter:
615     """Class to dump the environment to a file.
616     """
617     def __init__(self, config, logger, out_dir, src_root, env_info=None):
618         '''Initialization.
619
620         :param cfg Config: the global config
621         :param logger Logger: The logger instance to display messages
622         :param out_dir str: The directory path where t put the output files
623         :param src_root str: The application working directory
624         :param env_info str: The list of products to add in the files.
625         '''
626         self.config = config
627         self.logger = logger
628         self.out_dir = out_dir
629         self.src_root= src_root
630         self.silent = True
631         self.env_info = env_info
632
633     def write_env_file(self, filename, forBuild, shell):
634         """Create an environment file.
635         
636         :param filename str: the file path
637         :param forBuild bool: if true, the build environment
638         :param shell str: the type of file wanted (.sh, .bat)
639         :return: The path to the generated file
640         :rtype: str
641         """
642         if not self.silent:
643             self.logger.write(_("Create environment file %s\n") % 
644                               src.printcolors.printcLabel(filename), 3)
645
646         # create then env object
647         env_file = open(os.path.join(self.out_dir, filename), "w")
648         tmp = src.fileEnviron.get_file_environ(env_file,
649                                                shell,
650                                                {})
651         env = SalomeEnviron(self.config, tmp, forBuild)
652         env.silent = self.silent
653
654         # Set the environment
655         if self.env_info is not None:
656             env.set_full_environ(self.logger, self.env_info)
657         else:
658             # set env from the APPLICATION
659             env.set_application_env(self.logger)
660             # set the products
661             env.set_products(self.logger,
662                             src_root=self.src_root)
663
664         # add cleanup and close
665         env.finish(True)
666         env_file.close()
667
668         return env_file.name
669    
670     def write_cfgForPy_file(self, filename, additional_env = {}):
671         """Append to current opened aFile a cfgForPy 
672            environment (SALOME python launcher).
673            
674         :param filename str: the file path
675         :param additional_env dict: a dictionary of additional variables 
676                                     to add to the environment
677         """
678         if not self.silent:
679             self.logger.write(_("Create configuration file %s\n") % 
680                               src.printcolors.printcLabel(aFile.name), 3)
681
682         # create then env object
683         tmp = src.fileEnviron.get_file_environ(filename, 
684                                                "cfgForPy", 
685                                                {})
686         # environment for launch
687         env = SalomeEnviron(self.config, tmp, forBuild=False)
688         env.silent = self.silent
689
690         if self.env_info is not None:
691             env.set_full_environ(self.logger, self.env_info)
692         else:
693             # set env from PRODUCT
694             env.set_application_env(self.logger)
695
696             # set the products
697             env.set_products(self.logger,
698                             src_root=self.src_root)
699
700         # Add the additional environment if it is not empty
701         if len(additional_env) != 0:
702             for variable in additional_env:
703                 env.set(variable, additional_env[variable])
704
705         # add cleanup and close
706         env.finish(True)
707
708 class Shell:
709     """Definition of a Shell.
710     """
711     def __init__(self, name, extension):
712         '''Initialization.
713
714         :param name str: the shell name
715         :param extension str: the shell extension
716         '''
717         self.name = name
718         self.extension = extension
719
720 def load_environment(config, build, logger):
721     """Loads the environment (used to run the tests, for example).
722     
723     :param config Config: the global config
724     :param build bool: build environement if True
725     :param logger Logger: The logger instance to display messages
726     """
727     environ = SalomeEnviron(config, Environ(os.environ), build)
728     environ.set_application_env(logger)
729     environ.set_products(logger)
730     environ.finish(True)