2 # -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2023 CEA, EDF, OPEN CASCADE
5 # Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
6 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
8 # This library is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU Lesser General Public
10 # License as published by the Free Software Foundation; either
11 # version 2.1 of the License, or (at your option) any later version.
13 # This library is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 # Lesser General Public License for more details.
18 # You should have received a copy of the GNU Lesser General Public
19 # License along with this library; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
28 from socket import AF_INET, SOCK_STREAM
32 __PORT_MIN_NUMBER = 2810
33 __PORT_MAX_NUMBER = 2910
37 logger = logging.getLogger(__name__)
38 #logger.setLevel(logging.DEBUG)
39 logger.setLevel(logging.INFO)
40 ch = logging.StreamHandler()
41 ch.setLevel(logging.DEBUG)
42 formatter = logging.Formatter("%(levelname)s:%(threadName)s:%(pathname)s[%(lineno)s]%(message)s")
43 ch.setFormatter(formatter)
47 logger = createLogger()
49 #------------------------------------
51 def __acquire_lock(lock):
52 logger.debug("ACQUIRE LOCK")
53 if sys.platform == "win32":
55 # lock 1 byte: file is supposed to be zero-byte long
56 msvcrt.locking(lock.fileno(), msvcrt.LK_LOCK, 1)
59 fcntl.flock(lock, fcntl.LOCK_EX)
60 logger.debug("LOCK ACQUIRED")
62 def __release_lock(lock):
63 logger.debug("RELEASE LOCK")
64 if sys.platform == "win32":
66 msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)
69 fcntl.flock(lock, fcntl.LOCK_UN)
70 logger.debug("LOCK RELEASED")
72 #------------------------------------
74 def _getConfigurationFilename():
75 omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
77 from salome_utils import generateFileName
78 portmanager_config = generateFileName(omniorbUserPath,
84 temp = tempfile.NamedTemporaryFile()
85 lock_file = os.path.join(os.path.dirname(temp.name), ".salome", ".PortManager.lock")
88 os.makedirs(os.path.dirname(lock_file))
95 return (portmanager_config, lock_file)
98 def __isPortUsed(port, config):
100 for ports in config.values():
102 return (port in busy_ports) or __isNetworkConnectionActiveOnPort(port)
105 def __isNetworkConnectionActiveOnPort(port):
107 return port in [c.laddr.port for c in psutil.net_connections(kind='inet') if \
108 (c.family, c.type, c.status) == (AF_INET, SOCK_STREAM, "LISTEN")]
111 def getPort(preferredPort=None):
112 logger.debug("GET PORT")
114 config_file, lock_file = _getConfigurationFilename()
115 oldmask = os.umask(0)
116 with open(lock_file, 'wb') as lock:
122 logger.debug("read configuration file")
124 with open(config_file, 'rb') as f:
125 config = pickle.load(f)
127 logger.debug("Problem loading PortManager file: %s"%config_file)
128 # In this case config dictionary is reset
130 logger.debug("load config: %s"%str(config))
131 appli_path = os.getenv("ABSOLUTE_APPLI_PATH", "unknown")
135 config[appli_path] = []
139 if not port or __isPortUsed(port, config):
140 port = __PORT_MIN_NUMBER
141 while __isPortUsed(port, config):
142 if port == __PORT_MAX_NUMBER:
144 msg += "Can't find a free port to launch omniNames\n"
145 msg += "Try to kill the running servers and then launch SALOME again.\n"
146 raise RuntimeError(msg)
147 logger.debug("Port %s seems to be busy"%str(port))
149 logger.debug("found free port: %s"%str(port))
150 config[appli_path].append(port)
153 logger.debug("write config: %s"%str(config))
155 with open(config_file, 'wb') as f:
156 pickle.dump(config, f, protocol=0)
165 logger.debug("get port: %s"%str(port))
169 def releasePort(port):
171 logger.debug("RELEASE PORT (%s)"%port)
173 config_file, lock_file = _getConfigurationFilename()
174 oldmask = os.umask(0)
175 with open(lock_file, 'wb') as lock:
181 logger.debug("read configuration file")
183 with open(config_file, 'rb') as f:
184 config = pickle.load(f)
185 except IOError: # empty file
188 logger.debug("load config: %s"%str(config))
189 appli_path = os.getenv("ABSOLUTE_APPLI_PATH", "unknown")
193 config[appli_path] = []
195 # remove port from list
196 ports_info = config[appli_path]
197 config[appli_path] = [x for x in ports_info if x != port]
200 logger.debug("write config: %s"%str(config))
202 with open(config_file, 'wb') as f:
203 pickle.dump(config, f, protocol=0)
210 logger.debug("released port port: %s"%str(port))
216 config_file, lock_file = _getConfigurationFilename()
217 oldmask = os.umask(0)
218 with open(lock_file, 'wb') as lock:
224 logger.debug("read configuration file")
226 with open(config_file, 'rb') as f:
227 config = pickle.load(f)
228 except IOError: # empty file
231 logger.debug("load config: %s"%str(config))
232 appli_path = os.getenv("ABSOLUTE_APPLI_PATH", "unknown")
236 config[appli_path] = []
238 # Scan all possible ports to determine which ones are owned by other applications
239 ports_info = { 'this': [], 'other': [] }
240 my_busy_ports = config[appli_path]
241 for port in range(__PORT_MIN_NUMBER, __PORT_MAX_NUMBER):
242 if __isPortUsed(port, config):
243 logger.debug("Port %s seems to be busy"%str(port))
244 if port in my_busy_ports:
245 ports_info["this"].append(port)
247 ports_info["other"].append(port)
249 logger.debug("all busy_ports: %s"%str(ports_info))
251 sorted_ports = { 'this': sorted(ports_info['this']),
252 'other': sorted(ports_info['other']) }