]> SALOME platform Git repositories - modules/kernel.git/commitdiff
Salome HOME
Avoid to kill all sessions when shutting down only one
authorAnthony Geay <anthony.geay@edf.fr>
Tue, 1 Mar 2022 08:44:08 +0000 (09:44 +0100)
committerAnthony Geay <anthony.geay@edf.fr>
Tue, 1 Mar 2022 13:07:16 +0000 (14:07 +0100)
Allow to pass path to study to subprocess launching script with : -t <path_study> <path_to_py_script>

bin/killSalomeWithPort.py
bin/runSalome.py
src/KERNEL_PY/__init__.py

index 1a7b7c5dadfd304861f54610f37e62330b4cb688..7e9c52204bf40132885002cf130741e953e3cd45 100755 (executable)
@@ -125,8 +125,7 @@ def appliCleanOmniOrbConfig(port):
         # outside application context
         return
 
-    if verbose():
-        print("Cleaning OmniOrb config for port {}".format(port))
+    logging.getLogger().debug("Cleaning OmniOrb config for port {}".format(port))
 
     omniorb_config = generateFileName(omniorb_user_path,
                                       prefix='omniORB',
@@ -141,10 +140,10 @@ def appliCleanOmniOrbConfig(port):
                                            extension='cfg',
                                            hidden=True,
                                            with_username=True)
-
-    if os.access(last_running_config, os.F_OK):
-        if sys.platform == 'win32' or (os.access(omniorb_config, os.F_OK) and \
-                                       osp.samefile(last_running_config, omniorb_config)):
+    logging.getLogger().debug("Omniorb_config file deduced by port : {}".format(omniorb_config))
+    logging.getLogger().debug("Omniorb_config file of last : {}".format(last_running_config))
+    if osp.exists(last_running_config):
+        if sys.platform == 'win32' or ( osp.exists(omniorb_config) and osp.samefile(last_running_config,omniorb_config) ):
             os.remove(last_running_config)
 
     if os.access(omniorb_config, os.F_OK):
@@ -253,8 +252,7 @@ def __killPids(pids):
             logger.debug("Add process with PID = {} into PIDList to kill".format(pid))
             processes.append(psutil.Process(pid))
         except psutil.NoSuchProcess:
-            if verbose():
-                print("  ------------------ Process {} not found".format(pid))
+            logger.debug("  ------------------ Process {} not found".format(pid))
     __killProcesses(processes)
 
 def __killMyPort(port, filedict):
@@ -306,37 +304,39 @@ def __guessPiDictFilename(port):
 
     return None
 
-def killMyPortSSL(*ports):
-    """ Called by runSalome.py after CTRL-C"""
-    for port in ports:
-        # ensure port is an integer
-        with suppress(ValueError):
-            port = int(port)
-
-        with suppress(Exception):
-            # DO NOT REMOVE NEXT LINE: it tests PortManager availability!
-            from PortManager import releasePort
-            # get pidict file
-            filedict = getPiDict(port)
-            if not osp.isfile(filedict): # removed by previous call, see (1) above
-                if verbose():
-                    print("SALOME session on port {} is already stopped".format(port))
-                # remove port from PortManager config file
-                with suppress(ImportError):
-                    if verbose():
-                        print("Removing port from PortManager configuration file")
-                    releasePort(port)
-                return
-        try:
-            # DO NOT REMOVE NEXT LINE: it tests PortManager availability!
-            import PortManager # pragma pylint: disable=unused-import
-            for file_path in glob('{}*'.format(getPiDict(port))):
-                __killMyPort(port, file_path)
-        except ImportError:
-            __killMyPort(port, __guessPiDictFilename(port))
+def killProcessSSL(port, pids_list):
+    """ Called by runSalome.py after CTRL-C.
+    This method :
+    - Kill all PIDS in pids
+    - update file of pidict 
+    """
+    __killPids(pids_list)
 
-        # clear-up omniOrb config files
-        appliCleanOmniOrbConfig(port)
+    with suppress(ValueError):
+        port = int(port)
+        
+    for filedict in glob('{}*'.format(getPiDict(port))):
+        with suppress(Exception), open(filedict, 'rb') as fpid:
+            logging.getLogger().debug("Removing following PIDS from file \"{}\" : {}"
+            .format(filedict,pids_list))
+            pids_lists_in_file = pickle.load(fpid)
+        for dico_of_pids in pids_lists_in_file:
+            for pid in pids_list:
+                if pid in dico_of_pids:
+                    del dico_of_pids[pid]
+        pids_lists_in_file = [elt for elt in pids_lists_in_file if len(elt)>0]
+        if len(pids_lists_in_file) == 0:
+            try:
+                logging.getLogger().debug("List of PIDS to Kill is now empty -> Remove file \"{}\"".format(filedict))
+                os.remove(filedict)
+            except:
+                pass
+            continue
+        with suppress(Exception), open(filedict, 'wb') as fpid:
+            logging.getLogger().debug("Writing back into file \"{}\"".format(filedict))
+            pickle.dump(pids_lists_in_file,fpid)
+    # clear-up omniOrb config files
+    appliCleanOmniOrbConfig(port)
 
 def killMyPort(*ports):
     """
index 422631b68340130606e80482e768c60617c57061..f89d1be6642f8a9cff9cbec08144945a61ec0cae 100755 (executable)
@@ -171,14 +171,6 @@ def execScript(script_path):
 
 # -----------------------------------------------------------------------------
 
-def addToPidict(args):
-    global process_id
-    from addToKillList import addToKillList
-    for pid, cmd in list(process_id.items()):
-        addToKillList(pid, cmd)
-
-# -----------------------------------------------------------------------------
-
 def main(exeName=None):
     """Salome launch as a main application"""
     keep_env = not os.getenv('SALOME_PLEASE_SETUP_ENVIRONMENT_AS_BEFORE')
@@ -190,13 +182,14 @@ def main(exeName=None):
     ior_fakens_filename = useSalome(args, modules_list, modules_root_dir)
     # Management of -t <script.py>
     toimport = []
+    env = os.environ
     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)
+                    os.environ["PATH_TO_STUDY_FILE_TO_INITIATE"] = toopen
+                    logger.debug("An input Study has been specified {} -> pass it with PATH_TO_STUDY_FILE_TO_INITIATE env var".format(toopen))
             if 'pyscript' in args:
                 toimport = args['pyscript']
     from salomeContextUtils import formatScriptsAndArgs
@@ -204,7 +197,7 @@ def main(exeName=None):
     command = formatScriptsAndArgs(toimport, escapeSpaces=True)
     if command:
         logger.debug("Launching following shell command : {}".format(str(command)))
-        proc = subprocess.Popen(command, shell=True)
+        proc = subprocess.Popen(command, shell=True, env = env)
         addToKillList(proc.pid, command)
         res = proc.wait()
         if res: sys.exit(1) 
@@ -279,14 +272,6 @@ def foreGround(args, ior_fakens_filename):
     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:
@@ -302,9 +287,9 @@ def foreGround(args, ior_fakens_filename):
         pass
     except KeyboardInterrupt:
         logger.debug("Keyboard requested : killing all process attached to port {}".format(port))
-        from killSalomeWithPort import killMyPortSSL
-        killMyPortSSL(port)
-        pass
+    finally:
+        from killSalomeWithPort import killProcessSSL
+        killProcessSSL(port,[session_pid])
     return
 #
 
index d2be57dfc30154a84127bf78a2d12c67f7a4737a..aa27871762a8c4525efe337aca7f4ea03c3a26ae 100644 (file)
@@ -177,9 +177,14 @@ def salome_init(path=None, embedded=False, iorfakensfile=None):
     """
     :param iorfakensfile: filename inside which IOR of fake NS will be written
     """
+    PATH_TO_STUDY_FILE_TO_INITIATE = "PATH_TO_STUDY_FILE_TO_INITIATE"
     import KernelBasis
     if KernelBasis.getSSLMode():
         if KernelBasis.getIOROfEmbeddedNS() == "":
+            import os
+            # make runSalome.py -t study.hdf toto.py
+            if path is None and PATH_TO_STUDY_FILE_TO_INITIATE in os.environ:
+                path = os.environ[PATH_TO_STUDY_FILE_TO_INITIATE]
             salome_init_without_session(path, embedded, iorfakensfile)
         else:
             salome_init_without_session_attached(path, embedded)