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 from Singleton import Singleton
26 import multiprocessing
36 import cPickle as pickle
45 logger = logging.getLogger(__name__)
46 # logger.setLevel(logging.DEBUG)
47 ch = logging.StreamHandler()
48 ch.setLevel(logging.DEBUG)
49 formatter = logging.Formatter("%(levelname)s:%(threadName)s:%(message)s")
50 ch.setFormatter(formatter)
54 logger = createLogger()
57 if sys.platform == 'win32':
58 import multiprocessing.reduction # make sockets pickable/inheritable
60 multiprocessing.freeze_support() # Add support for when a program which uses multiprocessing has been frozen to produce a Windows executable.
62 #------------------------------------
63 # A file locker (Linux only)
65 class PortManagerLock:
66 def __init__(self, filename, readonly=False, blocking=True):
67 # This will create it if it does not exist already
68 logger.debug("Create lock on %s"%filename)
69 self.__readonly = readonly
70 self.__blocking = blocking
71 self.__filename = filename
75 self.handle = open(self.__filename, 'a+')
79 if not self.__blocking: # Raise an IOError exception if file has already been locked
80 mode = mode | fcntl.LOCK_NB
81 fcntl.flock(self.handle, mode)
82 logger.debug("lock acquired %s"%self.__blocking)
85 fcntl.flock(self.handle, fcntl.LOCK_UN)
86 logger.debug("lock released")
89 logger.debug("Close lock file")
91 os.remove(self.__filename)
94 def _getConfigurationFilename():
95 omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
97 from salome_utils import generateFileName
98 portmanager_config = generateFileName(omniorbUserPath,
100 suffix="PortManager",
103 lock_file = portmanager_config + "-lock"
104 return (portmanager_config, lock_file)
107 def __isPortUsed(port, busy_ports):
108 return (port in busy_ports) or __isNetworkConnectionActiveOnPort(port)
111 def __isNetworkConnectionActiveOnPort(port):
112 # :NOTE: Under windows:
113 # netstat options -l and -t are unavailable
114 # grep command is unavailable
115 from subprocess import Popen, PIPE
116 (stdout, stderr) = Popen(['netstat','-an'], stdout=PIPE).communicate()
118 buf = StringIO.StringIO(stdout)
119 ports = buf.readlines()
120 # search for TCP - LISTEN connections
122 regObj = re.compile( ".*tcp.*:([0-9]+).*:.*listen", re.IGNORECASE );
125 p = int(regObj.match(item).group(1))
126 if p == port: return True
131 def getPort(preferedPort=None):
132 logger.debug("GET PORT")
134 config_file, lock_file = _getConfigurationFilename()
135 with open(lock_file, 'w') as lock:
137 fcntl.flock(lock, fcntl.LOCK_EX)
140 config = {'busy_ports':[]}
141 logger.debug("read configuration file")
143 with open(config_file, 'r') as f:
144 config = pickle.load(f)
145 except IOError: # empty file
148 logger.debug("load busy_ports: %s"%str(config["busy_ports"]))
151 busy_ports = config["busy_ports"]
153 if not port or __isPortUsed(port, busy_ports):
155 while __isPortUsed(port, busy_ports):
158 msg += "Can't find a free port to launch omniNames\n"
159 msg += "Try to kill the running servers and then launch SALOME again.\n"
160 raise RuntimeError, msg
162 logger.debug("found free port: %s"%str(port))
163 config["busy_ports"].append(port)
166 logger.debug("write busy_ports: %s"%str(config["busy_ports"]))
168 with open(config_file, 'w') as f:
169 pickle.dump(config, f)
174 fcntl.flock(lock, fcntl.LOCK_UN)
176 logger.debug("get port: %s"%str(port))
180 def releasePort(port):
182 logger.debug("RELEASE PORT (%s)"%port)
184 config_file, lock_file = _getConfigurationFilename()
185 with open(lock_file, 'w') as lock:
187 fcntl.flock(lock, fcntl.LOCK_EX)
190 config = {'busy_ports':[]}
191 logger.debug("read configuration file")
193 with open(config_file, 'r') as f:
194 config = pickle.load(f)
195 except IOError: # empty file
198 logger.debug("load busy_ports: %s"%str(config["busy_ports"]))
200 # remove port from list
201 busy_ports = config["busy_ports"]
203 if port in busy_ports:
204 busy_ports.remove(port)
205 config["busy_ports"] = busy_ports
208 logger.debug("write busy_ports: %s"%str(config["busy_ports"]))
210 with open(config_file, 'w') as f:
211 pickle.dump(config, f)
216 fcntl.flock(lock, fcntl.LOCK_UN)
218 logger.debug("released port port: %s"%str(port))
222 config_file, lock_file = _getConfigurationFilename()
223 with open(lock_file, 'w') as lock:
225 fcntl.flock(lock, fcntl.LOCK_EX)
228 config = {'busy_ports':[]}
229 logger.debug("read configuration file")
231 with open(config_file, 'r') as f:
232 config = pickle.load(f)
233 except IOError: # empty file
236 logger.debug("load busy_ports: %s"%str(config["busy_ports"]))
238 busy_ports = config["busy_ports"]
240 fcntl.flock(lock, fcntl.LOCK_UN)