Salome HOME
#17872 [CEA] /tmp/.salome_PortManager.lock permission denied
[modules/kernel.git] / bin / PortManager.py
index 7e83d4696e5f6705b6db2e4329227693ce16ff5a..e0584ac81529000f029ad5267f0b1b6a66dbd8b9 100644 (file)
@@ -1,6 +1,6 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 #  -*- coding: iso-8859-1 -*-
-# Copyright (C) 2007-2017  CEA/DEN, EDF R&D, OPEN CASCADE
+# Copyright (C) 2007-2019  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
@@ -35,11 +35,11 @@ __PORT_MAX_NUMBER = 2910
 import logging
 def createLogger():
   logger = logging.getLogger(__name__)
-#  logger.setLevel(logging.DEBUG)
+  #logger.setLevel(logging.DEBUG)
   logger.setLevel(logging.INFO)
   ch = logging.StreamHandler()
   ch.setLevel(logging.DEBUG)
-  formatter = logging.Formatter("%(levelname)s:%(threadName)s:%(message)s")
+  formatter = logging.Formatter("%(levelname)s:%(threadName)s:%(pathname)s[%(lineno)s]%(message)s")
   ch.setFormatter(formatter)
   logger.addHandler(ch)
   return logger
@@ -76,19 +76,27 @@ def _getConfigurationFilename():
 
   from salome_utils import generateFileName
   portmanager_config = generateFileName(omniorbUserPath,
-                                        prefix="omniORB",
+                                        prefix="salome",
                                         suffix="PortManager",
                                         extension="cfg",
                                         hidden=True)
   import tempfile
   temp = tempfile.NamedTemporaryFile()
-  lock_file = os.path.join(os.path.dirname(temp.name), ".omniORB_PortManager.lock")
+  lock_file = os.path.join(os.path.dirname(temp.name), ".salome_PortManager.lock")
+  try:
+    with open(lock_file, 'wb'):
+      pass
+  except IOError:
+    pass
   temp.close()
 
   return (portmanager_config, lock_file)
 #
 
-def __isPortUsed(port, busy_ports):
+def __isPortUsed(port, config):
+  busy_ports = []
+  for ports in config.values():
+    busy_ports += ports
   return (port in busy_ports) or __isNetworkConnectionActiveOnPort(port)
 #
 
@@ -97,7 +105,7 @@ def __isNetworkConnectionActiveOnPort(port):
   #        netstat options -l and -t are unavailable
   #        grep command is unavailable
   if sys.platform == "win32":
-    cmd = ['netstat','-a','-n','-p tcp']
+    cmd = ['netstat','-a','-n','-p','tcp']
   else:
     cmd = ['netstat','-ant']
     pass
@@ -108,14 +116,14 @@ def __isNetworkConnectionActiveOnPort(port):
     p = Popen(cmd, stdout=PIPE, stderr=STDOUT)
     out, err = p.communicate()
   except:
-    print "Error when trying to access active network connections."
-    if err: print err
+    print("Error when trying to access active network connections.")
+    if err: print(err)
     import traceback
     traceback.print_exc()
     return False
 
-  import StringIO
-  buf = StringIO.StringIO(out)
+  from io import StringIO
+  buf = StringIO(out.decode('utf-8', 'ignore'))
   ports = buf.readlines()
   # search for TCP - LISTEN connections
   import re
@@ -129,48 +137,52 @@ def __isNetworkConnectionActiveOnPort(port):
   return False
 #
 
-def getPort(preferedPort=None):
+def getPort(preferredPort=None):
   logger.debug("GET PORT")
 
   config_file, lock_file = _getConfigurationFilename()
   oldmask = os.umask(0)
-  with open(lock_file, 'w') as lock:
+  with open(lock_file, 'rb') as lock:
     # acquire lock
     __acquire_lock(lock)
 
     # read config
-    config = {'busy_ports':[]}
+    config = {}
     logger.debug("read configuration file")
     try:
-      with open(config_file, 'r') as f:
+      with open(config_file, 'rb') as f:
         config = pickle.load(f)
     except:
       logger.info("Problem loading PortManager file: %s"%config_file)
       # In this case config dictionary is reset
 
-    logger.debug("load busy_ports: %s"%str(config["busy_ports"]))
+    logger.debug("load config: %s"%str(config))
+    appli_path = os.getenv("ABSOLUTE_APPLI_PATH", "unknown")
+    try:
+        config[appli_path]
+    except KeyError:
+        config[appli_path] = []
 
     # append port
-    busy_ports = config["busy_ports"]
-    port = preferedPort
-    if not port or __isPortUsed(port, busy_ports):
+    port = preferredPort
+    if not port or __isPortUsed(port, config):
       port = __PORT_MIN_NUMBER
-      while __isPortUsed(port, busy_ports):
+      while __isPortUsed(port, config):
         if port == __PORT_MAX_NUMBER:
           msg  = "\n"
           msg += "Can't find a free port to launch omniNames\n"
           msg += "Try to kill the running servers and then launch SALOME again.\n"
-          raise RuntimeError, msg
+          raise RuntimeError(msg)
         logger.debug("Port %s seems to be busy"%str(port))
         port = port + 1
     logger.debug("found free port: %s"%str(port))
-    config["busy_ports"].append(port)
+    config[appli_path].append(port)
 
-    # write config, for this application only (i.e. no 'other' ports)
-    logger.debug("write busy_ports: %s"%str(config["busy_ports"]))
+    # write config
+    logger.debug("write config: %s"%str(config))
     try:
-      with open(config_file, 'w') as f:
-        pickle.dump(config, f)
+      with open(config_file, 'wb') as f:
+        pickle.dump(config, f, protocol=0)
     except IOError:
       pass
 
@@ -189,30 +201,35 @@ def releasePort(port):
 
   config_file, lock_file = _getConfigurationFilename()
   oldmask = os.umask(0)
-  with open(lock_file, 'w') as lock:
+  with open(lock_file, 'rb') as lock:
     # acquire lock
     __acquire_lock(lock)
 
     # read config
-    config = {'busy_ports':[]}
+    config = {}
     logger.debug("read configuration file")
     try:
-      with open(config_file, 'r') as f:
+      with open(config_file, 'rb') as f:
         config = pickle.load(f)
     except IOError: # empty file
       pass
 
-    logger.debug("load busy_ports: %s"%str(config["busy_ports"]))
+    logger.debug("load config: %s"%str(config))
+    appli_path = os.getenv("ABSOLUTE_APPLI_PATH", "unknown")
+    try:
+        config[appli_path]
+    except KeyError:
+        config[appli_path] = []
 
     # remove port from list
-    ports_info = config["busy_ports"]
-    config["busy_ports"] = [x for x in ports_info if x != port]
+    ports_info = config[appli_path]
+    config[appli_path] = [x for x in ports_info if x != port]
 
-    # write config, for this application only (i.e. no 'other' ports)
-    logger.debug("write busy_ports: %s"%str(config["busy_ports"]))
+    # write config
+    logger.debug("write config: %s"%str(config))
     try:
-      with open(config_file, 'w') as f:
-        pickle.dump(config, f)
+      with open(config_file, 'wb') as f:
+        pickle.dump(config, f, protocol=0)
     except IOError:
       pass
 
@@ -227,28 +244,33 @@ def releasePort(port):
 def getBusyPorts():
   config_file, lock_file = _getConfigurationFilename()
   oldmask = os.umask(0)
-  with open(lock_file, 'w') as lock:
+  with open(lock_file, 'wb') as lock:
     # acquire lock
     __acquire_lock(lock)
 
     # read config
-    config = {'busy_ports':[]}
+    config = {}
     logger.debug("read configuration file")
     try:
-      with open(config_file, 'r') as f:
+      with open(config_file, 'rb') as f:
         config = pickle.load(f)
     except IOError: # empty file
       pass
 
-    logger.debug("load busy_ports: %s"%str(config["busy_ports"]))
+    logger.debug("load config: %s"%str(config))
+    appli_path = os.getenv("ABSOLUTE_APPLI_PATH", "unknown")
+    try:
+        config[appli_path]
+    except KeyError:
+        config[appli_path] = []
 
     # Scan all possible ports to determine which ones are owned by other applications
     ports_info = { 'this': [], 'other': [] }
-    busy_ports = config["busy_ports"]
+    my_busy_ports = config[appli_path]
     for port in range(__PORT_MIN_NUMBER, __PORT_MAX_NUMBER):
-      if __isPortUsed(port, busy_ports):
+      if __isPortUsed(port, config):
         logger.debug("Port %s seems to be busy"%str(port))
-        if port in busy_ports:
+        if port in my_busy_ports:
           ports_info["this"].append(port)
         else:
           ports_info["other"].append(port)