Salome HOME
display a message only on debug mode
[modules/kernel.git] / bin / PortManager.py
1 #!/usr/bin/env python3
2 #  -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2019  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     import traceback
124     traceback.print_exc()
125     return False
126
127   from io import StringIO
128   buf = StringIO(out.decode('utf-8', 'ignore'))
129   ports = buf.readlines()
130   # search for TCP - LISTEN connections
131   import re
132   regObj = re.compile( ".*tcp.*:([0-9]+).*:.*listen", re.IGNORECASE );
133   for item in ports:
134     try:
135       p = int(regObj.match(item).group(1))
136       if p == port: return True
137     except:
138       pass
139   return False
140 #
141
142 def getPort(preferredPort=None):
143   logger.debug("GET PORT")
144
145   config_file, lock_file = _getConfigurationFilename()
146   oldmask = os.umask(0)
147   with open(lock_file, 'wb') as lock:
148     # acquire lock
149     __acquire_lock(lock)
150
151     # read config
152     config = {}
153     logger.debug("read configuration file")
154     try:
155       with open(config_file, 'rb') as f:
156         config = pickle.load(f)
157     except:
158       logger.debug("Problem loading PortManager file: %s"%config_file)
159       # In this case config dictionary is reset
160
161     logger.debug("load config: %s"%str(config))
162     appli_path = os.getenv("ABSOLUTE_APPLI_PATH", "unknown")
163     try:
164         config[appli_path]
165     except KeyError:
166         config[appli_path] = []
167
168     # append port
169     port = preferredPort
170     if not port or __isPortUsed(port, config):
171       port = __PORT_MIN_NUMBER
172       while __isPortUsed(port, config):
173         if port == __PORT_MAX_NUMBER:
174           msg  = "\n"
175           msg += "Can't find a free port to launch omniNames\n"
176           msg += "Try to kill the running servers and then launch SALOME again.\n"
177           raise RuntimeError(msg)
178         logger.debug("Port %s seems to be busy"%str(port))
179         port = port + 1
180     logger.debug("found free port: %s"%str(port))
181     config[appli_path].append(port)
182
183     # write config
184     logger.debug("write config: %s"%str(config))
185     try:
186       with open(config_file, 'wb') as f:
187         pickle.dump(config, f, protocol=0)
188     except IOError:
189       pass
190
191     # release lock
192     __release_lock(lock)
193   #
194
195   os.umask(oldmask)
196   logger.debug("get port: %s"%str(port))
197   return port
198 #
199
200 def releasePort(port):
201   port = int(port)
202   logger.debug("RELEASE PORT (%s)"%port)
203
204   config_file, lock_file = _getConfigurationFilename()
205   oldmask = os.umask(0)
206   with open(lock_file, 'wb') as lock:
207     # acquire lock
208     __acquire_lock(lock)
209
210     # read config
211     config = {}
212     logger.debug("read configuration file")
213     try:
214       with open(config_file, 'rb') as f:
215         config = pickle.load(f)
216     except IOError: # empty file
217       pass
218
219     logger.debug("load config: %s"%str(config))
220     appli_path = os.getenv("ABSOLUTE_APPLI_PATH", "unknown")
221     try:
222         config[appli_path]
223     except KeyError:
224         config[appli_path] = []
225
226     # remove port from list
227     ports_info = config[appli_path]
228     config[appli_path] = [x for x in ports_info if x != port]
229
230     # write config
231     logger.debug("write config: %s"%str(config))
232     try:
233       with open(config_file, 'wb') as f:
234         pickle.dump(config, f, protocol=0)
235     except IOError:
236       pass
237
238     # release lock
239     __release_lock(lock)
240
241     logger.debug("released port port: %s"%str(port))
242
243   os.umask(oldmask)
244 #
245
246 def getBusyPorts():
247   config_file, lock_file = _getConfigurationFilename()
248   oldmask = os.umask(0)
249   with open(lock_file, 'wb') as lock:
250     # acquire lock
251     __acquire_lock(lock)
252
253     # read config
254     config = {}
255     logger.debug("read configuration file")
256     try:
257       with open(config_file, 'rb') as f:
258         config = pickle.load(f)
259     except IOError: # empty file
260       pass
261
262     logger.debug("load config: %s"%str(config))
263     appli_path = os.getenv("ABSOLUTE_APPLI_PATH", "unknown")
264     try:
265         config[appli_path]
266     except KeyError:
267         config[appli_path] = []
268
269     # Scan all possible ports to determine which ones are owned by other applications
270     ports_info = { 'this': [], 'other': [] }
271     my_busy_ports = config[appli_path]
272     for port in range(__PORT_MIN_NUMBER, __PORT_MAX_NUMBER):
273       if __isPortUsed(port, config):
274         logger.debug("Port %s seems to be busy"%str(port))
275         if port in my_busy_ports:
276           ports_info["this"].append(port)
277         else:
278           ports_info["other"].append(port)
279
280     logger.debug("all busy_ports: %s"%str(ports_info))
281
282     sorted_ports = { 'this': sorted(ports_info['this']),
283                      'other': sorted(ports_info['other']) }
284
285     # release lock
286     __release_lock(lock)
287
288   os.umask(oldmask)
289   return sorted_ports
290 #