Salome HOME
fix port number reservation
[modules/kernel.git] / bin / PortManager.py
1 #!/usr/bin/env python
2 #  -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2017  CEA/DEN, EDF R&D, OPEN CASCADE
4 #
5 # Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
6 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
7 #
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.
12 #
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.
17 #
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
21 #
22 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 #
24 import os
25 import sys
26
27 try:
28   import cPickle as pickle #@UnusedImport
29 except:
30   import pickle #@Reimport
31
32 __PORT_MIN_NUMBER = 2810
33 __PORT_MAX_NUMBER = 2910
34
35 import logging
36 def createLogger():
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:%(message)s")
43   ch.setFormatter(formatter)
44   logger.addHandler(ch)
45   return logger
46 #
47 logger = createLogger()
48
49 #------------------------------------
50 # A file locker
51 def __acquire_lock(lock):
52   logger.debug("ACQUIRE LOCK")
53   if sys.platform == "win32":
54     import msvcrt
55     # lock 1 byte: file is supposed to be zero-byte long
56     msvcrt.locking(lock.fileno(), msvcrt.LK_LOCK, 1)
57   else:
58     import fcntl
59     fcntl.flock(lock, fcntl.LOCK_EX)
60   logger.debug("LOCK ACQUIRED")
61 #
62 def __release_lock(lock):
63   logger.debug("RELEASE LOCK")
64   if sys.platform == "win32":
65     import msvcrt
66     msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)
67   else:
68     import fcntl
69     fcntl.flock(lock, fcntl.LOCK_UN)
70   logger.debug("LOCK RELEASED")
71 #
72 #------------------------------------
73
74 def _getConfigurationFilename():
75   omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
76
77   from salome_utils import generateFileName
78   portmanager_config = generateFileName(omniorbUserPath,
79                                         prefix="salome",
80                                         suffix="PortManager",
81                                         extension="cfg",
82                                         hidden=True)
83   import tempfile
84   temp = tempfile.NamedTemporaryFile()
85   lock_file = os.path.join(os.path.dirname(temp.name), ".salome_PortManager.lock")
86   temp.close()
87
88   return (portmanager_config, lock_file)
89 #
90
91 def __isPortUsed(port, config):
92   busy_ports = []
93   for ports in config.values():
94     busy_ports += ports
95   return (port in busy_ports) or __isNetworkConnectionActiveOnPort(port)
96 #
97
98 def __isNetworkConnectionActiveOnPort(port):
99   # :NOTE: Under windows:
100   #        netstat options -l and -t are unavailable
101   #        grep command is unavailable
102   if sys.platform == "win32":
103     cmd = ['netstat','-a','-n','-p tcp']
104   else:
105     cmd = ['netstat','-ant']
106     pass
107
108   err = None
109   try:
110     from subprocess import Popen, PIPE, STDOUT
111     p = Popen(cmd, stdout=PIPE, stderr=STDOUT)
112     out, err = p.communicate()
113   except:
114     print "Error when trying to access active network connections."
115     if err: print err
116     import traceback
117     traceback.print_exc()
118     return False
119
120   import StringIO
121   buf = StringIO.StringIO(out)
122   ports = buf.readlines()
123   # search for TCP - LISTEN connections
124   import re
125   regObj = re.compile( ".*tcp.*:([0-9]+).*:.*listen", re.IGNORECASE );
126   for item in ports:
127     try:
128       p = int(regObj.match(item).group(1))
129       if p == port: return True
130     except:
131       pass
132   return False
133 #
134
135 def getPort(preferedPort=None):
136   logger.debug("GET PORT")
137
138   config_file, lock_file = _getConfigurationFilename()
139   oldmask = os.umask(0)
140   with open(lock_file, 'w') as lock:
141     # acquire lock
142     __acquire_lock(lock)
143
144     # read config
145     config = {}
146     logger.debug("read configuration file")
147     try:
148       with open(config_file, 'r') as f:
149         config = pickle.load(f)
150     except:
151       logger.info("Problem loading PortManager file: %s"%config_file)
152       # In this case config dictionary is reset
153
154     logger.debug("load config: %s"%str(config))
155     appli_path = os.getenv("ABSOLUTE_APPLI_PATH", "unknown")
156     try:
157         config[appli_path]
158     except KeyError:
159         config[appli_path] = []
160
161     # append port
162     port = preferedPort
163     if not port or __isPortUsed(port, config):
164       port = __PORT_MIN_NUMBER
165       while __isPortUsed(port, config):
166         if port == __PORT_MAX_NUMBER:
167           msg  = "\n"
168           msg += "Can't find a free port to launch omniNames\n"
169           msg += "Try to kill the running servers and then launch SALOME again.\n"
170           raise RuntimeError, msg
171         logger.debug("Port %s seems to be busy"%str(port))
172         port = port + 1
173     logger.debug("found free port: %s"%str(port))
174     config[appli_path].append(port)
175
176     # write config
177     logger.debug("write config: %s"%str(config))
178     try:
179       with open(config_file, 'w') as f:
180         pickle.dump(config, f)
181     except IOError:
182       pass
183
184     # release lock
185     __release_lock(lock)
186   #
187
188   os.umask(oldmask)
189   logger.debug("get port: %s"%str(port))
190   return port
191 #
192
193 def releasePort(port):
194   port = int(port)
195   logger.debug("RELEASE PORT (%s)"%port)
196
197   config_file, lock_file = _getConfigurationFilename()
198   oldmask = os.umask(0)
199   with open(lock_file, 'w') as lock:
200     # acquire lock
201     __acquire_lock(lock)
202
203     # read config
204     config = {}
205     logger.debug("read configuration file")
206     try:
207       with open(config_file, 'r') as f:
208         config = pickle.load(f)
209     except IOError: # empty file
210       pass
211
212     logger.debug("load config: %s"%str(config))
213     appli_path = os.getenv("ABSOLUTE_APPLI_PATH", "unknown")
214     try:
215         config[appli_path]
216     except KeyError:
217         config[appli_path] = []
218
219     # remove port from list
220     ports_info = config[appli_path]
221     config[appli_path] = [x for x in ports_info if x != port]
222
223     # write config
224     logger.debug("write config: %s"%str(config))
225     try:
226       with open(config_file, 'w') as f:
227         pickle.dump(config, f)
228     except IOError:
229       pass
230
231     # release lock
232     __release_lock(lock)
233
234     logger.debug("released port port: %s"%str(port))
235
236   os.umask(oldmask)
237 #
238
239 def getBusyPorts():
240   config_file, lock_file = _getConfigurationFilename()
241   oldmask = os.umask(0)
242   with open(lock_file, 'w') as lock:
243     # acquire lock
244     __acquire_lock(lock)
245
246     # read config
247     config = {}
248     logger.debug("read configuration file")
249     try:
250       with open(config_file, 'r') as f:
251         config = pickle.load(f)
252     except IOError: # empty file
253       pass
254
255     logger.debug("load config: %s"%str(config))
256     appli_path = os.getenv("ABSOLUTE_APPLI_PATH", "unknown")
257     try:
258         config[appli_path]
259     except KeyError:
260         config[appli_path] = []
261
262     # Scan all possible ports to determine which ones are owned by other applications
263     ports_info = { 'this': [], 'other': [] }
264     my_busy_ports = config[appli_path]
265     for port in range(__PORT_MIN_NUMBER, __PORT_MAX_NUMBER):
266       if __isPortUsed(port, config):
267         logger.debug("Port %s seems to be busy"%str(port))
268         if port in my_busy_ports:
269           ports_info["this"].append(port)
270         else:
271           ports_info["other"].append(port)
272
273     logger.debug("all busy_ports: %s"%str(ports_info))
274
275     sorted_ports = { 'this': sorted(ports_info['this']),
276                      'other': sorted(ports_info['other']) }
277
278     # release lock
279     __release_lock(lock)
280
281   os.umask(oldmask)
282   return sorted_ports
283 #