2 # -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2014 CEA/DEN, EDF R&D, 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.
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
24 import multiprocessing
34 import cPickle as pickle
43 logger = logging.getLogger(__name__)
44 # logger.setLevel(logging.DEBUG)
45 ch = logging.StreamHandler()
46 ch.setLevel(logging.DEBUG)
47 formatter = logging.Formatter("%(levelname)s:%(threadName)s:%(message)s")
48 ch.setFormatter(formatter)
52 logger = createLogger()
55 if sys.platform == 'win32':
56 import multiprocessing.reduction # make sockets pickable/inheritable
58 multiprocessing.freeze_support() # Add support for when a program which uses multiprocessing has been frozen to produce a Windows executable.
60 #------------------------------------
61 # A file locker (Linux only)
63 class PortManagerLock:
64 def __init__(self, filename, readonly=False, blocking=True):
65 # This will create it if it does not exist already
66 logger.debug("Create lock on %s"%filename)
67 self.__readonly = readonly
68 self.__blocking = blocking
69 self.__filename = filename
73 self.handle = open(self.__filename, 'a+')
77 if not self.__blocking: # Raise an IOError exception if file has already been locked
78 mode = mode | fcntl.LOCK_NB
79 fcntl.flock(self.handle, mode)
80 logger.debug("lock acquired %s"%self.__blocking)
83 fcntl.flock(self.handle, fcntl.LOCK_UN)
84 logger.debug("lock released")
87 logger.debug("Close lock file")
89 os.remove(self.__filename)
92 def _getConfigurationFilename():
93 omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
95 from salome_utils import generateFileName
96 portmanager_config = generateFileName(omniorbUserPath,
101 lock_file = portmanager_config + "-lock"
102 return (portmanager_config, lock_file)
105 def __isPortUsed(port, busy_ports):
106 return (port in busy_ports) or __isNetworkConnectionActiveOnPort(port)
109 def __isNetworkConnectionActiveOnPort(port):
110 # :NOTE: Under windows:
111 # netstat options -l and -t are unavailable
112 # grep command is unavailable
113 from subprocess import Popen, PIPE
114 (stdout, stderr) = Popen(['netstat','-an'], stdout=PIPE).communicate()
116 buf = StringIO.StringIO(stdout)
117 ports = buf.readlines()
118 # search for TCP - LISTEN connections
120 regObj = re.compile( ".*tcp.*:([0-9]+).*:.*listen", re.IGNORECASE );
123 p = int(regObj.match(item).group(1))
124 if p == port: return True
129 def getPort(preferedPort=None):
130 logger.debug("GET PORT")
132 config_file, lock_file = _getConfigurationFilename()
133 with open(lock_file, 'w') as lock:
135 fcntl.flock(lock, fcntl.LOCK_EX)
138 config = {'busy_ports':[]}
139 logger.debug("read configuration file")
141 with open(config_file, 'r') as f:
142 config = pickle.load(f)
143 except IOError: # empty file
146 logger.debug("load busy_ports: %s"%str(config["busy_ports"]))
149 busy_ports = config["busy_ports"]
151 if not port or __isPortUsed(port, busy_ports):
153 while __isPortUsed(port, busy_ports):
156 msg += "Can't find a free port to launch omniNames\n"
157 msg += "Try to kill the running servers and then launch SALOME again.\n"
158 raise RuntimeError, msg
160 logger.debug("found free port: %s"%str(port))
161 config["busy_ports"].append(port)
164 logger.debug("write busy_ports: %s"%str(config["busy_ports"]))
166 with open(config_file, 'w') as f:
167 pickle.dump(config, f)
172 fcntl.flock(lock, fcntl.LOCK_UN)
174 logger.debug("get port: %s"%str(port))
178 def releasePort(port):
180 logger.debug("RELEASE PORT (%s)"%port)
182 config_file, lock_file = _getConfigurationFilename()
183 with open(lock_file, 'w') as lock:
185 fcntl.flock(lock, fcntl.LOCK_EX)
188 config = {'busy_ports':[]}
189 logger.debug("read configuration file")
191 with open(config_file, 'r') as f:
192 config = pickle.load(f)
193 except IOError: # empty file
196 logger.debug("load busy_ports: %s"%str(config["busy_ports"]))
198 # remove port from list
199 busy_ports = config["busy_ports"]
201 if port in busy_ports:
202 busy_ports.remove(port)
203 config["busy_ports"] = busy_ports
206 logger.debug("write busy_ports: %s"%str(config["busy_ports"]))
208 with open(config_file, 'w') as f:
209 pickle.dump(config, f)
214 fcntl.flock(lock, fcntl.LOCK_UN)
216 logger.debug("released port port: %s"%str(port))
220 config_file, lock_file = _getConfigurationFilename()
221 with open(lock_file, 'w') as lock:
223 fcntl.flock(lock, fcntl.LOCK_EX)
226 config = {'busy_ports':[]}
227 logger.debug("read configuration file")
229 with open(config_file, 'r') as f:
230 config = pickle.load(f)
231 except IOError: # empty file
234 logger.debug("load busy_ports: %s"%str(config["busy_ports"]))
236 busy_ports = config["busy_ports"]
238 fcntl.flock(lock, fcntl.LOCK_UN)