Salome HOME
updated copyright message
[modules/kernel.git] / bin / PortManager.py
index d0ba1b91347da84318f0e88c56d1a7b525fe9954..fcac751a37d6d182edb9a36eccb4a8f7e8783ccc 100644 (file)
@@ -1,6 +1,6 @@
 #!/usr/bin/env python3
 #  -*- coding: iso-8859-1 -*-
-# Copyright (C) 2007-2017  CEA/DEN, EDF R&D, OPEN CASCADE
+# Copyright (C) 2007-2023  CEA, EDF, OPEN CASCADE
 #
 # Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
 #
 import os
 import sys
+import psutil
 
-try:
-  import cPickle as pickle #@UnusedImport
-except:
-  import pickle #@Reimport
+from socket import AF_INET, SOCK_STREAM
+
+import pickle
 
 __PORT_MIN_NUMBER = 2810
 __PORT_MAX_NUMBER = 2910
@@ -82,7 +82,14 @@ def _getConfigurationFilename():
                                         hidden=True)
   import tempfile
   temp = tempfile.NamedTemporaryFile()
-  lock_file = os.path.join(os.path.dirname(temp.name), ".salome_PortManager.lock")
+  lock_file = os.path.join(os.path.dirname(temp.name), ".salome", ".PortManager.lock")
+  try:
+    oldmask = os.umask(0)
+    os.makedirs(os.path.dirname(lock_file))
+  except IOError:
+    pass
+  finally:
+    os.umask(oldmask)
   temp.close()
 
   return (portmanager_config, lock_file)
@@ -96,41 +103,10 @@ def __isPortUsed(port, config):
 #
 
 def __isNetworkConnectionActiveOnPort(port):
-  # :NOTE: Under windows:
-  #        netstat options -l and -t are unavailable
-  #        grep command is unavailable
-  if sys.platform == "win32":
-    cmd = ['netstat','-a','-n','-p','tcp']
-  else:
-    cmd = ['netstat','-ant']
-    pass
-
-  err = None
-  try:
-    from subprocess import Popen, PIPE, STDOUT
-    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)
-    import traceback
-    traceback.print_exc()
-    return False
-
-  from io import StringIO
-  buf = StringIO(out.decode('utf-8', 'ignore'))
-  ports = buf.readlines()
-  # search for TCP - LISTEN connections
-  import re
-  regObj = re.compile( ".*tcp.*:([0-9]+).*:.*listen", re.IGNORECASE );
-  for item in ports:
-    try:
-      p = int(regObj.match(item).group(1))
-      if p == port: return True
-    except:
-      pass
-  return False
-#
+  # psutil realization
+  return port in [c.laddr.port for c in psutil.net_connections(kind='inet') if \
+      (c.family, c.type, c.status) == (AF_INET, SOCK_STREAM, "LISTEN")]
+  #
 
 def getPort(preferredPort=None):
   logger.debug("GET PORT")
@@ -147,8 +123,8 @@ def getPort(preferredPort=None):
     try:
       with open(config_file, 'rb') as f:
         config = pickle.load(f)
-    except:
-      logger.info("Problem loading PortManager file: %s"%config_file)
+    except Exception:
+      logger.debug("Problem loading PortManager file: %s"%config_file)
       # In this case config dictionary is reset
 
     logger.debug("load config: %s"%str(config))