]> SALOME platform Git repositories - modules/kernel.git/blob - bin/PortManager.py
Salome HOME
aace9e17bcd9e8aac5353abb572d4aa35bd750a4
[modules/kernel.git] / bin / PortManager.py
1 #!/usr/bin/env python3
2 #  -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2020  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:%(pathname)s[%(lineno)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   try:
87     oldmask = os.umask(0)
88     os.makedirs(os.path.dirname(lock_file))
89   except IOError:
90     pass
91   finally:
92     os.umask(oldmask)
93   temp.close()
94
95   return (portmanager_config, lock_file)
96 #
97
98 def __isPortUsed(port, config):
99   busy_ports = []
100   for ports in config.values():
101     busy_ports += ports
102   return (port in busy_ports) or __isNetworkConnectionActiveOnPort(port)
103 #
104
105 def __isNetworkConnectionActiveOnPort(port):
106   # :NOTE: Under windows:
107   #        netstat options -l and -t are unavailable
108   #        grep command is unavailable
109   if sys.platform == "win32":
110     cmd = ['netstat','-a','-n','-p','tcp']
111   else:
112     cmd = ['netstat','-ant']
113     pass
114
115   err = None
116   try:
117     from subprocess import Popen, PIPE, STDOUT
118     p = Popen(cmd, stdout=PIPE, stderr=STDOUT)
119     out, err = p.communicate()
120   except:
121     print("Error when trying to access active network connections.")
122     if err: print(err)
123     print("... Presumably this package is not installed...Please install netstat if available for your distribution.")
124     print("... Trying socket based approach")
125     try:
126       import socket
127       sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
128       result = sock.connect_ex(("127.0.0.1", port))
129       if result == 0:
130         print("Port %r:      Closed" % (port))
131         sock.close()
132         return True
133       else:
134         sock.close()
135         return False
136     except:
137       import traceback
138       traceback.print_exc()
139       return False
140
141   from io import StringIO
142   buf = StringIO(out.decode('utf-8', 'ignore'))
143   ports = buf.readlines()
144   # search for TCP - LISTEN connections
145   import re
146   regObj = re.compile( ".*tcp.*:([0-9]+).*:.*listen", re.IGNORECASE );
147   for item in ports:
148     try:
149       p = int(regObj.match(item).group(1))
150       if p == port: return True
151     except:
152       pass
153   return False
154 #
155
156 def getPort(preferredPort=None):
157   logger.debug("GET PORT")
158
159   config_file, lock_file = _getConfigurationFilename()
160   oldmask = os.umask(0)
161   with open(lock_file, 'wb') as lock:
162     # acquire lock
163     __acquire_lock(lock)
164
165     # read config
166     config = {}
167     logger.debug("read configuration file")
168     try:
169       with open(config_file, 'rb') as f:
170         config = pickle.load(f)
171     except:
172       logger.debug("Problem loading PortManager file: %s"%config_file)
173       # In this case config dictionary is reset
174
175     logger.debug("load config: %s"%str(config))
176     appli_path = os.getenv("ABSOLUTE_APPLI_PATH", "unknown")
177     try:
178         config[appli_path]
179     except KeyError:
180         config[appli_path] = []
181
182     # append port
183     port = preferredPort
184     if not port or __isPortUsed(port, config):
185       port = __PORT_MIN_NUMBER
186       while __isPortUsed(port, config):
187         if port == __PORT_MAX_NUMBER:
188           msg  = "\n"
189           msg += "Can't find a free port to launch omniNames\n"
190           msg += "Try to kill the running servers and then launch SALOME again.\n"
191           raise RuntimeError(msg)
192         logger.debug("Port %s seems to be busy"%str(port))
193         port = port + 1
194     logger.debug("found free port: %s"%str(port))
195     config[appli_path].append(port)
196
197     # write config
198     logger.debug("write config: %s"%str(config))
199     try:
200       with open(config_file, 'wb') as f:
201         pickle.dump(config, f, protocol=0)
202     except IOError:
203       pass
204
205     # release lock
206     __release_lock(lock)
207   #
208
209   os.umask(oldmask)
210   logger.debug("get port: %s"%str(port))
211   return port
212 #
213
214 def releasePort(port):
215   port = int(port)
216   logger.debug("RELEASE PORT (%s)"%port)
217
218   config_file, lock_file = _getConfigurationFilename()
219   oldmask = os.umask(0)
220   with open(lock_file, 'wb') as lock:
221     # acquire lock
222     __acquire_lock(lock)
223
224     # read config
225     config = {}
226     logger.debug("read configuration file")
227     try:
228       with open(config_file, 'rb') as f:
229         config = pickle.load(f)
230     except IOError: # empty file
231       pass
232
233     logger.debug("load config: %s"%str(config))
234     appli_path = os.getenv("ABSOLUTE_APPLI_PATH", "unknown")
235     try:
236         config[appli_path]
237     except KeyError:
238         config[appli_path] = []
239
240     # remove port from list
241     ports_info = config[appli_path]
242     config[appli_path] = [x for x in ports_info if x != port]
243
244     # write config
245     logger.debug("write config: %s"%str(config))
246     try:
247       with open(config_file, 'wb') as f:
248         pickle.dump(config, f, protocol=0)
249     except IOError:
250       pass
251
252     # release lock
253     __release_lock(lock)
254
255     logger.debug("released port port: %s"%str(port))
256
257   os.umask(oldmask)
258 #
259
260 def getBusyPorts():
261   config_file, lock_file = _getConfigurationFilename()
262   oldmask = os.umask(0)
263   with open(lock_file, 'wb') as lock:
264     # acquire lock
265     __acquire_lock(lock)
266
267     # read config
268     config = {}
269     logger.debug("read configuration file")
270     try:
271       with open(config_file, 'rb') as f:
272         config = pickle.load(f)
273     except IOError: # empty file
274       pass
275
276     logger.debug("load config: %s"%str(config))
277     appli_path = os.getenv("ABSOLUTE_APPLI_PATH", "unknown")
278     try:
279         config[appli_path]
280     except KeyError:
281         config[appli_path] = []
282
283     # Scan all possible ports to determine which ones are owned by other applications
284     ports_info = { 'this': [], 'other': [] }
285     my_busy_ports = config[appli_path]
286     for port in range(__PORT_MIN_NUMBER, __PORT_MAX_NUMBER):
287       if __isPortUsed(port, config):
288         logger.debug("Port %s seems to be busy"%str(port))
289         if port in my_busy_ports:
290           ports_info["this"].append(port)
291         else:
292           ports_info["other"].append(port)
293
294     logger.debug("all busy_ports: %s"%str(ports_info))
295
296     sorted_ports = { 'this': sorted(ports_info['this']),
297                      'other': sorted(ports_info['other']) }
298
299     # release lock
300     __release_lock(lock)
301
302   os.umask(oldmask)
303   return sorted_ports
304 #