Salome HOME
SMH: Fixes and patches from Paul.
[modules/kernel.git] / bin / runSalome.py
index 3586e5542292a14c356d83d2a240d1bad94c2ea8..8738ca5581f74e6efa5a017f6bcdd5d90eb797f4 100755 (executable)
 #!/usr/bin/env python
 
-usage="""USAGE: runSalome.py [options]
-
-[command line options] :
---help                        : affichage de l'aide
---gui                         : lancement du GUI
---logger                     : redirection des messages dans un fichier
---xterm                              : les serveurs ouvrent une fenêtre xterm et les messages sont affichés dans cette fenêtre
---modules=module1,module2,... : où modulen est le nom d'un module Salome à charger dans le catalogue
---containers=cpp,python,superv: lancement des containers cpp, python et de supervision
---killall                    : arrêt des serveurs de salome
-
- La variable d'environnement <modulen>_ROOT_DIR doit etre préalablement
- positionnée (modulen doit etre en majuscule).
- KERNEL_ROOT_DIR est obligatoire.
-"""
+import sys, os, string, glob, time, pickle
+import orbmodule
+
+process_id = {}
+
+# salome_subdir variable is used for composing paths like $KERNEL_ROOT_DIR/share/salome/resources, etc.
+# before moving to SUIT-based gui, instead of salome_subdir there was args['appname'] used.
+# but after - 'appname'  = "SalomeApp", so using it in making the subdirectory is an error.
+salome_subdir = "salome"
 
 # -----------------------------------------------------------------------------
-#
-# Fonction d'arrêt de salome
-#
 
-def killSalome():
-   print "arret des serveurs SALOME"
-   for pid, cmd in process_id.items():
-      print "arret du process %s : %s"% (pid, cmd[0])
-      try:
-       os.kill(pid,signal.SIGKILL)
-      except:
-         print "  ------------------ process %s : %s inexistant"% (pid, cmd[0])
-   print "arret du naming service"
-   os.system("killall -9 omniNames")
-   
+def add_path(directory, variable_name):
+    """Function helper to add environment variables"""
+    if not os.environ.has_key(variable_name):
+        os.environ[variable_name] = ""
+        pass
+    if os.path.exists(directory):
+        newpath=[]
+        for _dir in os.environ[variable_name].split(":"):
+            if os.path.exists(_dir):
+                if not os.path.samefile(_dir, directory):
+                  newpath.append(_dir)
+            else:
+                if os.path.abspath(_dir) != os.path.abspath(directory):
+                  newpath.append(_dir)
+            pass
+        import string
+        newpath[:0] = [ directory ]
+        newpath = string.join(newpath,":")
+        os.environ[variable_name] = newpath
+        if variable_name == "PYTHONPATH":
+            sys.path[:0] = [directory]
+
 # -----------------------------------------------------------------------------
-#
-# Fonction message
-#
 
-def message(code, msg=''):
-    if msg: print msg
-    sys.exit(code)
-
-import sys,os,string,glob,time,signal,pickle,getopt
-
-init_time=os.times()
-opts, args=getopt.getopt(sys.argv[1:], 'hmglxck:', ['help','modules=','gui','logger','xterm','containers=','killall'])
-modules_root_dir={}
-process_id={}
-liste_modules={}
-liste_containers={}
-with_gui=0
-with_logger=0
-with_xterm=0
-
-with_container_cpp=0
-with_container_python=0
-with_container_superv=0
-
-try:
-  for o, a in opts:
-    if o in ('-h', '--help'):
-      print usage
-      sys.exit(1)
-    elif o in ('-g', '--gui'):
-      with_gui=1
-    elif o in ('-l', '--logger'):
-      with_logger=1
-    elif o in ('-x', '--xterm'):
-      with_xterm=1
-    elif o in ('-m', '--modules'):
-      liste_modules = [x.upper() for x in a.split(',')]
-    elif o in ('-c', '--containers'):
-      liste_containers = [x.lower() for x in a.split(',')]
-      for r in liste_containers:
-        if r not in ('cpp', 'python', 'superv'):
-          message(1, 'Invalid -c/--containers option: %s' % a)
-      if 'cpp' in liste_containers:
-          with_container_cpp=1
-      else:
-          with_container_cpp=0
-      if 'python' in liste_containers:
-          with_container_python=1
-      else:
-          with_container_python=0
-      if 'superv' in liste_containers:
-          with_container_superv=1
-      else:
-          with_container_superv=0
-    elif o in ('-k', '--killall'):
-      filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict'
-      #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
-      found = 0
-      try:
-         fpid=open(filedict, 'r')
-        found = 1
-      except:
-         print "le fichier %s des process SALOME n'est pas accessible"% filedict
-
-      if found:
-         process_id=pickle.load(fpid)
-         fpid.close()
-         killSalome()
-        process_id={}
-         os.remove(filedict)
-       
-except getopt.error, msg:
-  print usage
-  sys.exit(1)
+def get_config():
+    """
+    Get list of modules, paths.
+    
+    Read args from launch configure xml file and command line options.
+    Check variables <module>_ROOT_DIR and set list of used modules.
+    Return args, modules_list, modules_root_dir    
+    """
+    
+    # read args from launch configure xml file and command line options
+    
+    import launchConfigureParser
+    args = launchConfigureParser.args
+    
+    # Check variables <module>_ROOT_DIR
+    # and set list of used modules (without KERNEL)
+
+    modules_list = []
+    if args.has_key("modules"):
+        modules_list += args["modules"]
+    # KERNEL must be last in the list to locate it at the first place in PATH 
+    modules_list[:0] = ["KERNEL"]
+    modules_list.reverse()
+
+    modules_root_dir = {}
+
+    to_remove_list=[]
+    for module in modules_list :
+        module_variable=module.upper()+"_ROOT_DIR"
+        if not os.environ.has_key(module_variable):
+            print "*******************************************************"
+            print "*"
+            print "* Environment variable",module_variable,"must be set"
+            print "* Module", module, "will be not available"
+            print "*"
+            print "********************************************************"
+            to_remove_list.append(module)
+            continue
+            pass
+        module_root_dir = os.environ[module_variable]
+        modules_root_dir[module]=module_root_dir
+
+    for to_remove in to_remove_list:
+        modules_list.remove(to_remove)
+
+    while "KERNEL" in modules_list:
+        modules_list.remove("KERNEL")
+        pass
+
+    if "SUPERV" in modules_list and not 'superv' in args['standalone']:
+        args['standalone'].append("superv")
+        pass
+   
+    return args, modules_list, modules_root_dir
 
 # -----------------------------------------------------------------------------
-#
-# Vérification des variables d'environnement
-#
-try:
-  kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
-  modules_root_dir["KERNEL"]=kernel_root_dir
-except:
-  print usage
-  sys.exit(1)
-
-for module in liste_modules :
-   try:
-      module=module.upper()
-      module_root_dir=os.environ[module +"_ROOT_DIR"]
-      modules_root_dir[module]=module_root_dir
-   except:
-      print usage
-      sys.exit(1)
-
-# il faut KERNEL en premier dans la liste des modules
-# - l'ordre des modules dans le catalogue sera identique
-# - la liste des modules presents dans le catalogue est exploitée pour charger les modules CORBA python,
-#   il faut charger les modules python du KERNEL en premier
-
-if "KERNEL" in liste_modules:liste_modules.remove("KERNEL")
-liste_modules[:0]=["KERNEL"]
-#print liste_modules
-#print modules_root_dir
-
-os.environ["SALOMEPATH"]=":".join(modules_root_dir.values())
-if "SUPERV" in liste_modules:with_container_superv=1
 
+def set_env(args, modules_list, modules_root_dir):
+    """Add to the PATH-variables modules specific paths"""
+    
+    python_version="python%d.%d" % sys.version_info[0:2]
+    modules_root_dir_list = []
+    modules_list = modules_list[:] + ["KERNEL"] 
+    for module in modules_list :
+        module_root_dir = modules_root_dir[module]
+        modules_root_dir_list[:0] = [module_root_dir]
+        add_path(os.path.join(module_root_dir,"lib",salome_subdir),
+                 "LD_LIBRARY_PATH")
+        add_path(os.path.join(module_root_dir,"bin",salome_subdir),
+                 "PATH")
+        if os.path.exists(module_root_dir + "/examples") :
+            add_path(os.path.join(module_root_dir,"examples"),
+                     "PYTHONPATH")
+        add_path(os.path.join(module_root_dir,"bin",salome_subdir),
+                 "PYTHONPATH")
+        add_path(os.path.join(module_root_dir,"lib",
+                              python_version,"site-packages",salome_subdir),
+                 "PYTHONPATH")
+        add_path(os.path.join(module_root_dir,"lib",salome_subdir),
+                 "PYTHONPATH")
+        add_path(os.path.join(module_root_dir,"lib",
+                              python_version,"site-packages",salome_subdir,
+                              "shared_modules"),
+                 "PYTHONPATH")
+
+    os.environ["SALOMEPATH"]=":".join(modules_root_dir_list)
+    
+    # special path for logger lib if needeed
+    
+    os.environ["SALOME_trace"]="local"
+    if args['file']:
+        os.environ["SALOME_trace"]=args['file'][0]
+    if args['logger']:
+        os.environ["SALOME_trace"]="with_logger"
+        locdir=os.environ['PWD']
+        libtracedir=os.path.join(locdir,"libSalomeTrace")
+        libtrace = os.path.join(modules_root_dir["KERNEL"],"lib",
+                                salome_subdir,
+                                "libSALOMELoggerClient.so.0.0.0")
+        libtraceln = os.path.join(libtracedir,"libSALOMELocalTrace.so")
+        aCommand = 'rm -rf ' + libtracedir + "; "
+        aCommand += 'mkdir ' + libtracedir + "; "
+        aCommand += 'ln -s ' + libtrace + " " + libtraceln + "; "
+        aCommand += 'ln -s ' + libtrace + " " + libtraceln + ".0; "
+        aCommand += 'ln -s ' + libtrace + " " + libtraceln + ".0.0.0; "
+        os.system(aCommand)
+        add_path(libtracedir, "LD_LIBRARY_PATH")
+
+    # set environment for SMESH plugins
+
+    if "SMESH" in modules_list:
+        os.environ["SMESH_MeshersList"]="StdMeshers"
+        if not os.environ.has_key("SALOME_StdMeshersResources"):
+            os.environ["SALOME_StdMeshersResources"] \
+            = modules_root_dir["SMESH"]+"/share/"+args["appname"]+"/resources"
+            pass
+        if args.has_key("SMESH_plugins"):
+            for plugin in args["SMESH_plugins"]:
+                if os.environ.has_key(plugin.upper()+"_ROOT_DIR"):
+                    os.environ["SMESH_MeshersList"] \
+                    = os.environ["SMESH_MeshersList"]+":"+plugin
+                    plugin_root = os.environ[plugin.upper()+"_ROOT_DIR"]
+                    if not os.environ.has_key("SALOME_"+plugin+"Resources"):
+                        os.environ["SALOME_"+plugin+"Resources"] \
+                        = plugin_root+"/share/"+args["appname"]+"/resources"
+                    add_path(os.path.join(plugin_root,"lib",python_version,
+                                          "site-packages",salome_subdir),
+                             "PYTHONPATH")
+                    add_path(os.path.join(plugin_root,"lib",salome_subdir),
+                             "PYTHONPATH")
+                    add_path(os.path.join(plugin_root,"lib",salome_subdir),
+                             "LD_LIBRARY_PATH")
+                    add_path(os.path.join(plugin_root,"bin",salome_subdir),
+                             "PYTHONPATH")
+                    add_path(os.path.join(plugin_root,"bin",salome_subdir),
+                             "PATH")
+            pass
+        pass
+
+    # set environment for SUPERV module
+    os.environ["ENABLE_MACRO_NODE"]="1"
+   
 
+# -----------------------------------------------------------------------------
+
+from killSalome import killAllPorts
+
+def killLocalPort():
+    """
+    kill servers from a previous SALOME exection, if needed,
+    on the CORBA port given in args of runSalome
+    """
+    
+    from killSalomeWithPort import killMyPort
+    my_port=str(args['port'])
+    try:
+        killMyPort(my_port)
+    except:
+        print "problem in killLocalPort()"
+        pass
+    pass
+    
+def givenPortKill(port):
+    """
+    kill servers from a previous SALOME exection, if needed,
+    on the same CORBA port
+    """
+    
+    from killSalomeWithPort import killMyPort
+    my_port=port
+    try:
+        killMyPort(my_port)
+    except:
+        print "problem in LocalPortKill(), killMyPort("<<port<<")"
+        pass
+    pass
+
+def kill_salome(args):
+    """
+    Kill servers from previous SALOME executions, if needed;
+    depending on args 'killall' or 'portkill', kill all executions,
+    or only execution on the same CORBA port
+    """
+
+    if args['killall']:
+        killAllPorts()
+    elif args['portkill']:
+        givenPortKill(str(args['port']))
+       
 # -----------------------------------------------------------------------------
 #
-# Définition des classes d'objets pour le lancement des Server CORBA
+# Definition des classes d'objets pour le lancement des Server CORBA
 #
 
 class Server:
-   CMD=[]
-   if with_xterm:
-       ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-e']
-   else:
-       ARGS=[] 
-
-   def run(self):
-      args = self.ARGS+self.CMD
-      #print "args = ", args
-      pid = os.spawnvp(os.P_NOWAIT, args[0], args)
-      process_id[pid]=self.CMD
+    """Generic class for CORBA server launch"""
+
+    def initArgs(self):
+        self.CMD=[]
+        self.ARGS=[]   
+        if self.args['xterm']:
+            self.ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-hold']
+
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+
+
+    def run(self):
+        global process_id
+        myargs=self.ARGS
+        if self.args['xterm']:
+            # (Debian) send LD_LIBRARY_PATH to children shells (xterm)
+            env_ld_library_path=['env', 'LD_LIBRARY_PATH='
+                                 + os.getenv("LD_LIBRARY_PATH")]
+            myargs = myargs +['-T']+self.CMD[:1]+['-e'] + env_ld_library_path
+        command = myargs + self.CMD
+        print "command = ", command
+        pid = os.spawnvp(os.P_NOWAIT, command[0], command)
+        process_id[pid]=self.CMD
+
+
+class InterpServer(Server):
+    def __init__(self,args):
+        self.args=args
+        env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
+        self.CMD=['xterm', '-e']+ env_ld_library_path + ['python']
+        #self.CMD=['xterm', '-e', 'python']
+       
+    def run(self):
+        global process_id
+        command = self.CMD
+        print "command = ", command
+        pid = os.spawnvp(os.P_NOWAIT, command[0], command)
+        process_id[pid]=self.CMD
+
+# ---
 
 class CatalogServer(Server):
-   SCMD1=['SALOME_ModuleCatalog_Server','-common']
-   SCMD2=['-personal','${HOME}/Salome/resources/CatalogModulePersonnel.xml'] 
-
-   def setpath(self,liste_modules):
-      cata_path=[]
-      for module in liste_modules:
-          module_root_dir=modules_root_dir[module]
-          module_cata=module+"Catalog.xml"
-          print "   ", module_cata
-          cata_path.extend(glob.glob(os.path.join(module_root_dir,"share","salome","resources",module_cata)))
-      self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.SCMD1=['SALOME_ModuleCatalog_Server','-common']
+        self.SCMD2=[]
+        home_dir=os.getenv('HOME')
+        if home_dir is not None:
+            self.SCMD2=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')] 
+
+    def setpath(self,modules_list,modules_root_dir):
+        cata_path=[]
+        list_modules = modules_list[:]
+        list_modules.reverse()
+        for module in ["KERNEL"] + list_modules:
+            module_root_dir=modules_root_dir[module]
+            module_cata=module+"Catalog.xml"
+            print "   ", module_cata
+            cata_path.extend(
+                glob.glob(os.path.join(module_root_dir,
+                                       "share",salome_subdir,
+                                       "resources",module_cata)))
+        self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
+
+# ---
 
 class SalomeDSServer(Server):
-   CMD=['SALOMEDS_Server']
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.CMD=['SALOMEDS_Server']
+
+# ---
 
 class RegistryServer(Server):
-   CMD=['SALOME_Registry_Server', '--salome_session','theSession']
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.CMD=['SALOME_Registry_Server', '--salome_session','theSession']
+
+# ---
 
 class ContainerCPPServer(Server):
-   CMD=['SALOME_Container','FactoryServer','-ORBInitRef','NameService=corbaname::localhost']
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.CMD=['SALOME_Container','FactoryServer']
+
+# ---
 
 class ContainerPYServer(Server):
-   CMD=['SALOME_ContainerPy.py','FactoryServerPy','-ORBInitRef','NameService=corbaname::localhost']
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.CMD=['SALOME_ContainerPy.py','FactoryServerPy']
+
+# ---
 
 class ContainerSUPERVServer(Server):
-   CMD=['SALOME_Container','SuperVisionContainer','-ORBInitRef','NameService=corbaname::localhost']
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.CMD=['SALOME_Container','SuperVisionContainer']
+
+# ---
 
 class LoggerServer(Server):
-   CMD=['SALOME_Logger_Server', 'logger.log']
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.CMD=['SALOME_Logger_Server', 'logger.log']
+
+# ---
 
 class SessionLoader(Server):
-   CMD=['SALOME_Session_Loader']
-   if with_container_cpp:
-       CMD=CMD+['CPP']
-   if with_container_python:
-       CMD=CMD+['PY']
-   if with_container_superv:
-       CMD=CMD+['SUPERV']
-   if with_gui:
-       CMD=CMD+['GUI']
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.CMD=['SALOME_Session_Loader']
+        if "cppContainer" in self.args['standalone'] \
+        or "cppContainer" in self.args['embedded']:
+            self.CMD=self.CMD+['CPP']
+        if "pyContainer" in self.args['standalone'] \
+        or "pyContainer" in self.args['embedded']:
+            self.CMD=self.CMD+['PY']
+        if "supervContainer" in self.args['containers'] \
+        or "supervContainer" in self.args['standalone']:
+            self.CMD=self.CMD+['SUPERV']
+        if self.args['gui']:
+            self.CMD=self.CMD+['GUI']
+        print self.CMD
+
+# ---
 
 class SessionServer(Server):
-   CMD=['SALOME_Session_Server']
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.SCMD1=['SALOME_Session_Server']
+        self.SCMD2=[]
+        if 'registry' in self.args['embedded']:
+            self.SCMD1+=['--with','Registry',
+                         '(','--salome_session','theSession',')']
+        if 'moduleCatalog' in self.args['embedded']:
+            self.SCMD1+=['--with','ModuleCatalog','(','-common']
+            home_dir=os.getenv('HOME')
+            if home_dir is not None:
+                self.SCMD2+=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')] 
+            self.SCMD2+=[')']
+        if 'study' in self.args['embedded']:
+            self.SCMD2+=['--with','SALOMEDS','(',')']
+        if 'cppContainer' in self.args['embedded']:
+            self.SCMD2+=['--with','Container','(','FactoryServer',')']
+        if 'SalomeAppEngine' in self.args['embedded']:
+            self.SCMD2+=['--with','SalomeAppEngine','(',')']
+
+    def setpath(self,modules_list,modules_root_dir):
+        cata_path=[]
+        list_modules = modules_list[:]
+        list_modules.reverse()
+        for module in ["KERNEL"] + list_modules:
+            module_root_dir=modules_root_dir[module]
+            module_cata=module+"Catalog.xml"
+            print "   ", module_cata
+            cata_path.extend(
+                glob.glob(os.path.join(module_root_dir,"share",
+                                       salome_subdir,"resources",
+                                       module_cata)))
+        if 'moduleCatalog' in self.args['embedded']:
+            self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
+        else:
+            self.CMD=self.SCMD1 + self.SCMD2
+
+      # arguments SALOME_Session_Server pour ddd
+        comm_ddd=""
+        for mot in self.CMD:
+            if mot == "(":
+                comm_ddd+='"(" '
+            elif mot == ")":
+                comm_ddd+='")" '
+            else:
+                comm_ddd+=mot+" "
+        print comm_ddd
+      
+# ---
+
+class ContainerManagerServer(Server):
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.SCMD1=['SALOME_ContainerManagerServer']
+        self.SCMD2=[]
+        if 'registry' in self.args['embedded']:
+            self.SCMD1+=['--with','Registry',
+                         '(','--salome_session','theSession',')']
+        if 'moduleCatalog' in self.args['embedded']:
+            self.SCMD1+=['--with','ModuleCatalog','(','-common']
+            self.SCMD2+=['-personal',
+                         '${HOME}/Salome/resources/CatalogModulePersonnel.xml',')']
+        if 'study' in self.args['embedded']:
+            self.SCMD2+=['--with','SALOMEDS','(',')']
+        if 'cppContainer' in self.args['embedded']:
+            self.SCMD2+=['--with','Container','(','FactoryServer',')']
+        
+    def setpath(self,modules_list,modules_root_dir):
+        cata_path=[]
+        list_modules = modules_list[:]
+        list_modules.reverse()
+        for module in ["KERNEL"] + list_modules:
+            module_root_dir=modules_root_dir[module]
+            module_cata=module+"Catalog.xml"
+            print "   ", module_cata
+            cata_path.extend(
+                glob.glob(os.path.join(module_root_dir,"share",
+                                       self.args['appname'],"resources",
+                                       module_cata)))
+        if 'moduleCatalog' in self.args['embedded']:
+            self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
+        else:
+            self.CMD=self.SCMD1 + self.SCMD2
 
 class NotifyServer(Server):
-   CMD=['notifd','-c','${KERNEL_ROOT_DIR}/share/salome/resources/channel.cfg -DFactoryIORFileName=/tmp/${LOGNAME}_rdifact.ior -DChannelIORFileName=/tmp/${LOGNAME}_rdichan.ior']
-
-# -----------------------------------------------------------------------------
-#
-# Fonction de test
-#
-
-def test(clt):
-   # create an LifeCycleCORBA instance
-   import LifeCycleCORBA 
-   lcc = LifeCycleCORBA.LifeCycleCORBA(clt.orb)
-   med = lcc.FindOrLoadComponent("FactoryServer", "MED")
-   #pycalc = lcc.FindOrLoadComponent("FactoryServerPy", "CalculatorPy")
-
-# -----------------------------------------------------------------------------
-#
-# Fonctions helper pour ajouter des variables d'environnement
-#
-
-def add_path(directory):
-   os.environ["PATH"]=directory + ":" + os.environ["PATH"]
-
-def add_ld_library_path(directory):
-   os.environ["LD_LIBRARY_PATH"]=directory + ":" + os.environ["LD_LIBRARY_PATH"]
-
-def add_python_path(directory):
-   os.environ["PYTHONPATH"]=directory + ":" + os.environ["PYTHONPATH"]
-   sys.path[:0]=[directory]
-
-# -----------------------------------------------------------------------------
-#
-# initialisation des variables d'environnement
-#
-
-python_version="python%d.%d" % sys.version_info[0:2]
-
-#
-# Ajout du chemin d'acces aux executables de KERNEL dans le PATH
-#
-
-add_path(os.path.join(kernel_root_dir,"bin","salome"))
-#print "PATH=",os.environ["PATH"]
-
-#
-# Ajout des modules dans le LD_LIBRARY_PATH
-#
-for module in liste_modules:
-    module_root_dir=modules_root_dir[module]
-    add_ld_library_path(os.path.join(module_root_dir,"lib","salome"))
-
-os.environ["SALOME_trace"]="local"
-if with_logger:
-   os.environ["SALOME_trace"]="with_logger"
-   locdir=os.environ['PWD']
-   libtracedir=os.path.join(locdir,"libSalomeTrace")
-   libtrace = os.path.join(kernel_root_dir,"lib","salome","libSALOMELoggerClient.so.0.0.0")
-   libtraceln = os.path.join(libtracedir,"libSALOMELocalTrace.so")
-   aCommand = 'rm -rf ' + libtracedir + "; "
-   aCommand += 'mkdir ' + libtracedir + "; "
-   aCommand += 'ln -s ' + libtrace + " " + libtraceln + "; "
-   aCommand += 'ln -s ' + libtrace + " " + libtraceln + ".0; "
-   aCommand += 'ln -s ' + libtrace + " " + libtraceln + ".0.0.0; "
-   os.system(aCommand)
-   add_ld_library_path(libtracedir)
-   
-#print "LD_LIBRARY_PATH=",os.environ["LD_LIBRARY_PATH"]
-
-#
-# Ajout des modules dans le PYTHONPATH (KERNEL prioritaire, donc en dernier)
-#
-
-liste_modules_reverse=liste_modules[:]
-liste_modules_reverse.reverse()
-#print liste_modules
-#print liste_modules_reverse
-for module in liste_modules_reverse:
-    module_root_dir=modules_root_dir[module]
-    add_python_path(os.path.join(module_root_dir,"bin","salome"))
-    add_python_path(os.path.join(module_root_dir,"lib",python_version,"site-packages","salome"))
-    add_python_path(os.path.join(module_root_dir,"lib","salome"))
-    add_python_path(os.path.join(module_root_dir,"lib",python_version,"site-packages","salome","shared_modules"))
-
-#print "PYTHONPATH=",sys.path
-
-import orbmodule
+    def __init__(self,args,modules_root_dir):
+        self.args=args
+        self.initArgs()
+        self.modules_root_dir=modules_root_dir
+        myLogName = os.environ["LOGNAME"]
+        self.CMD=['notifd','-c',
+                  self.modules_root_dir["KERNEL"] +'/share/salome/resources/channel.cfg',
+                  '-DFactoryIORFileName=/tmp/'+myLogName+'_rdifact.ior',
+                  '-DChannelIORFileName=/tmp/'+myLogName+'_rdichan.ior',
+                  '-DReportLogFile=/tmp/'+myLogName+'_notifd.report',
+                  '-DDebugLogFile=/tmp/'+myLogName+'_notifd.debug',
+                  ]
 
 #
 # -----------------------------------------------------------------------------
-#
 
 def startGUI():
-  import SALOME
-  session=clt.waitNS("/Kernel/Session",SALOME.Session)
-
-  #
-  # Activation du GUI de Session Server
-  #
-       
-  session.GetInterface()
+    """Salome Session Graphic User Interface activation"""
+    import SALOME
+    import SALOME_Session_idl
+    session=clt.waitNS("/Kernel/Session",SALOME.Session)
+    session.GetInterface()
   
-#
 # -----------------------------------------------------------------------------
-#
 
-def startSalome():
+def startSalome(args, modules_list, modules_root_dir):
+    """Launch all SALOME servers requested by args"""
+    init_time = os.times()
 
-  #
-  # Lancement Session Loader
-  #
+    #
+    # Lancement Session Loader
+    #
 
-  if with_gui:
-     SessionLoader().run()
+    print "startSalome ", args
+    
+    #if args['gui']:
+    #    myServer=SessionLoader(args)
+    #    myServer.run()
 
-  #
-  # Initialisation ORB et Naming Service
-  #
+    #
+    # Initialisation ORB et Naming Service
+    #
    
-  clt=orbmodule.client()
-
-  # (non obligatoire) Lancement Logger Server et attente de sa disponibilite dans le naming service
-  #
-
-  if with_logger:
-       LoggerServer().run()
-       clt.waitLogger("Logger")
-
-
-  #
-  # Lancement Registry Server
-  #
-
-  RegistryServer().run()
-
-  #
-  # Attente de la disponibilité du Registry dans le Naming Service
-  #
-
-  clt.waitNS("/Registry")
-
-  #
-  # Lancement Catalog Server
-  #
-
-  cataServer=CatalogServer()
-  cataServer.setpath(liste_modules)
-  cataServer.run()
-
-  #
-  # Attente de la disponibilité du Catalog Server dans le Naming Service
-  #
-
-  import SALOME_ModuleCatalog
-  clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
-
-  #
-  # Lancement SalomeDS Server
-  #
-
-  os.environ["CSF_PluginDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
-  os.environ["CSF_SALOMEDS_ResourcesDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
-  SalomeDSServer().run()
-
-  if "GEOM" in liste_modules:
-       print "GEOM OCAF Resources"
-       os.environ["CSF_GEOMDS_ResourcesDefaults"]=os.path.join(modules_root_dir["GEOM"],"share","salome","resources")
-
-
-  #
-  # Attente de la disponibilité du SalomeDS dans le Naming Service
-  #
-
-  clt.waitNS("/myStudyManager")
-
-  #
-  # Lancement Session Server
-  #
-
-  SessionServer().run()
-
-  #
-  # Attente de la disponibilité du Session Server dans le Naming Service
-  #
+    clt=orbmodule.client()
+
+    # (non obligatoire) Lancement Logger Server
+    # et attente de sa disponibilite dans le naming service
+    #
+
+    if args['logger']:
+        myServer=LoggerServer(args)
+        myServer.run()
+        clt.waitLogger("Logger")
+
+    # Notify Server launch
+    #
+
+    print "Notify Server to launch"
+
+    myServer=NotifyServer(args,modules_root_dir)
+    myServer.run()
+
+    #
+    # Lancement Registry Server,
+    # attente de la disponibilite du Registry dans le Naming Service
+    #
+
+    if 'registry' not in args['embedded']:
+        myServer=RegistryServer(args)
+        myServer.run()
+        clt.waitNS("/Registry")
+
+    #
+    # Lancement Catalog Server,
+    # attente de la disponibilite du Catalog Server dans le Naming Service
+    #
+    
+
+    if 'moduleCatalog' not in args['embedded']:
+        cataServer=CatalogServer(args)
+        cataServer.setpath(modules_list,modules_root_dir)
+        cataServer.run()
+        import SALOME_ModuleCatalog
+        clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
+
+    #
+    # Lancement SalomeDS Server,
+    # attente de la disponibilite du SalomeDS dans le Naming Service
+    #
+
+    os.environ["CSF_PluginDefaults"] \
+    = os.path.join(modules_root_dir["KERNEL"],"share",
+                   salome_subdir,"resources")
+    os.environ["CSF_SALOMEDS_ResourcesDefaults"] \
+    = os.path.join(modules_root_dir["KERNEL"],"share",
+                   salome_subdir,"resources")
+
+    if "GEOM" in modules_list:
+        print "GEOM OCAF Resources"
+        os.environ["CSF_GEOMDS_ResourcesDefaults"] \
+        = os.path.join(modules_root_dir["GEOM"],"share",
+                       salome_subdir,"resources")
+       print "GEOM Shape Healing Resources"
+        os.environ["CSF_ShHealingDefaults"] \
+        = os.path.join(modules_root_dir["GEOM"],"share",
+                       salome_subdir,"resources")
+
+    print "ARGS = ",args
+    if 'study' not in args['embedded']:
+        print "RunStudy"
+        myServer=SalomeDSServer(args)
+        myServer.run()
+        clt.waitNS("/myStudyManager")
+
+    #
+    # Lancement ContainerManagerServer
+    #
+    
+    myCmServer = ContainerManagerServer(args)
+    myCmServer.setpath(modules_list,modules_root_dir)
+    myCmServer.run()
+
+
+    from Utils_Identity import getShortHostName
+    
+    if os.getenv("HOSTNAME") == None:
+        if os.getenv("HOST") == None:
+            os.environ["HOSTNAME"]=getShortHostName()
+        else:
+            os.environ["HOSTNAME"]=os.getenv("HOST")
+
+    theComputer = getShortHostName()
+    
+    #
+    # Lancement Container C++ local,
+    # attente de la disponibilite du Container C++ local dans le Naming Service
+    #
+
+    if 'cppContainer' in args['standalone']:
+        myServer=ContainerCPPServer(args)
+        myServer.run()
+        clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
+
+    #
+    # Lancement Container Python local,
+    # attente de la disponibilite du Container Python local
+    # dans le Naming Service
+    #
+
+    if 'pyContainer' in args['standalone']:
+        myServer=ContainerPYServer(args)
+        myServer.run()
+        clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy")
+
+    #
+    # Lancement Container Supervision local,
+    # attente de la disponibilite du Container Supervision local
+    # dans le Naming Service
+    #
+
+    if 'supervContainer' in args['standalone']:
+        myServer=ContainerSUPERVServer(args)
+        myServer.run()
+        clt.waitNS("/Containers/" + theComputer + "/SuperVisionContainer")
+##----------------        
+
+    #
+    # Lancement Session Server
+    #
+    mySessionServ = SessionServer(args)
+    mySessionServ.setpath(modules_list,modules_root_dir)
+    mySessionServ.run()
+
+    #macomm2=['ddd']
+    #pid = os.spawnvp(os.P_NOWAIT, macomm2[0], macomm2)
+    #
+    # Attente de la disponibilite du Session Server dans le Naming Service
+    #
+
+    import SALOME
+    import SALOME_Session_idl
+    session=clt.waitNS("/Kernel/Session",SALOME.Session)
+
+    end_time = os.times()
+    print
+    print "Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
+                                                         - init_time[4])
+
+    # ASV start GUI without Loader
+    if args['gui']:
+        session.GetInterface()
+
+
+    #
+    # additionnal external python interpreters
+    #
+    nbaddi=0
+    
+    try:
+        if 'interp' in args:
+            if args['interp']:
+                nbaddi = int(args['interp'][0])
+    except:
+        import traceback
+        traceback.print_exc()
+        print "-------------------------------------------------------------"
+        print "-- to get an external python interpreter:runSalome --interp=1"
+        print "-------------------------------------------------------------"
+        
+    print "additional external python interpreters: ", nbaddi
+    if nbaddi:
+        for i in range(nbaddi):
+            print "i=",i
+            anInterp=InterpServer(args)
+            anInterp.run()
+    
+    return clt
 
-  import SALOME
-  session=clt.waitNS("/Kernel/Session",SALOME.Session)
-
-  if os.getenv("HOSTNAME") == None:
-     if os.getenv("HOST") == None:
-        os.environ["HOSTNAME"]="localhost"
-     else:
-        os.environ["HOSTNAME"]=os.getenv("HOST")
-  
-  theComputer = os.getenv("HOSTNAME")
-  computerSplitName = theComputer.split('.')
-  theComputer = computerSplitName[0]
-  
-  #
-  # Lancement Container C++ local
-  #
-  if with_container_cpp:
-         ContainerCPPServer().run()
-
-         #
-         # Attente de la disponibilité du Container C++ local dans le Naming Service
-         #
-
-         clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
-
-  #
-  # Lancement Container Python local
-  #
-
-  if with_container_python:
-         ContainerPYServer().run()
-
-         #
-         # Attente de la disponibilité du Container Python local dans le Naming Service
-         #
-       
-         clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy")
-
-  if with_container_superv:
-
-       #
-       # Lancement Container Supervision local
-       #
+# -----------------------------------------------------------------------------
 
-       ContainerSUPERVServer().run()
+def useSalome(args, modules_list, modules_root_dir):
+    """
+    Launch all SALOME servers requested by args,
+    save list of process, give info to user,
+    show registered objects in Naming Service.
+    """
+    
+    clt=None
+    try:
+        clt = startSalome(args, modules_list, modules_root_dir)
+    except:
+        import traceback
+        traceback.print_exc()
+        print
+        print
+        print "--- erreur au lancement Salome ---"
+        
+    #print process_id
+    
+#    filedict = '/tmp/' + os.getenv('USER') + "_" + str(args['port']) \
+#             + '_' + args['appname'].upper() + '_pidict'
+# replaced args['appname'] by "SALOME" because in killSalome.py use of 'SALOME' in file name is hardcoded.
+    filedict = os.getenv("HOME") + '/' + os.getenv('USER') + "_" + str(args['port']) \
+               + '_' + 'SALOME' + '_pidict'   
+    process_ids = []
+    try:
+        fpid=open(filedict, 'r')
+        process_ids=pickle.load(fpid)
+        fpid.close()
+    except:
+        pass
+    
+    fpid=open(filedict, 'w')
+    process_ids.append(process_id)
+    pickle.dump(process_ids,fpid)
+    fpid.close()
+    
+    print """
+    Saving of the dictionary of Salome processes in %s
+    To kill SALOME processes from a console (kill all sessions from all ports):
+      python killSalome.py 
+    To kill SALOME from the present interpreter, if it is not closed :
+      killLocalPort()      --> kill this session
+                               (use CORBA port from args of runSalome)
+      givenPortKill(port)  --> kill a specific session with given CORBA port 
+      killAllPorts()       --> kill all sessions
+    
+    runSalome, with --killall option, starts with killing
+    the processes resulting from the previous execution.
+    """%filedict
+    
+    #
+    #  Impression arborescence Naming Service
+    #
+    
+    if clt != None:
+        print
+        print " --- registered objects tree in Naming Service ---"
+        clt.showNS()
+
+    return clt
 
-       #
-       # Attente de la disponibilité du Container Supervision local dans le Naming Service
-       #
+# -----------------------------------------------------------------------------
 
-       clt.waitNS("/Containers/" + theComputer + "/SuperVisionContainer")
+def registerEnv(args, modules_list, modules_root_dir):
+    """
+    Register args, modules_list, modules_root_dir in a file
+    for further use, when SALOME is launched embedded in an other application.
+    """
+    fileEnv = '/tmp/' + os.getenv('USER') + "_" + str(args['port']) \
+            + '_' + args['appname'].upper() + '_env'
+    fenv=open(fileEnv,'w')
+    pickle.dump((args, modules_list, modules_root_dir),fenv)
+    fenv.close()
+    os.environ["SALOME_LAUNCH_CONFIG"] = fileEnv
 
+# -----------------------------------------------------------------------------
 
-  #
-  # Activation du GUI de Session Server
-  #
-       
-  #session.GetInterface()
+def no_main():
+    """Salome Launch, when embedded in other application"""
+    fileEnv = os.environ["SALOME_LAUNCH_CONFIG"]
+    fenv=open(fileEnv,'r')
+    args, modules_list, modules_root_dir = pickle.load(fenv)
+    fenv.close()
+    kill_salome(args)
+    clt = useSalome(args, modules_list, modules_root_dir)
+    return clt
 
-  end_time = os.times()
-  print
-  print "Start SALOME, elpased time : %5.1f seconds"% (end_time[4] - init_time[4])
+# -----------------------------------------------------------------------------
 
-  return clt
+def main():
+    """Salome launch as a main application"""
+    args, modules_list, modules_root_dir = get_config()
+    kill_salome(args)
+    set_env(args, modules_list, modules_root_dir)
+    clt = useSalome(args, modules_list, modules_root_dir)
+    return clt,args
 
-#
 # -----------------------------------------------------------------------------
-#
 
 if __name__ == "__main__":
-   clt=None
-   try:
-      clt = startSalome()
-   except:
-      print
-      print
-      print "--- erreur au lancement Salome ---"
-   
-   #print process_id
-   
-   
-   filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict'
-   #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
-   
-   fpid=open(filedict, 'w')
-   pickle.dump(process_id,fpid)
-   fpid.close()
-   
-   print
-   print "Sauvegarde du dictionnaire des process dans ", filedict
-   print "Pour tuer les process SALOME, executer : python killSalome.py depuis"
-   print "une console, ou bien killSalome() depuis le present interpreteur,"
-   print "s'il n'est pas fermé."
-   print
-   print "runSalome, avec l'option --killall, commence par tuer les process restants d'une execution précédente."
-   print
-   print "Pour lancer uniquement le GUI, executer startGUI() depuis le present interpreteur,"
-   print "s'il n'est pas fermé."
-   
-   #
-   #  Impression arborescence Naming Service
-   #
-   
-   if clt != None:
-     print
-     print " --- registered objects tree in Naming Service ---"
-     clt.showNS()
-   
+   import user
+   clt,args = main()