]> SALOME platform Git repositories - modules/kernel.git/commitdiff
Salome HOME
SSL mode by default mode
authorAnthony Geay <anthony.geay@edf.fr>
Tue, 15 Feb 2022 10:32:47 +0000 (11:32 +0100)
committerAnthony Geay <anthony.geay@edf.fr>
Thu, 17 Feb 2022 15:51:29 +0000 (16:51 +0100)
25 files changed:
bin/CMakeLists.txt
bin/addToKillList.py
bin/appliskel/salome_tester/salome_instance.py
bin/launchConfigureParser.py
bin/runSalome.py
bin/runSalomeCommon.py [new file with mode: 0755]
bin/runSalomeNoServer.py
bin/runSalomeOld.py [new file with mode: 0755]
bin/runSalomeSL.py [deleted file]
bin/salomeContext.py
src/Basics/KernelBasis.cxx
src/KERNEL_PY/__init__.py
src/KernelHelpers/Test/KernelHelpersUnitTests.cxx
src/KernelHelpers/Test/TestKernelHelpers.py
src/Launcher/Launcher_Job_PythonSALOME.cxx
src/Launcher/Launcher_Job_SALOME.cxx
src/LifeCycleCORBA/Test/TestLifeCycleCORBA.py
src/LifeCycleCORBA_SWIG/Test/TestLifeCycleCORBA_SWIG.py
src/NamingService/Test/TestNamingService.py
src/SALOMEDS/Test/TestSALOMEDS.py
src/SALOMEDSImpl/Test/TestSALOMEDSImpl.py
src/SALOMELocalTrace/Test/TestSALOMELocalTrace.py
src/SALOMETraceCollector/Test/TestSALOMETraceCollector.py
src/UnitTests/UnitTests.py
src/Utils/Test/TestUtils.py

index e5bb5279b685228fbbaba5ac17318230c728d910..16d8f13c84bb9fee3b8b0006acac4df155759567 100644 (file)
@@ -45,8 +45,9 @@ SET(SCRIPTS
   ORBConfigFile.py
   parseConfigFile.py
   PortManager.py
+  runSalomeCommon.py
   runSalome.py
-  runSalomeSL.py
+  runSalomeOld.py
   runSalomeNoServer.py
   runSession.py
   runConsole.py
index 3f892e77283ea9441fb1ef3a4050bd8588eaedbd..e306ccdd9a628eebf25666d50856a960a43a36ae 100755 (executable)
@@ -120,7 +120,8 @@ def killList(port=None):
             pass
         pass
     # remove processes dictionary file
-    os.remove(filedict)
+    if os.path.exists(filedict):
+        os.remove(filedict)
     pass
 
 if __name__ == "__main__":
index 2eaf70d3ef976b41b1c5c6f3b7ba18f2766c51f5..df7e432374680e19cf2804190f44b7f3fdf03b04 100755 (executable)
@@ -27,6 +27,8 @@ import os
 class SalomeInstance:
 
   def __init__(self):
+    import KernelBasis
+    KernelBasis.setSSLMode(False)
     self.port = None
   #
 
@@ -63,7 +65,7 @@ class SalomeInstance:
     if args is None:
       args = []
 
-    sys.argv = ['runSalome'] + args
+    sys.argv = ['runSalomeOld'] + args
 
     if with_gui:
       # :WARNING: NOT TESTED YET
@@ -80,8 +82,8 @@ class SalomeInstance:
 
     import setenv
     setenv.main(True)
-    import runSalome
-    runSalome.runSalome()
+    import runSalomeOld
+    runSalomeOld.runSalome()
 
     if not with_gui:
       import salome
index c7eb5157c304bbb69e3f986180d6a6944ae64efb..7b24312a56dfe3a3f08041f487dd15c3b1069b76 100644 (file)
@@ -84,6 +84,7 @@ useport_nam    = "useport"
 salomecfgname  = "salome"
 salomeappname  = "SalomeApp"
 script_nam     = "pyscript"
+verbosity_nam  = "verbosity"
 
 # possible choices for the "embedded" and "standalone" parameters
 embedded_choices   = [ "registry", "study", "moduleCatalog", "cppContainer", "SalomeAppEngine" ]
@@ -817,6 +818,16 @@ Python file arguments, if any, must be comma-separated (without blank characters
                       dest="language",
                       help=help_str)
 
+    # Verbosity
+    help_str  = "Level of verbosity"
+    pars.add_argument("-V",
+                      "--verbose",
+                      metavar="<2/1/0>",
+                      dest="verbosity",
+                      default="0",
+                      help=help_str)
+
+
     # Positional arguments (hdf file, python file)
     pars.add_argument("arguments", nargs=argparse.REMAINDER)
 
@@ -1034,6 +1045,8 @@ def get_env(appname=salomeappname, cfgname=salomecfgname, exeName=None, keepEnvi
         #
         args[script_nam] = new_args
 
+    args[verbosity_nam] = cmd_opts.verbosity
+
     # xterm
     if cmd_opts.xterm is not None:
         args[xterm_nam] = cmd_opts.xterm
index 619f4dc3b8ce12f64402a104718f3112f480d77c..bd0a5bcaf78337638de4a13ee3cf354f4869044b 100755 (executable)
@@ -1,9 +1,6 @@
 #!/usr/bin/env python3
 #  -*- coding: iso-8859-1 -*-
-# Copyright (C) 2007-2021  CEA/DEN, EDF R&D, OPEN CASCADE
-#
-# Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-# CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
+# Copyright (C) 2022 CEA/DEN, EDF R&D
 #
 # This library is free software; you can redistribute it and/or
 # modify it under the terms of the GNU Lesser General Public
 import sys, os, string, glob, time, pickle, re
 import orbmodule
 import setenv
-from launchConfigureParser import verbose
 from server import process_id, Server
 import json
 import subprocess
 from salomeContextUtils import ScriptAndArgsObjectEncoder
+import runSalomeNoServer
+import runSalomeCommon
 import platform
+import logging
+logger = logging.getLogger()
 
 # -----------------------------------------------------------------------------
 
 from killSalome import killAllPorts
 
-def killLocalPort():
-    """
-    kill servers from a previous SALOME execution, 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 Exception:
-        print("problem in killLocalPort()")
-        pass
-    pass
-
-def givenPortKill(port):
-    """
-    kill servers from a previous SALOME execution, if needed,
-    on the same CORBA port
-    """
-
-    from killSalomeWithPort import killMyPort
-    my_port=port
-    try:
-        killMyPort(my_port)
-    except Exception:
-        print("problem in LocalPortKill(), killMyPort(%s)"%port)
-        pass
-    pass
-
 def kill_salome(args):
     """
     Kill servers from previous SALOME executions, if needed;
@@ -79,355 +49,6 @@ def kill_salome(args):
 
     if args['killall']:
         killAllPorts()
-    elif args['portkill']:
-        givenPortKill(str(args['port']))
-
-# -----------------------------------------------------------------------------
-#
-# Class definitions to launch CORBA Servers
-#
-
-class InterpServer(Server):
-    def __init__(self,args):
-        self.args=args
-        if sys.platform == "win32":
-          self.CMD=['cmd', '/c', 'start cmd.exe', '/K', 'python']
-        elif sys.platform == "darwin":
-          env_ld_library_path=['env', 'DYLD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
-          self.CMD=['xterm', '-e'] + env_ld_library_path + ['python']
-        else:
-          env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
-          self.CMD=['xterm', '-e'] + env_ld_library_path + ['python']
-
-    def run(self):
-        global process_id
-        command = self.CMD
-        print("INTERPSERVER::command = ", command)
-        import subprocess
-        pid = subprocess.Popen(command).pid
-        process_id[pid]=self.CMD
-        self.PID = pid
-
-# ---
-
-def get_cata_path(list_modules,modules_root_dir):
-    """Build a list of catalog paths (cata_path) to initialize the ModuleCatalog server
-    """
-    modules_cata={}
-    cata_path=[]
-
-    for module in list_modules:
-        if module in modules_root_dir:
-            module_root_dir=modules_root_dir[module]
-            module_cata=module+"Catalog.xml"
-            cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources",module.lower(), module_cata)
-
-            if os.path.exists(cata_file):
-                cata_path.append(cata_file)
-                modules_cata[module]=cata_file
-            else:
-                cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources", module_cata)
-                if os.path.exists(cata_file):
-                    cata_path.append(cata_file)
-                    modules_cata[module]=cata_file
-
-    for path in os.getenv("SALOME_CATALOGS_PATH","").split(os.pathsep):
-        if os.path.exists(path):
-            for cata_file in glob.glob(os.path.join(path,"*Catalog.xml")):
-                module_name= os.path.basename(cata_file)[:-11]
-                if module_name not in modules_cata:
-                    cata_path.append(cata_file)
-                    modules_cata[module_name]=cata_file
-
-    return cata_path
-
-class CatalogServer(Server):
-    def __init__(self,args):
-        self.args=args
-        self.initArgs()
-        self.SCMD1=['SALOME_ModuleCatalog_Server']
-        if 'launcher' in self.args:
-            pos = args['launcher'].find(":")
-            if pos != -1:
-              self.SCMD1+=['-ORBInitRef']
-              machine = args['launcher'][0:pos]
-              port = args['launcher'][pos+1:]
-              self.SCMD1+=["NameService=corbaname::" + machine + ":" + port]
-        self.SCMD1+=['-common']
-        self.SCMD2=[]
-        home_dir=os.path.expanduser("~")
-        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):
-        list_modules = modules_list[:]
-        list_modules.reverse()
-        if self.args["gui"] :
-            list_modules = ["KERNEL", "GUI"] + list_modules
-        else :
-            list_modules = ["KERNEL"] + list_modules
-
-        cata_path=get_cata_path(list_modules,modules_root_dir)
-
-        self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
-
-# ---
-
-class SalomeDSServer(Server):
-    def __init__(self,args):
-        self.args=args
-        self.initArgs()
-        self.CMD=['SALOMEDS_Server']
-        if 'launcher' in self.args:
-            pos = args['launcher'].find(":")
-            if pos != -1:
-              self.CMD+=['-ORBInitRef']
-              machine = args['launcher'][0:pos]
-              port = args['launcher'][pos+1:]
-              self.CMD+=["NameService=corbaname::" + machine + ":" + port]
-
-# ---
-
-class ConnectionManagerServer(Server):
-    def __init__(self,args):
-        self.args=args
-        self.initArgs()
-        self.CMD=['SALOME_ConnectionManagerServer']
-        if 'launcher' in self.args:
-            pos = args['launcher'].find(":")
-            if pos != -1:
-              self.CMD+=['-ORBInitRef']
-              machine = args['launcher'][0:pos]
-              port = args['launcher'][pos+1:]
-              self.CMD+=["NameService=corbaname::" + machine + ":" + port]
-
-
-# ---
-
-class RegistryServer(Server):
-    def __init__(self,args):
-        self.args=args
-        self.initArgs()
-        self.CMD=['SALOME_Registry_Server', '--salome_session','theSession']
-        if 'launcher' in self.args:
-            pos = args['launcher'].find(":")
-            if pos != -1:
-              self.CMD+=['-ORBInitRef']
-              machine = args['launcher'][0:pos]
-              port = args['launcher'][pos+1:]
-              self.CMD+=["NameService=corbaname::" + machine + ":" + port]
-
-# ---
-
-class ContainerCPPServer(Server):
-    def __init__(self,args,with_gui=False):
-        self.args=args
-        self.initArgs()
-        self.CMD=['SALOME_Container']
-        if 'launcher' in self.args:
-            pos = args['launcher'].find(":")
-            if pos != -1:
-              self.CMD+=['-ORBInitRef']
-              machine = args['launcher'][0:pos]
-              port = args['launcher'][pos+1:]
-              self.CMD+=["NameService=corbaname::" + machine + ":" + port]
-        self.CMD+=['FactoryServer']
-        if not with_gui and self.args["valgrind_session"]:
-            l = ["valgrind"]
-            val = os.getenv("VALGRIND_OPTIONS")
-            if val:
-                l += val.split()
-                pass
-            self.CMD = l + self.CMD
-            pass
-
-# ---
-
-class LoggerServer(Server):
-    def __init__(self,args):
-        self.args=args
-        self.initArgs()
-        from salome_utils import generateFileName, getLogDir
-        logfile = generateFileName( getLogDir(),
-                                    prefix="logger",
-                                    extension="log",
-                                    with_username=True,
-                                    with_hostname=True,
-                                    with_port=True)
-        print("===========================================================")
-        print("Logger server: put log to the file:")
-        print(logfile)
-        print("===========================================================")
-        self.CMD=['SALOME_Logger_Server', logfile]
-        pass
-    pass # end of LoggerServer class
-
-# ---
-
-class SessionServer(Server):
-    def __init__(self,args,modules_list,modules_root_dir):
-        self.args = args.copy()
-        # Bug 11512 (Problems with runSalome --xterm on Mandrake and Debian Sarge)
-        #self.args['xterm']=0
-        #
-        self.initArgs()
-        self.SCMD1=['SALOME_Session_Server']
-        if "SQUISH_PREFIX" in os.environ:
-            if platform.system() == "Windows" :
-                self.SCMD1 = [os.path.join(os.getenv("SQUISH_PREFIX"), "bin", "dllpreload.exe"),os.path.join(os.getenv("SQUISH_SALOME_PATH"), "W64", "GUI", "bin", "salome", self.SCMD1[0])]
-            else :
-                os.environ["LD_LIBRARY_PATH"] = os.environ["SQUISH_PREFIX"] + "/lib:" + os.environ["LD_LIBRARY_PATH"]
-        self.SCMD2=[]
-        if 'launcher' in self.args:
-            pos = args['launcher'].find(":")
-            if pos != -1:
-              self.SCMD1+=['-ORBInitRef']
-              machine = args['launcher'][0:pos]
-              port = args['launcher'][pos+1:]
-              self.SCMD1+=["NameService=corbaname::" + machine + ":" + port]
-        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.path.expanduser("~")
-            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','(',')']
-
-        if 'cppContainer' in self.args['standalone'] or 'cppContainer' in self.args['embedded']:
-            self.SCMD2+=['CPP']
-        if 'pyContainer' in self.args['standalone'] or 'pyContainer' in self.args['embedded']:
-            raise Exception('Python containers no longer supported')
-        if self.args['gui']:
-            session_gui = self.args.get('session_gui', True)
-            if not session_gui:
-                self.SCMD2+=['--hide-desktop']
-            else:
-                if not self.args['splash']:
-                    self.SCMD2+=['--hide-splash']
-                    pass
-                if self.args['study_hdf'] is not None:
-                    self.SCMD2+=['--study-hdf=%s'%self.args['study_hdf']]
-                    pass
-                pass
-                if 'pyscript' in self.args and len(self.args['pyscript']) > 0:
-                    msg = json.dumps(self.args['pyscript'], cls=ScriptAndArgsObjectEncoder)
-                    self.SCMD2+=['--pyscript=%s'%(msg)]
-                    pass
-                pass
-            pass
-        if self.args['noexcepthandler']:
-            self.SCMD2+=['--no-exception-handler']
-        if 'user_config' in self.args:
-            self.SCMD2+=['--resources=%s'%self.args['user_config']]
-        if 'modules' in self.args:
-            list_modules = []
-            #keep only modules with GUI
-            for m in modules_list:
-              if m not in modules_root_dir:
-                list_modules.insert(0,m)
-              else:
-                fr1 = os.path.join(modules_root_dir[m],"share","salome","resources",m.lower(),"SalomeApp.xml")
-                fr2 = os.path.join(modules_root_dir[m],"share","salome","resources","SalomeApp.xml")
-                if os.path.exists(fr1) or os.path.exists(fr2):
-                  list_modules.insert(0,m)
-            list_modules.reverse()
-            self.SCMD2+=['--modules (%s)' % ":".join(list_modules)]
-            pass
-        if 'language' in self.args:
-            self.SCMD2+=['--language=%s' % self.args['language']]
-        pass
-
-    def setpath(self,modules_list,modules_root_dir):
-        list_modules = modules_list[:]
-        list_modules.reverse()
-        if self.args["gui"] :
-            list_modules = ["KERNEL", "GUI"] + list_modules
-        else :
-            list_modules = ["KERNEL"] + list_modules
-
-        cata_path=get_cata_path(list_modules,modules_root_dir)
-
-        if ("gui" in self.args) & ('moduleCatalog' in self.args['embedded']):
-            #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
-            self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
-        else:
-            self.CMD=self.SCMD1 + self.SCMD2
-        if 'test' in self.args:
-            self.CMD+=['-test'] + self.args['test']
-        elif 'play' in self.args:
-            self.CMD+=['-play'] + self.args['play']
-
-        if self.args["gdb_session"] or self.args["ddd_session"]:
-            f = open(".gdbinit4salome", "w")
-            f.write("set args ")
-            args = " ".join(self.CMD[1:])
-            args = args.replace("(", "\(")
-            args = args.replace(")", "\)")
-            f.write(args)
-            f.write("\n")
-            f.close()
-            if self.args["ddd_session"]:
-                self.CMD = ["ddd", "--command=.gdbinit4salome", self.CMD[0]]
-            elif self.args["gdb_session"]:
-                self.CMD = ["xterm", "-e", "gdb", "--command=.gdbinit4salome", self.CMD[0]]
-                pass
-            pass
-
-        if self.args["valgrind_session"]:
-            l = ["valgrind"]
-            val = os.getenv("VALGRIND_OPTIONS")
-            if val:
-                l += val.split()
-                pass
-            self.CMD = l + self.CMD
-            pass
-
-# ---
-
-class LauncherServer(Server):
-    def __init__(self,args):
-        self.args=args
-        self.initArgs()
-        self.SCMD1=['SALOME_LauncherServer']
-        self.SCMD2=[]
-        if args["gui"] :
-            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.path.expanduser("~")
-                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',')']
-
-    def setpath(self,modules_list,modules_root_dir):
-        list_modules = modules_list[:]
-        list_modules.reverse()
-        if self.args["gui"] :
-            list_modules = ["KERNEL", "GUI"] + list_modules
-        else :
-            list_modules = ["KERNEL"] + list_modules
-
-        cata_path=get_cata_path(list_modules,modules_root_dir)
-
-        if ("gui" in self.args) & ('moduleCatalog' in self.args['embedded']):
-            #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
-            self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
-        else:
-            self.CMD=self.SCMD1 + self.SCMD2
 #
 # -----------------------------------------------------------------------------
 
@@ -447,205 +68,22 @@ def startSalome(args, modules_list, modules_root_dir):
     """Launch all SALOME servers requested by args"""
     init_time = os.times()
 
-    if verbose(): print("startSalome ", args)
-
-    #
-    # Set server launch command
-    #
-    if 'server_launch_mode' in args:
-        Server.set_server_launch_mode(args['server_launch_mode'])
-
-    #
-    # Wake up session option
-    #
-    if args['wake_up_session']:
-        if "OMNIORB_CONFIG" not in os.environ:
-            from salome_utils import generateFileName
-            omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
-            kwargs={}
-            if omniorbUserPath is not None:
-                kwargs["with_username"]=True
-
-            last_running_config = generateFileName(omniorbUserPath, prefix="omniORB",
-                                                   suffix="last",
-                                                   extension="cfg",
-                                                   hidden=True,
-                                                   **kwargs)
-            os.environ['OMNIORB_CONFIG'] = last_running_config
-            pass
-        pass
-
-    #
-    # Initialisation ORB and Naming Service
-    #
-
-    clt=orbmodule.client(args)
-    addToPidict(args)
-
-    #
-    # Wake up session option
-    #
-    if args['wake_up_session']:
-        import Engines
-        import SALOME
-        import SALOMEDS
-        import SALOME_ModuleCatalog
-        import SALOME_Session_idl
-        session = clt.waitNS("/Kernel/Session",SALOME.Session)
-        status = session.GetStatSession()
-        if status.activeGUI:
-            from salome_utils import getPortNumber
-            port = getPortNumber()
-            msg  = "Warning :"
-            msg += "\n"
-            msg += "Session GUI for port number %s is already active."%(port)
-            msg += "\n"
-            msg += "If you which to wake up another session,"
-            msg += "\n"
-            msg += "please use variable OMNIORB_CONFIG"
-            msg += "\n"
-            msg += "to get the correct session object in naming service."
-            sys.stdout.write(msg+"\n")
-            sys.stdout.flush()
-            return clt
-        session.GetInterface()
-        args["session_object"] = session
-        return clt
-
-    # Launch Logger Server (optional)
-    # and wait until it is registered in naming service
-    #
-
-    if args['logger']:
-        myServer=LoggerServer(args)
-        myServer.run()
-        clt.waitLogger("Logger")
-        addToPidict(args)
+    logger.debug("startSalome : {} ".format(args))
 
     # Launch  Session Server (to show splash ASAP)
     #
 
     if args["gui"] and not args['launcher_only']:
-        mySessionServ = SessionServer(args,args['modules'],modules_root_dir)
+        mySessionServ = runSalomeNoServer.NoSessionServer(args,args['modules'],modules_root_dir)
         mySessionServ.setpath(modules_list,modules_root_dir)
         mySessionServ.run()
-        addToPidict(args)
-
-    #
-    # Launch Registry Server,
-    # and wait until it is registered in naming service
-    #
-
-    if ('registry' not in args['embedded']) | (args["gui"] == 0) :
-        myServer=RegistryServer(args)
-        myServer.run()
-        if sys.platform == "win32":
-          clt.waitNS("/Registry")
-        else:
-          clt.waitNSPID("/Registry",myServer.PID)
-        addToPidict(args)
-
-    #
-    # Launch Catalog Server,
-    # and wait until it is registered in naming service
-    #
-
-    if ('moduleCatalog' not in args['embedded']) | (args["gui"] == 0):
-        cataServer=CatalogServer(args)
-        cataServer.setpath(modules_list,modules_root_dir)
-        cataServer.run()
-        import SALOME_ModuleCatalog
-        if sys.platform == "win32":
-          clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
-        else:
-          clt.waitNSPID("/Kernel/ModulCatalog",cataServer.PID,SALOME_ModuleCatalog.ModuleCatalog)
-        addToPidict(args)
-
-    #
-    # Launch SalomeDS Server,
-    # and wait until it is registered in naming service
-    #
-
-    # print("ARGS = ",args)
-    if ('study' not in args['embedded']) | (args["gui"] == 0):
-        print("RunStudy")
-        myServer=SalomeDSServer(args)
-        myServer.run()
-        if sys.platform == "win32":
-          clt.waitNS("/Study")
-        else:
-          clt.waitNSPID("/Study",myServer.PID)
-        addToPidict(args)
-
-    #
-    # Launch LauncherServer
-    #
-
-    if not 'launcher' in args:
-      myCmServer = LauncherServer(args)
-      myCmServer.setpath(modules_list,modules_root_dir)
-      myCmServer.run()
-      addToPidict(args)
-
-    #
-    # Launch ConnectionManagerServer
-    #
-
-    if not args['launcher_only']:
-      myConnectionServer = ConnectionManagerServer(args)
-      myConnectionServer.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()
-
-    #
-    # Launch local C++ Container (FactoryServer),
-    # and wait until it is registered in naming service
-    #
-
-    if ('cppContainer' in args['standalone']) | (args["gui"] == 0) :
-        myServer=ContainerCPPServer(args, with_gui=args["gui"]!=0)
-        myServer.run()
-        if sys.platform == "win32":
-          clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
-        else:
-          clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID)
-        addToPidict(args)
-
-    if 'pyContainer' in args['standalone']:
-        raise Exception('Python containers no longer supported')
+    
+    end_time = os.times()
 
     #
     # Wait until Session Server is registered in naming service
     #
-
-    if args["gui"] and not args['launcher_only']:
-##----------------
-        import Engines
-        import SALOME
-        import SALOMEDS
-        import SALOME_ModuleCatalog
-        import SALOME_Session_idl
-        if sys.platform == "win32":
-          session=clt.waitNS("/Kernel/Session",SALOME.Session)
-        else:
-          session=clt.waitNSPID("/Kernel/Session",mySessionServ.PID,SALOME.Session)
-        args["session_object"] = session
-    end_time = os.times()
-    if verbose(): 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()
+    logger.debug("Start SALOME, elapsed time : %5.1f seconds"% (end_time[4] - init_time[4]))
 
     #
     # additional external python interpreters
@@ -662,7 +100,7 @@ def startSalome(args, modules_list, modules_root_dir):
         print("-- to get an external python interpreter:runSalome --interp=1")
         print("-------------------------------------------------------------")
 
-    if verbose(): print("additional external python interpreters: ", nbaddi)
+    logger.debug("additional external python interpreters: {}".format(nbaddi))
     if nbaddi:
         for i in range(nbaddi):
             print("i=",i)
@@ -677,7 +115,7 @@ def startSalome(args, modules_list, modules_root_dir):
         except ImportError:
             pass
 
-    return clt
+    return
 
 # -----------------------------------------------------------------------------
 
@@ -689,9 +127,8 @@ def useSalome(args, modules_list, modules_root_dir):
     """
     global process_id
 
-    clt=None
     try:
-        clt = startSalome(args, modules_list, modules_root_dir)
+        startSalome(args, modules_list, modules_root_dir)
     except Exception:
         import traceback
         traceback.print_exc()
@@ -709,7 +146,7 @@ def useSalome(args, modules_list, modules_root_dir):
         addToKillList(pid, cmd, args['port'])
         pass
 
-    if verbose(): print("""
+    logger.debug("""
     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
@@ -723,56 +160,7 @@ def useSalome(args, modules_list, modules_root_dir):
     the processes resulting from the previous execution.
     """%filedict)
 
-    #
-    #  Print Naming Service directory list
-    #
-
-    if clt != None:
-        if verbose():
-            print()
-            print(" --- registered objects tree in Naming Service ---")
-            clt.showNS()
-            pass
-
-        if not args['gui'] or not args['session_gui']:
-            if args['shutdown_servers']:
-                class __utils__:
-                    def __init__(self, port):
-                        self.port = port
-                        import killSalomeWithPort
-                        self.killSalomeWithPort = killSalomeWithPort
-                        return
-                    def __del__(self):
-                        self.killSalomeWithPort.killMyPort(self.port)
-                        return
-                    pass
-                def func(s):
-                    del s
-                import atexit
-                atexit.register(func, __utils__(args['port']))
-                pass
-            pass
-
-        # run python scripts, passed as command line arguments
-        toimport = []
-        if 'gui' in args and 'session_gui' in args:
-            if not args['gui'] or not args['session_gui']:
-                if 'study_hdf' in args:
-                    toopen = args['study_hdf']
-                    if toopen:
-                        import salome
-                        salome.salome_init(path=toopen)
-                if 'pyscript' in args:
-                    toimport = args['pyscript']
-        from salomeContextUtils import formatScriptsAndArgs
-        command = formatScriptsAndArgs(toimport, escapeSpaces=True)
-        if command:
-            proc = subprocess.Popen(command, shell=True)
-            addToKillList(proc.pid, command, args['port'])
-            res = proc.wait()
-            if res: sys.exit(1) # if there's an error when executing script, we should explicitly exit
-
-    return clt
+    return
 
 def execScript(script_path):
     print('executing', script_path)
@@ -782,37 +170,6 @@ def execScript(script_path):
 
 # -----------------------------------------------------------------------------
 
-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.
-    """
-    from salome_utils import getTmpDir
-    fileEnv = getTmpDir()
-    from salome_utils import getUserName
-    fileEnv += getUserName() + "_" + 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
-
-# -----------------------------------------------------------------------------
-
-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)
-    from searchFreePort import searchFreePort
-    searchFreePort(args, 0)
-    clt = useSalome(args, modules_list, modules_root_dir)
-    return clt
-
-# -----------------------------------------------------------------------------
-
 def addToPidict(args):
     global process_id
     from addToKillList import addToKillList
@@ -823,42 +180,18 @@ def addToPidict(args):
 
 def main(exeName=None):
     """Salome launch as a main application"""
-
-    # define folder to store omniorb config (initially in virtual application folder)
-    try:
-        from salomeContextUtils import setOmniOrbUserPath
-        setOmniOrbUserPath()
-    except Exception as e:
-        print(e)
-        sys.exit(1)
-
-    from salome_utils import getHostName
     keep_env = not os.getenv('SALOME_PLEASE_SETUP_ENVIRONMENT_AS_BEFORE')
     args, modules_list, modules_root_dir = setenv.get_config(exeName=exeName, keepEnvironment=keep_env)
-    print("runSalome running on %s" % getHostName())
-
+    runSalomeCommon.setVerbose(args["verbosity"])
     kill_salome(args)
-    save_config = True
-    if 'save_config' in args:
-        save_config = args['save_config']
-    # --
-    test = True
-    if args['wake_up_session']:
-        test = False
-        pass
-    if test and not 'launcher' in args:
-        from searchFreePort import searchFreePort
-        searchFreePort(args, save_config, args.get('useport'))
-        pass
     # --
-    #setenv.main()
     setenv.set_env(args, modules_list, modules_root_dir, keepEnvironment=keep_env)
-    clt = useSalome(args, modules_list, modules_root_dir)
-    return clt,args
+    useSalome(args, modules_list, modules_root_dir)
+    return args
 
 # -----------------------------------------------------------------------------
 
-def foreGround(clt, args):
+def foreGround(args):
     # --
     if "session_object" not in args:
         return
@@ -922,7 +255,7 @@ def foreGround(clt, args):
 #
 
 def runSalome():
-    clt,args = main()
+    args = main()
     # --
     test = args['gui'] and args['session_gui']
     test = test or args['wake_up_session']
@@ -946,7 +279,7 @@ def runSalome():
     if test:
         from time import sleep
         sleep(3.0)
-        foreGround(clt, args)
+        foreGround(args)
         pass
     pass
 #
diff --git a/bin/runSalomeCommon.py b/bin/runSalomeCommon.py
new file mode 100755 (executable)
index 0000000..1e3295a
--- /dev/null
@@ -0,0 +1,420 @@
+#!/usr/bin/env python3
+#  -*- coding: iso-8859-1 -*-
+# Copyright (C) 2007-2021  CEA/DEN, EDF R&D, OPEN CASCADE
+#
+# Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
+# CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+
+## @package runSalome
+# \brief Module that provides services to launch SALOME
+#
+
+import sys, os, string, glob, time, pickle, re
+import setenv
+from server import process_id, Server
+import json
+import subprocess
+from salomeContextUtils import ScriptAndArgsObjectEncoder
+import platform
+import logging
+logger = logging.getLogger()
+
+class ColoredFormatter(logging.Formatter):
+    BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(30,38)
+    COLORS = { 'WARNING': YELLOW, 'INFO': WHITE, 'DEBUG': BLUE, 'CRITICAL': YELLOW, 'ERROR': RED }
+    def __init__(self, *args, **kwargs):
+        logging.Formatter.__init__(self, *args, **kwargs)
+    def format(self, record):
+        RESET_SEQ = "\033[0m"
+        COLOR_SEQ = "\033[1;%dm"
+        record.levelname = COLOR_SEQ % ColoredFormatter.COLORS[record.levelname] + record.levelname + RESET_SEQ
+        return logging.Formatter.format(self, record)
+
+def setVerbose(verbose):
+    global logger
+    formatter = logging.Formatter('%(levelname)s : %(asctime)s : %(message)s ',style='%')
+    formatter.default_time_format = '%H:%M:%S'
+    formatter.default_msec_format = "%s.%03d"
+    stream_handler = logging.StreamHandler()
+    stream_handler.setFormatter(formatter)
+    logger.addHandler(stream_handler)
+
+    verbose_map = { "0": logging.WARNING, "1": logging.INFO, "2": logging.DEBUG}
+    if verbose in verbose_map:
+        logger.setLevel(verbose_map[verbose])
+
+# -----------------------------------------------------------------------------
+#
+# Class definitions to launch CORBA Servers
+#
+
+class InterpServer(Server):
+    def __init__(self,args):
+        self.args=args
+        if sys.platform == "win32":
+          self.CMD=['cmd', '/c', 'start cmd.exe', '/K', 'python']
+        elif sys.platform == "darwin":
+          env_ld_library_path=['env', 'DYLD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
+          self.CMD=['xterm', '-e'] + env_ld_library_path + ['python']
+        else:
+          env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
+          self.CMD=['xterm', '-e'] + env_ld_library_path + ['python']
+
+    def run(self):
+        global process_id
+        command = self.CMD
+        print("INTERPSERVER::command = ", command)
+        import subprocess
+        pid = subprocess.Popen(command).pid
+        process_id[pid]=self.CMD
+        self.PID = pid
+
+# ---
+
+def get_cata_path(list_modules,modules_root_dir):
+    """Build a list of catalog paths (cata_path) to initialize the ModuleCatalog server
+    """
+    modules_cata={}
+    cata_path=[]
+
+    for module in list_modules:
+        if module in modules_root_dir:
+            module_root_dir=modules_root_dir[module]
+            module_cata=module+"Catalog.xml"
+            cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources",module.lower(), module_cata)
+
+            if os.path.exists(cata_file):
+                cata_path.append(cata_file)
+                modules_cata[module]=cata_file
+            else:
+                cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources", module_cata)
+                if os.path.exists(cata_file):
+                    cata_path.append(cata_file)
+                    modules_cata[module]=cata_file
+
+    for path in os.getenv("SALOME_CATALOGS_PATH","").split(os.pathsep):
+        if os.path.exists(path):
+            for cata_file in glob.glob(os.path.join(path,"*Catalog.xml")):
+                module_name= os.path.basename(cata_file)[:-11]
+                if module_name not in modules_cata:
+                    cata_path.append(cata_file)
+                    modules_cata[module_name]=cata_file
+
+    return cata_path
+
+class CatalogServer(Server):
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.SCMD1=['SALOME_ModuleCatalog_Server']
+        if 'launcher' in self.args:
+            pos = args['launcher'].find(":")
+            if pos != -1:
+              self.SCMD1+=['-ORBInitRef']
+              machine = args['launcher'][0:pos]
+              port = args['launcher'][pos+1:]
+              self.SCMD1+=["NameService=corbaname::" + machine + ":" + port]
+        self.SCMD1+=['-common']
+        self.SCMD2=[]
+        home_dir=os.path.expanduser("~")
+        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):
+        list_modules = modules_list[:]
+        list_modules.reverse()
+        if self.args["gui"] :
+            list_modules = ["KERNEL", "GUI"] + list_modules
+        else :
+            list_modules = ["KERNEL"] + list_modules
+
+        cata_path=get_cata_path(list_modules,modules_root_dir)
+
+        self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
+
+# ---
+
+class SalomeDSServer(Server):
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.CMD=['SALOMEDS_Server']
+        if 'launcher' in self.args:
+            pos = args['launcher'].find(":")
+            if pos != -1:
+              self.CMD+=['-ORBInitRef']
+              machine = args['launcher'][0:pos]
+              port = args['launcher'][pos+1:]
+              self.CMD+=["NameService=corbaname::" + machine + ":" + port]
+
+# ---
+
+class ConnectionManagerServer(Server):
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.CMD=['SALOME_ConnectionManagerServer']
+        if 'launcher' in self.args:
+            pos = args['launcher'].find(":")
+            if pos != -1:
+              self.CMD+=['-ORBInitRef']
+              machine = args['launcher'][0:pos]
+              port = args['launcher'][pos+1:]
+              self.CMD+=["NameService=corbaname::" + machine + ":" + port]
+
+
+# ---
+
+class RegistryServer(Server):
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.CMD=['SALOME_Registry_Server', '--salome_session','theSession']
+        if 'launcher' in self.args:
+            pos = args['launcher'].find(":")
+            if pos != -1:
+              self.CMD+=['-ORBInitRef']
+              machine = args['launcher'][0:pos]
+              port = args['launcher'][pos+1:]
+              self.CMD+=["NameService=corbaname::" + machine + ":" + port]
+
+# ---
+
+class ContainerCPPServer(Server):
+    def __init__(self,args,with_gui=False):
+        self.args=args
+        self.initArgs()
+        self.CMD=['SALOME_Container']
+        if 'launcher' in self.args:
+            pos = args['launcher'].find(":")
+            if pos != -1:
+              self.CMD+=['-ORBInitRef']
+              machine = args['launcher'][0:pos]
+              port = args['launcher'][pos+1:]
+              self.CMD+=["NameService=corbaname::" + machine + ":" + port]
+        self.CMD+=['FactoryServer']
+        if not with_gui and self.args["valgrind_session"]:
+            l = ["valgrind"]
+            val = os.getenv("VALGRIND_OPTIONS")
+            if val:
+                l += val.split()
+                pass
+            self.CMD = l + self.CMD
+            pass
+
+# ---
+
+class LoggerServer(Server):
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        from salome_utils import generateFileName, getLogDir
+        logfile = generateFileName( getLogDir(),
+                                    prefix="logger",
+                                    extension="log",
+                                    with_username=True,
+                                    with_hostname=True,
+                                    with_port=True)
+        print("===========================================================")
+        print("Logger server: put log to the file:")
+        print(logfile)
+        print("===========================================================")
+        self.CMD=['SALOME_Logger_Server', logfile]
+        pass
+    pass # end of LoggerServer class
+
+# ---
+import abc
+class CommonSessionServer(Server):
+    def __init__(self,args,modules_list,modules_root_dir):
+        self.args = args.copy()
+        # Bug 11512 (Problems with runSalome --xterm on Mandrake and Debian Sarge)
+        #self.args['xterm']=0
+        #
+        self.initArgs()
+        self.SCMD1=[self.getSessionServerExe()]
+        if "SQUISH_PREFIX" in os.environ:
+            if platform.system() == "Windows" :
+                self.SCMD1 = [os.path.join(os.getenv("SQUISH_PREFIX"), "bin", "dllpreload.exe"),os.path.join(os.getenv("SQUISH_SALOME_PATH"), "W64", "GUI", "bin", "salome", self.SCMD1[0])]
+            else :
+                os.environ["LD_LIBRARY_PATH"] = os.environ["SQUISH_PREFIX"] + "/lib:" + os.environ["LD_LIBRARY_PATH"]
+        self.SCMD2=[]
+        if 'launcher' in self.args:
+            pos = args['launcher'].find(":")
+            if pos != -1:
+              self.SCMD1+=['-ORBInitRef']
+              machine = args['launcher'][0:pos]
+              port = args['launcher'][pos+1:]
+              self.SCMD1+=["NameService=corbaname::" + machine + ":" + port]
+        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.path.expanduser("~")
+            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','(',')']
+
+        if 'cppContainer' in self.args['standalone'] or 'cppContainer' in self.args['embedded']:
+            self.SCMD2+=['CPP']
+        if 'pyContainer' in self.args['standalone'] or 'pyContainer' in self.args['embedded']:
+            raise Exception('Python containers no longer supported')
+        if self.args['gui']:
+            session_gui = self.args.get('session_gui', True)
+            if not session_gui:
+                self.SCMD2+=['--hide-desktop']
+            else:
+                if not self.args['splash']:
+                    self.SCMD2+=['--hide-splash']
+                    pass
+                if self.args['study_hdf'] is not None:
+                    self.SCMD2+=['--study-hdf=%s'%self.args['study_hdf']]
+                    pass
+                pass
+                if 'pyscript' in self.args and len(self.args['pyscript']) > 0:
+                    msg = json.dumps(self.args['pyscript'], cls=ScriptAndArgsObjectEncoder)
+                    self.SCMD2+=['--pyscript=%s'%(msg)]
+                    pass
+                pass
+            pass
+        if self.args['noexcepthandler']:
+            self.SCMD2+=['--no-exception-handler']
+        if 'user_config' in self.args:
+            self.SCMD2+=['--resources=%s'%self.args['user_config']]
+        if 'modules' in self.args:
+            list_modules = []
+            #keep only modules with GUI
+            for m in modules_list:
+              if m not in modules_root_dir:
+                list_modules.insert(0,m)
+              else:
+                fr1 = os.path.join(modules_root_dir[m],"share","salome","resources",m.lower(),"SalomeApp.xml")
+                fr2 = os.path.join(modules_root_dir[m],"share","salome","resources","SalomeApp.xml")
+                if os.path.exists(fr1) or os.path.exists(fr2):
+                  list_modules.insert(0,m)
+            list_modules.reverse()
+            self.SCMD2+=['--modules (%s)' % ":".join(list_modules)]
+            pass
+        if 'language' in self.args:
+            self.SCMD2+=['--language=%s' % self.args['language']]
+        pass
+
+    @abc.abstractmethod
+    def getSessionServerExe(self):
+        pass
+    
+    def setpath(self,modules_list,modules_root_dir):
+        list_modules = modules_list[:]
+        list_modules.reverse()
+        if self.args["gui"] :
+            list_modules = ["KERNEL", "GUI"] + list_modules
+        else :
+            list_modules = ["KERNEL"] + list_modules
+
+        cata_path=get_cata_path(list_modules,modules_root_dir)
+
+        if ("gui" in self.args) & ('moduleCatalog' in self.args['embedded']):
+            #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
+            self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
+        else:
+            self.CMD=self.SCMD1 + self.SCMD2
+        if 'test' in self.args:
+            self.CMD+=['-test'] + self.args['test']
+        elif 'play' in self.args:
+            self.CMD+=['-play'] + self.args['play']
+
+        if self.args["gdb_session"] or self.args["ddd_session"]:
+            f = open(".gdbinit4salome", "w")
+            f.write("set args ")
+            args = " ".join(self.CMD[1:])
+            args = args.replace("(", "\(")
+            args = args.replace(")", "\)")
+            f.write(args)
+            f.write("\n")
+            f.close()
+            if self.args["ddd_session"]:
+                self.CMD = ["ddd", "--command=.gdbinit4salome", self.CMD[0]]
+            elif self.args["gdb_session"]:
+                self.CMD = ["xterm", "-e", "gdb", "--command=.gdbinit4salome", self.CMD[0]]
+                pass
+            pass
+
+        if self.args["valgrind_session"]:
+            l = ["valgrind"]
+            val = os.getenv("VALGRIND_OPTIONS")
+            if val:
+                l += val.split()
+                pass
+            self.CMD = l + self.CMD
+            pass
+
+class SessionServer(CommonSessionServer):
+    def __init__(self,args,modules_list,modules_root_dir):
+        super().__init__(args,modules_list,modules_root_dir)
+        import KernelBasis
+        KernelBasis.setSSLMode(False)
+    
+    def getSessionServerExe(self):
+        return "SALOME_Session_Server"
+# ---
+
+class LauncherServer(Server):
+    def __init__(self,args):
+        self.args=args
+        self.initArgs()
+        self.SCMD1=['SALOME_LauncherServer']
+        self.SCMD2=[]
+        if args["gui"] :
+            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.path.expanduser("~")
+                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',')']
+
+    def setpath(self,modules_list,modules_root_dir):
+        list_modules = modules_list[:]
+        list_modules.reverse()
+        if self.args["gui"] :
+            list_modules = ["KERNEL", "GUI"] + list_modules
+        else :
+            list_modules = ["KERNEL"] + list_modules
+
+        cata_path=get_cata_path(list_modules,modules_root_dir)
+
+        if ("gui" in self.args) & ('moduleCatalog' in self.args['embedded']):
+            #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
+            self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
+        else:
+            self.CMD=self.SCMD1 + self.SCMD2
index f63e74a73a766abd9b8a69a5264cfa8c0804f5b3..1039f050a2e7ee41995f87d31922f5ec0a3914e3 100755 (executable)
 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 #
 import setenv
-import runSalome
+import runSalomeCommon
 import os
+import logging
+logger = logging.getLogger()
 
-class NoSessionServer(runSalome.SessionServer):
+class NoSessionServer(runSalomeCommon.CommonSessionServer):
     def __init__(self,args,modules_list,modules_root_dir):
         super().__init__(args,modules_list,modules_root_dir)
-        for i in range (len(self.SCMD1)):
-            if self.SCMD1[i] == "SALOME_Session_Server" :
-                self.SCMD1[i] = "SALOME_Session_Server_No_Server"
-        os.putenv("SALOME_EMB_SERVANT", "1")
         SalomeAppSLConfig=os.getenv("SalomeAppConfig","")
         os.putenv("SalomeAppSLConfig", SalomeAppSLConfig)
+    def getSessionServerExe(self):
+        return "SALOME_Session_Server_No_Server"
+
+from server import process_id
+from addToKillList import addToKillList,killList
 
 def main():
     args, modules_list, modules_root_dir = setenv.get_config()
     mySessionServ = NoSessionServer(args, args.get('modules', []), modules_root_dir)
+    runSalomeCommon.setVerbose(mySessionServ.args["verbosity"])
+    if mySessionServ.args["killall"]:
+        killList()
+    logger.debug("Effective args : {}".format(mySessionServ.args))
     mySessionServ.setpath(modules_list, modules_root_dir)
     mySessionServ.run()
+    for pid, cmd in list(process_id.items()):
+        logger.debug("Killing {} {}".format(pid, cmd))
+        addToKillList(pid, cmd)
 
 if __name__ == "__main__":
     main()
diff --git a/bin/runSalomeOld.py b/bin/runSalomeOld.py
new file mode 100755 (executable)
index 0000000..f25f510
--- /dev/null
@@ -0,0 +1,609 @@
+#!/usr/bin/env python3
+#  -*- coding: iso-8859-1 -*-
+# Copyright (C) 2007-2021  CEA/DEN, EDF R&D, OPEN CASCADE
+#
+# Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
+# CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+
+## @package runSalome
+# \brief Module that provides services to launch SALOME
+#
+
+import sys, os, string, glob, time, pickle, re
+import orbmodule
+import setenv
+from launchConfigureParser import verbose
+from server import process_id, Server
+import json
+import subprocess
+from salomeContextUtils import ScriptAndArgsObjectEncoder
+import platform
+from runSalomeCommon import setVerbose, InterpServer, CatalogServer, SalomeDSServer, ConnectionManagerServer, RegistryServer, ContainerCPPServer, LoggerServer, CommonSessionServer, SessionServer, LauncherServer
+# -----------------------------------------------------------------------------
+
+from killSalome import killAllPorts
+
+def killLocalPort():
+    """
+    kill servers from a previous SALOME execution, 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 Exception:
+        print("problem in killLocalPort()")
+        pass
+    pass
+
+def givenPortKill(port):
+    """
+    kill servers from a previous SALOME execution, if needed,
+    on the same CORBA port
+    """
+
+    from killSalomeWithPort import killMyPort
+    my_port=port
+    try:
+        killMyPort(my_port)
+    except Exception:
+        print("problem in LocalPortKill(), killMyPort(%s)"%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']))
+
+def startGUI(clt):
+    """Salome Session Graphic User Interface activation"""
+    import Engines
+    import SALOME
+    import SALOMEDS
+    import SALOME_ModuleCatalog
+    import SALOME_Session_idl
+    session=clt.waitNS("/Kernel/Session",SALOME.Session)
+    session.GetInterface()
+
+# -----------------------------------------------------------------------------
+
+def startSalome(args, modules_list, modules_root_dir):
+    """Launch all SALOME servers requested by args"""
+    init_time = os.times()
+
+    if verbose(): print("startSalome ", args)
+
+    #
+    # Set server launch command
+    #
+    if 'server_launch_mode' in args:
+        Server.set_server_launch_mode(args['server_launch_mode'])
+
+    #
+    # Wake up session option
+    #
+    if args['wake_up_session']:
+        if "OMNIORB_CONFIG" not in os.environ:
+            from salome_utils import generateFileName
+            omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
+            kwargs={}
+            if omniorbUserPath is not None:
+                kwargs["with_username"]=True
+
+            last_running_config = generateFileName(omniorbUserPath, prefix="omniORB",
+                                                   suffix="last",
+                                                   extension="cfg",
+                                                   hidden=True,
+                                                   **kwargs)
+            os.environ['OMNIORB_CONFIG'] = last_running_config
+            pass
+        pass
+
+    #
+    # Initialisation ORB and Naming Service
+    #
+
+    clt=orbmodule.client(args)
+    addToPidict(args)
+
+    #
+    # Wake up session option
+    #
+    if args['wake_up_session']:
+        import Engines
+        import SALOME
+        import SALOMEDS
+        import SALOME_ModuleCatalog
+        import SALOME_Session_idl
+        session = clt.waitNS("/Kernel/Session",SALOME.Session)
+        status = session.GetStatSession()
+        if status.activeGUI:
+            from salome_utils import getPortNumber
+            port = getPortNumber()
+            msg  = "Warning :"
+            msg += "\n"
+            msg += "Session GUI for port number %s is already active."%(port)
+            msg += "\n"
+            msg += "If you which to wake up another session,"
+            msg += "\n"
+            msg += "please use variable OMNIORB_CONFIG"
+            msg += "\n"
+            msg += "to get the correct session object in naming service."
+            sys.stdout.write(msg+"\n")
+            sys.stdout.flush()
+            return clt
+        session.GetInterface()
+        args["session_object"] = session
+        return clt
+
+    # Launch Logger Server (optional)
+    # and wait until it is registered in naming service
+    #
+
+    if args['logger']:
+        myServer=LoggerServer(args)
+        myServer.run()
+        clt.waitLogger("Logger")
+        addToPidict(args)
+
+    # Launch  Session Server (to show splash ASAP)
+    #
+
+    if args["gui"] and not args['launcher_only']:
+        mySessionServ = SessionServer(args,args['modules'],modules_root_dir)
+        mySessionServ.setpath(modules_list,modules_root_dir)
+        mySessionServ.run()
+        addToPidict(args)
+
+    #
+    # Launch Registry Server,
+    # and wait until it is registered in naming service
+    #
+
+    if ('registry' not in args['embedded']) | (args["gui"] == 0) :
+        myServer=RegistryServer(args)
+        myServer.run()
+        if sys.platform == "win32":
+          clt.waitNS("/Registry")
+        else:
+          clt.waitNSPID("/Registry",myServer.PID)
+        addToPidict(args)
+
+    #
+    # Launch Catalog Server,
+    # and wait until it is registered in naming service
+    #
+
+    if ('moduleCatalog' not in args['embedded']) | (args["gui"] == 0):
+        cataServer=CatalogServer(args)
+        cataServer.setpath(modules_list,modules_root_dir)
+        cataServer.run()
+        import SALOME_ModuleCatalog
+        if sys.platform == "win32":
+          clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
+        else:
+          clt.waitNSPID("/Kernel/ModulCatalog",cataServer.PID,SALOME_ModuleCatalog.ModuleCatalog)
+        addToPidict(args)
+
+    #
+    # Launch SalomeDS Server,
+    # and wait until it is registered in naming service
+    #
+
+    # print("ARGS = ",args)
+    if ('study' not in args['embedded']) | (args["gui"] == 0):
+        print("RunStudy")
+        myServer=SalomeDSServer(args)
+        myServer.run()
+        if sys.platform == "win32":
+          clt.waitNS("/Study")
+        else:
+          clt.waitNSPID("/Study",myServer.PID)
+        addToPidict(args)
+
+    #
+    # Launch LauncherServer
+    #
+
+    if not 'launcher' in args:
+      myCmServer = LauncherServer(args)
+      myCmServer.setpath(modules_list,modules_root_dir)
+      myCmServer.run()
+      addToPidict(args)
+
+    #
+    # Launch ConnectionManagerServer
+    #
+
+    if not args['launcher_only']:
+      myConnectionServer = ConnectionManagerServer(args)
+      myConnectionServer.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()
+
+    #
+    # Launch local C++ Container (FactoryServer),
+    # and wait until it is registered in naming service
+    #
+
+    if ('cppContainer' in args['standalone']) | (args["gui"] == 0) :
+        myServer=ContainerCPPServer(args, with_gui=args["gui"]!=0)
+        myServer.run()
+        if sys.platform == "win32":
+          clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
+        else:
+          clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID)
+        addToPidict(args)
+
+    if 'pyContainer' in args['standalone']:
+        raise Exception('Python containers no longer supported')
+
+    #
+    # Wait until Session Server is registered in naming service
+    #
+
+    if args["gui"] and not args['launcher_only']:
+##----------------
+        import Engines
+        import SALOME
+        import SALOMEDS
+        import SALOME_ModuleCatalog
+        import SALOME_Session_idl
+        if sys.platform == "win32":
+          session=clt.waitNS("/Kernel/Session",SALOME.Session)
+        else:
+          session=clt.waitNSPID("/Kernel/Session",mySessionServ.PID,SALOME.Session)
+        args["session_object"] = session
+    end_time = os.times()
+    if verbose(): 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()
+
+    #
+    # additional external python interpreters
+    #
+    nbaddi=0
+
+    try:
+        if 'interp' in args:
+            nbaddi = args['interp']
+    except Exception:
+        import traceback
+        traceback.print_exc()
+        print("-------------------------------------------------------------")
+        print("-- to get an external python interpreter:runSalome --interp=1")
+        print("-------------------------------------------------------------")
+
+    if verbose(): print("additional external python interpreters: ", nbaddi)
+    if nbaddi:
+        for i in range(nbaddi):
+            print("i=",i)
+            anInterp=InterpServer(args)
+            anInterp.run()
+
+    # set PYTHONINSPECT variable (python interpreter in interactive mode)
+    if args['pinter']:
+        os.environ["PYTHONINSPECT"]="1"
+        try:
+            import readline
+        except ImportError:
+            pass
+
+    return clt
+
+# -----------------------------------------------------------------------------
+
+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.
+    """
+    global process_id
+
+    clt=None
+    try:
+        clt = startSalome(args, modules_list, modules_root_dir)
+    except Exception:
+        import traceback
+        traceback.print_exc()
+        print()
+        print()
+        print("--- Error during Salome launch ---")
+
+    # print(process_id)
+
+    from addToKillList import addToKillList
+    from killSalomeWithPort import getPiDict
+
+    filedict = getPiDict(args['port'])
+    for pid, cmd in list(process_id.items()):
+        addToKillList(pid, cmd, args['port'])
+        pass
+
+    if verbose(): 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)
+
+    #
+    #  Print Naming Service directory list
+    #
+
+    if clt != None:
+        if verbose():
+            print()
+            print(" --- registered objects tree in Naming Service ---")
+            clt.showNS()
+            pass
+
+        if not args['gui'] or not args['session_gui']:
+            if args['shutdown_servers']:
+                class __utils__:
+                    def __init__(self, port):
+                        self.port = port
+                        import killSalomeWithPort
+                        self.killSalomeWithPort = killSalomeWithPort
+                        return
+                    def __del__(self):
+                        self.killSalomeWithPort.killMyPort(self.port)
+                        return
+                    pass
+                def func(s):
+                    del s
+                import atexit
+                atexit.register(func, __utils__(args['port']))
+                pass
+            pass
+
+        # run python scripts, passed as command line arguments
+        toimport = []
+        if 'gui' in args and 'session_gui' in args:
+            if not args['gui'] or not args['session_gui']:
+                if 'study_hdf' in args:
+                    toopen = args['study_hdf']
+                    if toopen:
+                        import salome
+                        salome.salome_init(path=toopen)
+                if 'pyscript' in args:
+                    toimport = args['pyscript']
+        from salomeContextUtils import formatScriptsAndArgs
+        command = formatScriptsAndArgs(toimport, escapeSpaces=True)
+        if command:
+            proc = subprocess.Popen(command, shell=True)
+            addToKillList(proc.pid, command, args['port'])
+            res = proc.wait()
+            if res: sys.exit(1) # if there's an error when executing script, we should explicitly exit
+
+    return clt
+
+def execScript(script_path):
+    print('executing', script_path)
+    sys.path.insert(0, os.path.realpath(os.path.dirname(script_path)))
+    exec(compile(open(script_path).read(), script_path, 'exec'),globals())
+    del sys.path[0]
+
+# -----------------------------------------------------------------------------
+
+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.
+    """
+    from salome_utils import getTmpDir
+    fileEnv = getTmpDir()
+    from salome_utils import getUserName
+    fileEnv += getUserName() + "_" + 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
+
+# -----------------------------------------------------------------------------
+
+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)
+    from searchFreePort import searchFreePort
+    searchFreePort(args, 0)
+    clt = useSalome(args, modules_list, modules_root_dir)
+    return clt
+
+# -----------------------------------------------------------------------------
+
+def addToPidict(args):
+    global process_id
+    from addToKillList import addToKillList
+    for pid, cmd in list(process_id.items()):
+        addToKillList(pid, cmd, args['port'])
+
+# -----------------------------------------------------------------------------
+
+def main(exeName=None):
+    """Salome launch as a main application"""
+
+    # define folder to store omniorb config (initially in virtual application folder)
+    try:
+        from salomeContextUtils import setOmniOrbUserPath
+        setOmniOrbUserPath()
+    except Exception as e:
+        print(e)
+        sys.exit(1)
+
+    from salome_utils import getHostName
+    keep_env = not os.getenv('SALOME_PLEASE_SETUP_ENVIRONMENT_AS_BEFORE')
+    args, modules_list, modules_root_dir = setenv.get_config(exeName=exeName, keepEnvironment=keep_env)
+    print("runSalome running on %s" % getHostName())
+
+    kill_salome(args)
+    save_config = True
+    if 'save_config' in args:
+        save_config = args['save_config']
+    # --
+    test = True
+    if args['wake_up_session']:
+        test = False
+        pass
+    if test and not 'launcher' in args:
+        from searchFreePort import searchFreePort
+        searchFreePort(args, save_config, args.get('useport'))
+        pass
+    # --
+    #setenv.main()
+    setenv.set_env(args, modules_list, modules_root_dir, keepEnvironment=keep_env)
+    clt = useSalome(args, modules_list, modules_root_dir)
+    return clt,args
+
+# -----------------------------------------------------------------------------
+
+def foreGround(clt, args):
+    # --
+    if "session_object" not in args:
+        return
+    session = args["session_object"]
+    # --
+    # Wait until gui is arrived
+    # tmax = nbtot * dt
+    # --
+    gui_detected = False
+    dt = 0.1
+    nbtot = 100
+    nb = 0
+    session_pid = None
+    while 1:
+        try:
+            status = session.GetStatSession()
+            gui_detected = status.activeGUI
+            session_pid = session.getPID()
+        except Exception:
+            pass
+        if gui_detected:
+            break
+        from time import sleep
+        sleep(dt)
+        nb += 1
+        if nb == nbtot:
+            break
+        pass
+    # --
+    if not gui_detected:
+        return
+    # --
+    from salome_utils import getPortNumber
+    port = getPortNumber()
+    # --
+    server = Server({})
+    if sys.platform == "win32":
+      server.CMD = [os.getenv("PYTHONBIN"), "-m", "killSalomeWithPort", "--spy", "%s"%(session_pid or os.getpid()), "%s"%(port)]
+    else:
+      server.CMD = ["killSalomeWithPort.py", "--spy", "%s"%(session_pid or os.getpid()), "%s"%(port)]
+    server.run(True)
+    # os.system("killSalomeWithPort.py --spy %s %s &"%(os.getpid(), port))
+    # --
+    dt = 1.0
+    try:
+        while 1:
+            try:
+                status = session.GetStatSession()
+                assert status.activeGUI
+            except Exception:
+                break
+            from time import sleep
+            sleep(dt)
+            pass
+        pass
+    except KeyboardInterrupt:
+        from killSalomeWithPort import killMyPort
+        killMyPort(port)
+        pass
+    return
+#
+
+def runSalome():
+    clt,args = main()
+    # --
+    test = args['gui'] and args['session_gui']
+    test = test or args['wake_up_session']
+    # --
+    # The next test covers the --pinter option or if var PYTHONINSPECT is set
+    # --
+    test = test and not os.environ.get('PYTHONINSPECT')
+    # --
+    # The next test covers the python -i $KERNEL_ROOT_DIR/bin/salome/runSalome.py case
+    # --
+    try:
+        from ctypes import POINTER, c_int, cast, pythonapi
+        iflag_ptr = cast(pythonapi.Py_InteractiveFlag, POINTER(c_int))
+        test = test and not iflag_ptr.contents.value
+    except Exception:
+        pass
+    # --
+#    test = test and os.getenv("SALOME_TEST_MODE", "0") != "1"
+    test = test and args['foreground']
+    # --
+    if test:
+        from time import sleep
+        sleep(3.0)
+        foreGround(clt, args)
+        pass
+    pass
+#
+
+# -----------------------------------------------------------------------------
+
+if __name__ == "__main__":
+    runSalome()
+#
diff --git a/bin/runSalomeSL.py b/bin/runSalomeSL.py
deleted file mode 100755 (executable)
index 24be5de..0000000
+++ /dev/null
@@ -1,680 +0,0 @@
-#!/usr/bin/env python3
-#  -*- coding: iso-8859-1 -*-
-# Copyright (C) 2021  CEA/DEN, EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-
-## @package runSalome
-# \brief Module that provides services to launch SALOME
-#
-
-import sys, os, string, glob, time, pickle, re
-import orbmodule
-import setenv
-from launchConfigureParser import verbose
-from server import process_id, Server
-import json
-import subprocess
-from salomeContextUtils import ScriptAndArgsObjectEncoder
-import platform
-
-# -----------------------------------------------------------------------------
-
-from killSalome import killAllPorts
-
-def killLocalPort():
-    """
-    kill servers from a previous SALOME execution, 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 execution, if needed,
-    on the same CORBA port
-    """
-
-    from killSalomeWithPort import killMyPort
-    my_port=port
-    try:
-        killMyPort(my_port)
-    except:
-        print("problem in LocalPortKill(), killMyPort(%s)"%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']))
-
-# -----------------------------------------------------------------------------
-#
-# Class definitions to launch CORBA Servers
-#
-
-class InterpServer(Server):
-    def __init__(self,args):
-        self.args=args
-        if sys.platform == "win32":
-          self.CMD=['cmd', '/c', 'start cmd.exe', '/K', 'python']
-        elif sys.platform == "darwin":
-          env_ld_library_path=['env', 'DYLD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
-          self.CMD=['xterm', '-e'] + env_ld_library_path + ['python']
-        else:
-          env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
-          self.CMD=['xterm', '-e'] + env_ld_library_path + ['python']
-
-    def run(self):
-        global process_id
-        command = self.CMD
-        print("INTERPSERVER::command = ", command)
-        import subprocess
-        pid = subprocess.Popen(command).pid
-        process_id[pid]=self.CMD
-        self.PID = pid
-
-# ---
-
-def get_cata_path(list_modules,modules_root_dir):
-    """Build a list of catalog paths (cata_path) to initialize the ModuleCatalog server
-    """
-    modules_cata={}
-    cata_path=[]
-
-    for module in list_modules:
-        if module in modules_root_dir:
-            module_root_dir=modules_root_dir[module]
-            module_cata=module+"Catalog.xml"
-            cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources",module.lower(), module_cata)
-
-            if os.path.exists(cata_file):
-                cata_path.append(cata_file)
-                modules_cata[module]=cata_file
-            else:
-                cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources", module_cata)
-                if os.path.exists(cata_file):
-                    cata_path.append(cata_file)
-                    modules_cata[module]=cata_file
-
-    for path in os.getenv("SALOME_CATALOGS_PATH","").split(os.pathsep):
-        if os.path.exists(path):
-            for cata_file in glob.glob(os.path.join(path,"*Catalog.xml")):
-                module_name= os.path.basename(cata_file)[:-11]
-                if module_name not in modules_cata:
-                    cata_path.append(cata_file)
-                    modules_cata[module_name]=cata_file
-
-    return cata_path
-
-
-class LoggerServer(Server):
-    def __init__(self,args):
-        self.args=args
-        self.initArgs()
-        from salome_utils import generateFileName, getLogDir
-        logfile = generateFileName( getLogDir(),
-                                    prefix="logger",
-                                    extension="log",
-                                    with_username=True,
-                                    with_hostname=True,
-                                    with_port=True)
-        print("===========================================================")
-        print("Logger server: put log to the file:")
-        print(logfile)
-        print("===========================================================")
-        self.CMD=['SALOME_Logger_Server', logfile]
-        pass
-    pass # end of LoggerServer class
-
-# ---
-
-class SessionServer(Server):
-    def __init__(self,args,modules_list,modules_root_dir):
-        self.args = args.copy()
-        # Bug 11512 (Problems with runSalome --xterm on Mandrake and Debian Sarge)
-        #self.args['xterm']=0
-        #
-        self.initArgs()
-        self.SCMD1=['SALOME_Session_Server_No_Server']
-        if "SQUISH_PREFIX" in os.environ:
-            if platform.system() == "Windows" :
-                self.SCMD1 = [os.path.join(os.getenv("SQUISH_PREFIX"), "bin", "dllpreload.exe"),os.path.join(os.getenv("SQUISH_SALOME_PATH"), "W64", "GUI", "bin", "salome", self.SCMD1[0])]
-            else :
-                os.environ["LD_LIBRARY_PATH"] = os.environ["SQUISH_PREFIX"] + "/lib:" + os.environ["LD_LIBRARY_PATH"]
-        self.SCMD2=[]
-        if 'launcher' in self.args:
-            pos = args['launcher'].find(":")
-            if pos != -1:
-              self.SCMD1+=['-ORBInitRef']
-              machine = args['launcher'][0:pos]
-              port = args['launcher'][pos+1:]
-              self.SCMD1+=["NameService=corbaname::" + machine + ":" + port]
-        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.path.expanduser("~")
-            #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','(',')']
-
-        if 'cppContainer' in self.args['standalone'] or 'cppContainer' in self.args['embedded']:
-            self.SCMD2+=['CPP']
-        if 'pyContainer' in self.args['standalone'] or 'pyContainer' in self.args['embedded']:
-            raise Exception('Python containers no longer supported')
-        if self.args['gui']:
-            session_gui = self.args.get('session_gui', True)
-            if not session_gui:
-                self.SCMD2+=['--hide-desktop']
-            else:
-                if not self.args['splash']:
-                    self.SCMD2+=['--hide-splash']
-                    pass
-                if self.args['study_hdf'] is not None:
-                    self.SCMD2+=['--study-hdf=%s'%self.args['study_hdf']]
-                    pass
-                pass
-                if 'pyscript' in self.args and len(self.args['pyscript']) > 0:
-                    msg = json.dumps(self.args['pyscript'], cls=ScriptAndArgsObjectEncoder)
-                    self.SCMD2+=['--pyscript=%s'%(msg)]
-                    pass
-                pass
-            pass
-        if self.args['noexcepthandler']:
-            self.SCMD2+=['--no-exception-handler']
-        if 'user_config' in self.args:
-            self.SCMD2+=['--resources=%s'%self.args['user_config']]
-        if 'modules' in self.args:
-            list_modules = []
-            #keep only modules with GUI
-            for m in modules_list:
-              if m not in modules_root_dir:
-                list_modules.insert(0,m)
-              else:
-                fr1 = os.path.join(modules_root_dir[m],"share","salome","resources",m.lower(),"SalomeApp.xml")
-                fr2 = os.path.join(modules_root_dir[m],"share","salome","resources","SalomeApp.xml")
-                if os.path.exists(fr1) or os.path.exists(fr2):
-                  list_modules.insert(0,m)
-            list_modules.reverse()
-            self.SCMD2+=['--modules (%s)' % ":".join(list_modules)]
-            pass
-        if 'language' in self.args:
-            self.SCMD2+=['--language=%s' % self.args['language']]
-        #print(self.SCMD1)
-        #print(self.SCMD2)
-        pass
-
-    def setpath(self,modules_list,modules_root_dir):
-        list_modules = modules_list[:]
-        list_modules.reverse()
-        if self.args["gui"] :
-            list_modules = ["KERNEL", "GUI"] + list_modules
-        else :
-            list_modules = ["KERNEL"] + list_modules
-
-        cata_path=get_cata_path(list_modules,modules_root_dir)
-
-        if ("gui" in self.args) & ('moduleCatalog' in self.args['embedded']):
-            #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
-            self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
-        else:
-            self.CMD=self.SCMD1 + self.SCMD2
-        if 'test' in self.args:
-            self.CMD+=['-test'] + self.args['test']
-        elif 'play' in self.args:
-            self.CMD+=['-play'] + self.args['play']
-
-        if self.args["gdb_session"] or self.args["ddd_session"]:
-            f = open(".gdbinit4salome", "w")
-            f.write("set args ")
-            args = " ".join(self.CMD[1:])
-            args = args.replace("(", "\(")
-            args = args.replace(")", "\)")
-            f.write(args)
-            f.write("\n")
-            f.close()
-            if self.args["ddd_session"]:
-                self.CMD = ["ddd", "--command=.gdbinit4salome", self.CMD[0]]
-            elif self.args["gdb_session"]:
-                self.CMD = ["xterm", "-e", "gdb", "--command=.gdbinit4salome", self.CMD[0]]
-                pass
-            pass
-
-        if self.args["valgrind_session"]:
-            l = ["valgrind"]
-            val = os.getenv("VALGRIND_OPTIONS")
-            if val:
-                l += val.split()
-                pass
-            self.CMD = l + self.CMD
-            pass
-#
-# -----------------------------------------------------------------------------
-
-def startGUI(clt):
-    """Salome Session Graphic User Interface activation"""
-    import Engines
-    import SALOME
-    import SALOMEDS
-    import SALOME_ModuleCatalog
-    import SALOME_Session_idl
-    session=clt.waitNS("/Kernel/Session",SALOME.Session)
-    session.GetInterface()
-
-# -----------------------------------------------------------------------------
-
-def startSalome(args, modules_list, modules_root_dir):
-    #print(400*"*")
-    #print(args)
-    """Launch all SALOME servers requested by args"""
-    init_time = os.times()
-
-    if verbose(): print("startSalome ", args)
-
-    #
-    # Set server launch command
-    #
-    if 'server_launch_mode' in args:
-        Server.set_server_launch_mode(args['server_launch_mode'])
-
-    #
-    # Wake up session option
-    #
-    if args['wake_up_session']:
-        if "OMNIORB_CONFIG" not in os.environ:
-            from salome_utils import generateFileName
-            omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
-            kwargs={}
-            if omniorbUserPath is not None:
-                kwargs["with_username"]=True
-
-            last_running_config = generateFileName(omniorbUserPath, prefix="omniORB",
-                                                   suffix="last",
-                                                   extension="cfg",
-                                                   hidden=True,
-                                                   **kwargs)
-            os.environ['OMNIORB_CONFIG'] = last_running_config
-            pass
-        pass
-
-    #
-    # Initialisation ORB and Naming Service
-    #
-
-    addToPidict(args)
-
-    #
-    # Wake up session option
-    #
-    if args['wake_up_session']:
-        import Engines
-        import SALOME
-        import SALOMEDS
-        import SALOME_ModuleCatalog
-        import SALOME_Session_idl
-        session = clt.waitNS("/Kernel/Session",SALOME.Session)
-        status = session.GetStatSession()
-        if status.activeGUI:
-            from salome_utils import getPortNumber
-            port = getPortNumber()
-            msg  = "Warning :"
-            msg += "\n"
-            msg += "Session GUI for port number %s is already active."%(port)
-            msg += "\n"
-            msg += "If you which to wake up another session,"
-            msg += "\n"
-            msg += "please use variable OMNIORB_CONFIG"
-            msg += "\n"
-            msg += "to get the correct session object in naming service."
-            sys.stdout.write(msg+"\n")
-            sys.stdout.flush()
-            return clt
-        session.GetInterface()
-        args["session_object"] = session
-        return clt
-
-    # Launch Logger Server (optional)
-    # and wait until it is registered in naming service
-    #
-
-    if args['logger']:
-        myServer=LoggerServer(args)
-        myServer.run()
-        clt.waitLogger("Logger")
-        addToPidict(args)
-
-
-    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()
-
-    # ASV start GUI without Loader
-    #if args['gui']:
-    #    session.GetInterface()
-
-    #
-    # additional external python interpreters
-    #
-    nbaddi=0
-
-    try:
-        if 'interp' in args:
-            nbaddi = args['interp']
-    except:
-        import traceback
-        traceback.print_exc()
-        print("-------------------------------------------------------------")
-        print("-- to get an external python interpreter:runSalome --interp=1")
-        print("-------------------------------------------------------------")
-
-    if verbose(): print("additional external python interpreters: ", nbaddi)
-    if nbaddi:
-        for i in range(nbaddi):
-            print("i=",i)
-            anInterp=InterpServer(args)
-            anInterp.run()
-
-    # set PYTHONINSPECT variable (python interpreter in interactive mode)
-    if args['pinter']:
-        os.environ["PYTHONINSPECT"]="1"
-        try:
-            import readline
-        except ImportError:
-            pass
-
-# -----------------------------------------------------------------------------
-
-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.
-    """
-    global process_id
-
-    clt=None
-    try:
-        startSalome(args, modules_list, modules_root_dir)
-    except:
-        import traceback
-        traceback.print_exc()
-        print()
-        print()
-        print("--- Error during Salome launch ---")
-
-    # print(process_id)
-
-    from addToKillList import addToKillList
-    from killSalomeWithPort import getPiDict
-
-    filedict = getPiDict(args['port'])
-    for pid, cmd in list(process_id.items()):
-        addToKillList(pid, cmd, args['port'])
-        pass
-        
-    import salome
-    salome.standalone()
-
-    SalomeAppSLConfig=os.getenv("SalomeAppConfig","")
-    os.putenv("SalomeAppSLConfig", SalomeAppSLConfig)
-
-
-    if args["gui"] and not args['launcher_only']:
-        mySessionServ = SessionServer(args,args['modules'],modules_root_dir)
-        mySessionServ.setpath(modules_list,modules_root_dir)
-        mySessionServ.run()
-        addToPidict(args)
-
-
-    if verbose(): 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)
-
-    #
-    #  Print Naming Service directory list
-    #
-
-    if clt != None:
-        if verbose():
-            print()
-            print(" --- registered objects tree in Naming Service ---")
-            clt.showNS()
-            pass
-
-        # run python scripts, passed as command line arguments
-        toimport = []
-        if 'gui' in args and 'session_gui' in args:
-            if not args['gui'] or not args['session_gui']:
-                if 'study_hdf' in args:
-                    toopen = args['study_hdf']
-                    if toopen:
-                        import salome
-                        salome.salome_init(path=toopen)
-                if 'pyscript' in args:
-                    toimport = args['pyscript']
-        from salomeContextUtils import formatScriptsAndArgs
-        command = formatScriptsAndArgs(toimport, escapeSpaces=True)
-        if command:
-            proc = subprocess.Popen(command, shell=True)
-            addToKillList(proc.pid, command, args['port'])
-            res = proc.wait()
-            if res: sys.exit(1) # if there's an error when executing script, we should explicitly exit
-
-    return clt
-
-def execScript(script_path):
-    print('executing', script_path)
-    sys.path.insert(0, os.path.realpath(os.path.dirname(script_path)))
-    exec(compile(open(script_path).read(), script_path, 'exec'),globals())
-    del sys.path[0]
-
-# -----------------------------------------------------------------------------
-
-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.
-    """
-    from salome_utils import getTmpDir
-    fileEnv = getTmpDir()
-    from salome_utils import getUserName
-    fileEnv += getUserName() + "_" + 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
-
-# -----------------------------------------------------------------------------
-
-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)
-    from searchFreePort import searchFreePort
-    searchFreePort(args, 0)
-    clt = useSalome(args, modules_list, modules_root_dir)
-    return clt
-
-# -----------------------------------------------------------------------------
-
-def addToPidict(args):
-    global process_id
-    from addToKillList import addToKillList
-    for pid, cmd in list(process_id.items()):
-        addToKillList(pid, cmd, args['port'])
-
-# -----------------------------------------------------------------------------
-
-def main(exeName=None):
-    """Salome launch as a main application"""
-
-    from salome_utils import getHostName
-    keep_env = not os.getenv('SALOME_PLEASE_SETUP_ENVIRONMENT_AS_BEFORE')
-    args, modules_list, modules_root_dir = setenv.get_config(exeName=exeName, keepEnvironment=keep_env)
-    print("runSalome running on %s" % getHostName())
-
-    # --
-    #setenv.main()
-    setenv.set_env(args, modules_list, modules_root_dir, keepEnvironment=keep_env)
-    clt = useSalome(args, modules_list, modules_root_dir)
-    return clt,args
-
-# -----------------------------------------------------------------------------
-
-def foreGround(clt, args):
-    # --
-    if "session_object" not in args:
-        return
-    session = args["session_object"]
-    # --
-    # Wait until gui is arrived
-    # tmax = nbtot * dt
-    # --
-    gui_detected = False
-    dt = 0.1
-    nbtot = 100
-    nb = 0
-    session_pid = None
-    while 1:
-        try:
-            status = session.GetStatSession()
-            gui_detected = status.activeGUI
-            session_pid = session.getPID()
-        except:
-            pass
-        if gui_detected:
-            break
-        from time import sleep
-        sleep(dt)
-        nb += 1
-        if nb == nbtot:
-            break
-        pass
-    # --
-    if not gui_detected:
-        return
-    # --
-    from salome_utils import getPortNumber
-    port = getPortNumber()
-    # --
-    server = Server({})
-    if sys.platform == "win32":
-      server.CMD = [os.getenv("PYTHONBIN"), "-m", "killSalomeWithPort", "--spy", "%s"%(session_pid or os.getpid()), "%s"%(port)]
-    else:
-      server.CMD = ["killSalomeWithPort.py", "--spy", "%s"%(session_pid or os.getpid()), "%s"%(port)]
-    server.run(True)
-    # os.system("killSalomeWithPort.py --spy %s %s &"%(os.getpid(), port))
-    # --
-    dt = 1.0
-    try:
-        while 1:
-            try:
-                status = session.GetStatSession()
-                assert status.activeGUI
-            except:
-                break
-            from time import sleep
-            sleep(dt)
-            pass
-        pass
-    except KeyboardInterrupt:
-        from killSalomeWithPort import killMyPort
-        killMyPort(port)
-        pass
-    return
-#
-
-def runSalome():
-    clt,args = main()
-    # --
-    test = args['gui'] and args['session_gui']
-    test = test or args['wake_up_session']
-    # --
-    # The next test covers the --pinter option or if var PYTHONINSPECT is set
-    # --
-    test = test and not os.environ.get('PYTHONINSPECT')
-    # --
-    # The next test covers the python -i $KERNEL_ROOT_DIR/bin/salome/runSalome.py case
-    # --
-    try:
-        from ctypes import POINTER, c_int, cast, pythonapi
-        iflag_ptr = cast(pythonapi.Py_InteractiveFlag, POINTER(c_int))
-        test = test and not iflag_ptr.contents.value
-    except:
-        pass
-    # --
-#    test = test and os.getenv("SALOME_TEST_MODE", "0") != "1"
-    test = test and args['foreground']
-    # --
-    if test:
-        from time import sleep
-        sleep(3.0)
-        foreGround(clt, args)
-        pass
-    pass
-#
-
-# -----------------------------------------------------------------------------
-
-if __name__ == "__main__":
-    runSalome()
-#
index be7fc03d44b69fd795ba561572ff2813f2b53a5f..3cc93d22de0da7b7ffd243527eb979a06f31fade 100755 (executable)
@@ -32,6 +32,7 @@ import sys
 import platform
 
 from salomeContextUtils import SalomeContextException
+from addToKillList import killList
 
 def usage():
   msg = '''\
@@ -39,23 +40,25 @@ Usage: salome [command] [options] [--config=<file,folder,...>]
 
 Commands:
 =========
-    start           Start a new SALOME instance.
+    start           Start a new SALOME instance. Start a single SALOME_Session_Server_No_Server
+                    process with environment relevant to the application and hosting all servants in it.
     context         Initialize SALOME context. Current environment is extended.
     shell           Initialize SALOME context, attached to the last created SALOME
                     instance if any, and executes scripts passed as command arguments.
                     User works in a Shell terminal. SALOME environment is set but
                     application is not started.
-    connect         Connect a Python console to the active SALOME instance.
-    remote          run command in SALOME environment from remote call, ssh or rsh.
-    kill <port(s)>  Terminate SALOME instances running on given ports for current user.
-                    Port numbers must be separated by blank characters.
-    killall         Terminate *all* SALOME running instances for current user.
-                    Do not start a new one.
     test            Run SALOME tests.
     info            Display some information about SALOME.
     doc <module(s)> Show online module documentation (if available).
                     Module names must be separated by blank characters.
     help            Show this message.
+    remote          run command in SALOME environment from remote call, ssh or rsh.
+    withsession     Start a new SWS SALOME instance with multiple servers hosting all servants.
+    connect         In SWS context, Connect a Python console to the active SALOME instance.
+    kill <port(s)>  In SWS context, Terminate SALOME instances running on given ports for current user.
+                    Port numbers must be separated by blank characters.
+    killall         Terminate *all* SALOME running SWS instances for current user.
+                    Do not start a new one.
 
 If no command is given, default is start.
 
@@ -223,8 +226,8 @@ class SalomeContext:
     options = args[1:]
 
     availableCommands = {
-      'start'   : '_runAppli',
-      'sessionless' : '_sessionless',
+      'start'   : '_sessionless',
+      'withsession' : '_runAppli',
       'context' : '_setContext',
       'shell'   : '_runSession',
       'remote'  : '_runRemote',
@@ -273,7 +276,7 @@ class SalomeContext:
         usage()
         return 0
       # try to default to "start" command
-      command = "_runAppli"
+      command = "_sessionless"
 
     try:
       res = getattr(self, command)(options) # run appropriate method
@@ -350,12 +353,12 @@ class SalomeContext:
     if args is None:
       args = []
     # Initialize SALOME environment
-    sys.argv = ['runSalome'] + args
+    sys.argv = ['runSalomeOld'] + args
     import setenv
-    setenv.main(True, exeName="salome start")
+    setenv.main(True, exeName="salome withsession")
 
-    import runSalome
-    runSalome.runSalome()
+    import runSalomeOld
+    runSalomeOld.runSalome()
     return 0
   #
 
@@ -449,7 +452,6 @@ class SalomeContext:
       else:
         proc = subprocess.Popen(["killSalomeWithPort.py", str(port)])
       proc.communicate()
-
     return 0
   #
 
@@ -476,6 +478,7 @@ class SalomeContext:
       from killSalome import killAllPorts
       killAllPorts()
       pass
+    killList()
     return 0
   #
 
@@ -570,7 +573,7 @@ Available options are:
 
     if "-v" in args or "--version" in args:
       print("Running with python", platform.python_version())
-      return self._runAppli(["--version"])
+      return self._sessionless(["--version"])
 
     return 0
   #
index 6274ddcecd00e91772175566efb5d1a46db13012..0129281cd129c461dad370fc69d4641d0d56f70a 100644 (file)
@@ -19,7 +19,7 @@
 
 #include "KernelBasis.hxx"
 
-static bool DEFAULT_SSL_MODE = false;
+static bool DEFAULT_SSL_MODE = true;
 static bool GUI_MODE = false;
 
 // IOR of SALOME_Embedded_NamingService servant
index 80449ac00512a39bbeddb70e04f24516cb325958..175a86c30c6d2dd16e1af1d1affe5ddb60bc39f9 100644 (file)
@@ -166,20 +166,15 @@ myStudy, myStudyName = None,None
 
 salome_initial=True
 
-__EMB_SERVANT_ENV_VAR_NAME = "SALOME_EMB_SERVANT"
-
 def standalone():
-    import os
-    os.environ[__EMB_SERVANT_ENV_VAR_NAME] = "1"
+    pass
+
+def withServers():
     import KernelBasis
-    KernelBasis.setSSLMode(True)
+    KernelBasis.setSSLMode(False)
 
 def salome_init(path=None, embedded=False):
-    import os
     import KernelBasis
-    if __EMB_SERVANT_ENV_VAR_NAME in os.environ:
-        KernelBasis.setSSLMode(True)
-    #
     if KernelBasis.getSSLMode():
         if KernelBasis.getIOROfEmbeddedNS() == "":
             salome_init_without_session(path, embedded)
index cdf2b1990f9c6b231516a6645db080f799c3523d..31e222571ba7b2ba842e7771a0d9a8e9b8e3b462 100644 (file)
@@ -24,6 +24,7 @@
 
 #include "SALOME_KernelServices.hxx"
 #include "Basics_Utils.hxx"
+#include "KernelBasis.hxx"
 
 #include <SALOMEconfig.h>
 #include CORBA_CLIENT_HEADER(SALOME_TestComponent)
@@ -36,6 +37,7 @@
 
 void KernelHelpersUnitTests::setUp()
 {
+  setSSLMode(false);
 }
 
 // ============================================================================
index 919f2f4514be8279abf001c5daf1695b3db34d00..f0e1c0ec0461075b075794274df6d1abbdbb93a2 100644 (file)
@@ -23,7 +23,7 @@
 
 import sys, os,signal,string,subprocess
 import subprocess
-import runSalome
+import runSalomeOld
 import setenv
 import orbmodule
 import TestKiller
@@ -39,7 +39,7 @@ clt=orbmodule.client()
 
 # launch CORBA logger server
 
-myServer=runSalome.LoggerServer(args)
+myServer=runSalomeOld.LoggerServer(args)
 myServer.run()
 clt.waitLogger("Logger")
 
@@ -50,6 +50,6 @@ ret = subprocess.call(command)
 
 # kill Test process
 
-TestKiller.killProcess(runSalome.process_id)
+TestKiller.killProcess(runSalomeOld.process_id)
 TestKiller.closeSalome()
 exit(ret)
index 296f35f469f3617207f10883bd822b47e9c7752d..6b803e36e37dc18f9a54755987066bff90311114 100644 (file)
@@ -43,7 +43,7 @@ Launcher::Job_PythonSALOME::addJobTypeSpecificScript(std::ofstream & launch_scri
   struct stat statbuf;
   if(stat(getenv("APPLI"), &statbuf) ==0 &&  S_ISREG(statbuf.st_mode))
       // case where AppliPath hold a salome launcher file
-      launch_script_stream << _resource_definition.AppliPath << " shell -p \"$appli_port\" python " << _job_file_name_complete << " > logs/python_" << _launch_date << ".log 2>&1" << std::endl;
+      launch_script_stream << _resource_definition.AppliPath << " shell -- python " << _job_file_name_complete << " > logs/python_" << _launch_date << ".log 2>&1" << std::endl;
   else
-      launch_script_stream << _resource_definition.AppliPath << "/salome shell -p \"$appli_port\" python " << _job_file_name_complete << " > logs/python_" << _launch_date << ".log 2>&1" << std::endl;
+      launch_script_stream << _resource_definition.AppliPath << "/salome shell -- python " << _job_file_name_complete << " > logs/python_" << _launch_date << ".log 2>&1" << std::endl;
 }
index 394d3aac67d6358ea48c3be2cacf84a7b2730127..58a1a8dbcb8371e30b0a08bbf52fb0854b481337 100644 (file)
@@ -133,50 +133,12 @@ Launcher::Job_SALOME::buildSalomeScript(Batch::Parametre params)
     launch_script_stream << "} > $CATALOG_FILE" << std::endl;
     launch_script_stream << "fi" << std::endl;
   }
-  if(_activateSession)
-  {
-    // Create file for ns-port-log
-    if (is_launcher_file)
-        // for a salome application file, we write NS_PORT_FILE_PATH in working directory
-        launch_script_stream << "NS_PORT_FILE_PATH=$(mktemp " << work_directory << "/nsport_" << _launch_date << "_XXXXXX) &&\n";
-    else
-        launch_script_stream << "NS_PORT_FILE_PATH=$(mktemp " << _resource_definition.AppliPath << "/USERS/nsport_XXXXXX) &&\n";
-
-    // Launch SALOME with an appli
-    if (is_launcher_file)
-        launch_script_stream << _resource_definition.AppliPath << " start --terminal --ns-port-log=\"$NS_PORT_FILE_PATH\" --server-launch-mode=fork ";
-    else
-        launch_script_stream << _resource_definition.AppliPath << "/salome start --terminal --ns-port-log=\"$NS_PORT_FILE_PATH\" --server-launch-mode=fork ";
-    launch_script_stream << "> logs/salome_" << _launch_date << ".log 2>&1 &&" << std::endl;
-    launch_script_stream << "current=0 &&\n"
-                        << "stop=20 &&\n"
-                        << "while ! test -s \"$NS_PORT_FILE_PATH\"\n"
-                        << "do\n"
-                        << "  sleep 2\n"
-                        << "  current=$((current+1))\n"
-                        << "  if [ \"$current\" -eq \"$stop\" ] ; then\n"
-                        << "    echo Error Naming Service failed ! >&2\n"
-                        << "    exit\n"
-                        << "  fi\n"
-                        << "done &&\n"
-                        << "appli_port=$(cat \"$NS_PORT_FILE_PATH\") &&\n"
-                        << "rm \"$NS_PORT_FILE_PATH\" &&\n";
-  }
 
   // Call real job type
   addJobTypeSpecificScript(launch_script_stream);
   // log the exit code
   launch_script_stream << "echo $? > logs/exit_code.log" << std::endl;
 
-  // End
-  if(_activateSession)
-  {
-    if (is_launcher_file)
-        launch_script_stream << _resource_definition.AppliPath << " kill \"$appli_port\"" << std::endl;
-    else
-        launch_script_stream << _resource_definition.AppliPath << "/salome kill \"$appli_port\"" << std::endl;
-  }
-
   // Return
   launch_script_stream.flush();
   launch_script_stream.close();
index 9acc9ed45fc2c2746fe3a0f37927570a092289d8..2b59643e3924447506ad2ae1af67e0f0a096a524 100644 (file)
@@ -23,7 +23,7 @@
 
 import sys, os,signal,string,subprocess
 import subprocess
-import runSalome
+import runSalomeOld
 import setenv
 import orbmodule
 import TestKiller
@@ -47,26 +47,26 @@ clt=orbmodule.client()
 
 # launch CORBA logger server
 
-myServer=runSalome.LoggerServer(args)
+myServer=runSalomeOld.LoggerServer(args)
 myServer.run()
 clt.waitLogger("Logger")
 
 # launch registry server
 
-myServer=runSalome.RegistryServer(args)
+myServer=runSalomeOld.RegistryServer(args)
 myServer.run()
 clt.waitNS("/Registry")
 
 # launch module catalog server
 
-cataServer=runSalome.CatalogServer(args)
+cataServer=runSalomeOld.CatalogServer(args)
 cataServer.setpath(modules_list,modules_root_dir)
 cataServer.run()
 clt.waitNS("/Kernel/ModulCatalog")
 
 # launch launcher server
 
-myCmServer = runSalome.LauncherServer(args)
+myCmServer = runSalomeOld.LauncherServer(args)
 myCmServer.setpath(modules_list,modules_root_dir)
 myCmServer.run()
 clt.waitNS("/SalomeLauncher")
@@ -87,6 +87,6 @@ launcher.Shutdown()
 
 addToKillList.killList()
 
-TestKiller.killProcess(runSalome.process_id)
+TestKiller.killProcess(runSalomeOld.process_id)
 TestKiller.closeSalome()
 exit(ret)
index f09e62e791dae9fb72de7acc1bad7cfa715b3395..efbc0ea26d40d5373d3f3bcf1e832d91d35291e1 100644 (file)
@@ -28,7 +28,7 @@
 #
 import sys, os,signal,string,subprocess
 import subprocess
-import runSalome
+import runSalomeOld
 import setenv
 import orbmodule
 import TestKiller
@@ -52,26 +52,26 @@ clt=orbmodule.client()
 
 # launch CORBA logger server
 
-myServer=runSalome.LoggerServer(args)
+myServer=runSalomeOld.LoggerServer(args)
 myServer.run()
 clt.waitLogger("Logger")
 
 # launch registry server
 
-myServer=runSalome.RegistryServer(args)
+myServer=runSalomeOld.RegistryServer(args)
 myServer.run()
 clt.waitNS("/Registry")
 
 # launch module catalog server
 
-cataServer=runSalome.CatalogServer(args)
+cataServer=runSalomeOld.CatalogServer(args)
 cataServer.setpath(modules_list,modules_root_dir)
 cataServer.run()
 clt.waitNS("/Kernel/ModulCatalog")
 
 # launch container manager server
 
-myCmServer = runSalome.LauncherServer(args)
+myCmServer = runSalomeOld.LauncherServer(args)
 myCmServer.setpath(modules_list,modules_root_dir)
 myCmServer.run()
 clt.waitNS("/SalomeLauncher")
@@ -95,6 +95,6 @@ launcher.Shutdown()
 
 addToKillList.killList()
 
-TestKiller.killProcess(runSalome.process_id)
+TestKiller.killProcess(runSalomeOld.process_id)
 TestKiller.closeSalome()
 exit(ret)
index c577da1f93cf830811bc325e4d09943df66d02c8..a8409e0c8bddde7dd0d1380c9fc20861aa710130 100644 (file)
@@ -23,7 +23,7 @@
 
 import sys, os,signal,string,subprocess
 import subprocess
-import runSalome
+import runSalomeOld
 import setenv
 import orbmodule
 import TestKiller
@@ -46,7 +46,7 @@ clt=orbmodule.client()
 
 # launch CORBA logger server
 
-myServer=runSalome.LoggerServer(args)
+myServer=runSalomeOld.LoggerServer(args)
 myServer.run()
 clt.waitLogger("Logger")
 
@@ -59,6 +59,6 @@ ret = subprocess.call(command)
 
 # kill Test process
 
-TestKiller.killProcess(runSalome.process_id)
+TestKiller.killProcess(runSalomeOld.process_id)
 TestKiller.closeSalome()
 exit(ret)
index bb058bad144190fb07f133ba5257946379a9707f..437de25450199684427e2d072a7cc598dedf0357 100644 (file)
@@ -23,7 +23,7 @@
 
 import sys, os,signal,string,subprocess
 import subprocess
-import runSalome
+import runSalomeOld
 import orbmodule
 import TestKiller
 import setenv
@@ -39,7 +39,7 @@ clt=orbmodule.client()
 
 # launch CORBA logger server
 
-myServer=runSalome.LoggerServer(args)
+myServer=runSalomeOld.LoggerServer(args)
 myServer.run()
 clt.waitLogger("Logger")
 
@@ -50,6 +50,6 @@ ret = subprocess.call(command)
 
 # kill Test process
 
-TestKiller.killProcess(runSalome.process_id)
+TestKiller.killProcess(runSalomeOld.process_id)
 TestKiller.closeSalome()
 exit(ret)
index aa3bd63456bbba79778ffa69a9131cca5d39d2bd..da97104a958354f614613b5486b85bf88d95fe15 100644 (file)
@@ -23,7 +23,7 @@
 
 import sys, os,signal,string,subprocess
 import subprocess
-import runSalome
+import runSalomeOld
 import orbmodule
 import TestKiller
 import setenv
@@ -39,7 +39,7 @@ clt=orbmodule.client()
 
 # launch CORBA logger server
 
-myServer=runSalome.LoggerServer(args)
+myServer=runSalomeOld.LoggerServer(args)
 myServer.run()
 clt.waitLogger("Logger")
 
@@ -50,6 +50,6 @@ ret = subprocess.call(command)
 
 # kill Test process
 
-TestKiller.killProcess(runSalome.process_id)
+TestKiller.killProcess(runSalomeOld.process_id)
 TestKiller.closeSalome()
 exit(ret)
index d4a5979461240a1a6805408ecfe810ef917c0ddf..a785794fe69cd185576a500ff7500cba420d3bc8 100644 (file)
@@ -23,7 +23,6 @@
 
 import sys, signal,string,subprocess
 import subprocess
-import runSalome
 import setenv
 
 # get SALOME environment :
index a6cdbf1cd6235df12bf59e1de2db90cc3c6d23c2..d433a935a92c0280d3621e216c377055c47aa785 100644 (file)
@@ -24,7 +24,7 @@
 
 import sys, os,signal,string,subprocess
 import subprocess
-import runSalome
+import runSalomeOld
 import orbmodule
 import TestKiller
 import setenv
@@ -40,7 +40,7 @@ clt=orbmodule.client()
 
 # launch CORBA logger server
 
-myServer=runSalome.LoggerServer(args)
+myServer=runSalomeOld.LoggerServer(args)
 myServer.run()
 clt.waitLogger("Logger")
 
@@ -53,5 +53,5 @@ ret = subprocess.call(command)
 
 # kill Test process
 
-TestKiller.killProcess(runSalome.process_id)
+TestKiller.killProcess(runSalomeOld.process_id)
 exit(ret)
index ea9aedf229de761511f16ff53ff6ea0ddfd76e44..7b6f0e5bd505d7915cc8cf89c5a893d4a825213a 100644 (file)
@@ -24,7 +24,7 @@
 
 import sys, os,signal,string,subprocess
 import subprocess
-import runSalome
+import runSalomeOld
 import setenv
 import orbmodule
 import TestKiller
@@ -47,26 +47,26 @@ clt=orbmodule.client()
 
 # launch CORBA logger server
 
-myServer=runSalome.LoggerServer(args)
+myServer=runSalomeOld.LoggerServer(args)
 myServer.run()
 clt.waitLogger("Logger")
 
 # launch registry server
 
-myServer=runSalome.RegistryServer(args)
+myServer=runSalomeOld.RegistryServer(args)
 myServer.run()
 clt.waitNS("/Registry")
 
 # launch module catalog server
 
-cataServer=runSalome.CatalogServer(args)
+cataServer=runSalomeOld.CatalogServer(args)
 cataServer.setpath(modules_list,modules_root_dir)
 cataServer.run()
 clt.waitNS("/Kernel/ModulCatalog")
 
 # launch container manager server
 
-myCmServer = runSalome.LauncherServer(args)
+myCmServer = runSalomeOld.LauncherServer(args)
 myCmServer.setpath(modules_list,modules_root_dir)
 myCmServer.run()
 clt.waitNS("/SalomeLauncher")
@@ -84,6 +84,6 @@ launcher.Shutdown()
 
 # kill Test process
 
-TestKiller.killProcess(runSalome.process_id)
+TestKiller.killProcess(runSalomeOld.process_id)
 TestKiller.closeSalome()
 exit(ret)
index 478e9fe54138cc20ea8f83ffc2daf5601151d0fe..94e8a02f93fd3df16f96c8b179468e3ebd435fe7 100644 (file)
@@ -23,7 +23,7 @@
 
 import sys, os,signal,string,subprocess
 import subprocess
-import runSalome
+import runSalomeOld
 import orbmodule
 import TestKiller
 import setenv
@@ -39,7 +39,7 @@ clt=orbmodule.client()
 
 # launch CORBA logger server
 
-myServer=runSalome.LoggerServer(args)
+myServer=runSalomeOld.LoggerServer(args)
 myServer.run()
 clt.waitLogger("Logger")
 
@@ -50,6 +50,6 @@ ret = subprocess.call(command)
 
 # kill Test process
 
-TestKiller.killProcess(runSalome.process_id)
+TestKiller.killProcess(runSalomeOld.process_id)
 TestKiller.closeSalome()
 exit(ret)