Salome HOME
ff9eabfbef90cfe965d59091af22bf73840b5285
[modules/kernel.git] / bin / PortManager.py
1 #!/usr/bin/env python
2 #  -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2016  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 import logging
33 def createLogger():
34   logger = logging.getLogger(__name__)
35 #  logger.setLevel(logging.DEBUG)
36   logger.setLevel(logging.INFO)
37   ch = logging.StreamHandler()
38   ch.setLevel(logging.DEBUG)
39   formatter = logging.Formatter("%(levelname)s:%(threadName)s:%(message)s")
40   ch.setFormatter(formatter)
41   logger.addHandler(ch)
42   return logger
43 #
44 logger = createLogger()
45
46 #------------------------------------
47 # A file locker (Linux only)
48 def __acquire_lock(lock):
49   if sys.platform == "win32":
50     import msvcrt
51     # lock 1 byte: file is supposed to be zero-byte long
52     msvcrt.locking(lock.fileno(), msvcrt.LK_LOCK, 1)
53   else:
54     import fcntl
55     fcntl.flock(lock, fcntl.LOCK_EX)
56 #
57 def __release_lock(lock):
58   if sys.platform == "win32":
59     import msvcrt
60     msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)
61   else:
62     import fcntl
63     fcntl.flock(lock, fcntl.LOCK_UN)
64 #
65
66 def _getConfigurationFilename():
67   omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
68
69   from salome_utils import generateFileName
70   portmanager_config = generateFileName(omniorbUserPath,
71                                         prefix="omniORB",
72                                         suffix="PortManager",
73                                         extension="cfg",
74                                         hidden=True)
75   import tempfile
76   temp = tempfile.NamedTemporaryFile()
77   lock_file = os.path.join(os.path.dirname(temp.name), ".omniORB_PortManager.lock")
78   temp.close()
79
80   return (portmanager_config, lock_file)
81 #
82
83 def __isPortUsed(port, busy_ports):
84   return (port in busy_ports) or __isNetworkConnectionActiveOnPort(port)
85 #
86
87 def __isNetworkConnectionActiveOnPort(port):
88   # :NOTE: Under windows:
89   #        netstat options -l and -t are unavailable
90   #        grep command is unavailable
91   from subprocess import Popen, PIPE
92   if sys.platform == "win32":
93     out, _ = Popen(['netstat','-a','-n','-p tcp'], stdout=PIPE).communicate()
94   else:
95     out, _ = Popen(['netstat','-ant'], stdout=PIPE).communicate()
96   import StringIO
97   buf = StringIO.StringIO(out)
98   ports = buf.readlines()
99   # search for TCP - LISTEN connections
100   import re
101   regObj = re.compile( ".*tcp.*:([0-9]+).*:.*listen", re.IGNORECASE );
102   for item in ports:
103     try:
104       p = int(regObj.match(item).group(1))
105       if p == port: return True
106     except:
107       pass
108   return False
109 #
110
111 def getPort(preferedPort=None):
112   logger.debug("GET PORT")
113
114   config_file, lock_file = _getConfigurationFilename()
115   oldmask = os.umask(0)
116   with open(lock_file, 'w') as lock:
117     # acquire lock
118     __acquire_lock(lock)
119
120     # read config
121     config = {'busy_ports':[]}
122     logger.debug("read configuration file")
123     try:
124       with open(config_file, 'r') as f:
125         config = pickle.load(f)
126     except:
127       logger.info("Problem loading PortManager file: %s"%config_file)
128       # In this case config dictionary is reset
129
130     logger.debug("load busy_ports: %s"%str(config["busy_ports"]))
131
132     # append port
133     busy_ports = config["busy_ports"]
134     port = preferedPort
135     if not port or __isPortUsed(port, busy_ports):
136       port = 2810
137       while __isPortUsed(port, busy_ports):
138         if port == 2810+100:
139           msg  = "\n"
140           msg += "Can't find a free port to launch omniNames\n"
141           msg += "Try to kill the running servers and then launch SALOME again.\n"
142           raise RuntimeError, msg
143         logger.debug("Port %s seems to be busy"%str(port))
144         if not port in config["busy_ports"]:
145           config["busy_ports"].append(port)
146         port = port + 1
147     logger.debug("found free port: %s"%str(port))
148     config["busy_ports"].append(port)
149
150     # write config
151     logger.debug("write busy_ports: %s"%str(config["busy_ports"]))
152     try:
153       with open(config_file, 'w') as f:
154         pickle.dump(config, f)
155     except IOError:
156       pass
157
158     # release lock
159     __release_lock(lock)
160   #
161
162   os.umask(oldmask)
163   logger.debug("get port: %s"%str(port))
164   return port
165 #
166
167 def releasePort(port):
168   port = int(port)
169   logger.debug("RELEASE PORT (%s)"%port)
170
171   config_file, lock_file = _getConfigurationFilename()
172   oldmask = os.umask(0)
173   with open(lock_file, 'w') as lock:
174     # acquire lock
175     __acquire_lock(lock)
176
177     # read config
178     config = {'busy_ports':[]}
179     logger.debug("read configuration file")
180     try:
181       with open(config_file, 'r') as f:
182         config = pickle.load(f)
183     except IOError: # empty file
184       pass
185
186     logger.debug("load busy_ports: %s"%str(config["busy_ports"]))
187
188     # remove port from list
189     busy_ports = config["busy_ports"]
190
191     if port in busy_ports:
192       busy_ports.remove(port)
193       config["busy_ports"] = busy_ports
194
195     # write config
196     logger.debug("write busy_ports: %s"%str(config["busy_ports"]))
197     try:
198       with open(config_file, 'w') as f:
199         pickle.dump(config, f)
200     except IOError:
201       pass
202
203     # release lock
204     __release_lock(lock)
205
206     logger.debug("released port port: %s"%str(port))
207   
208   os.umask(oldmask)
209 #
210
211 def getBusyPorts():
212   busy_ports = []
213   config_file, lock_file = _getConfigurationFilename()
214   oldmask = os.umask(0)
215   with open(lock_file, 'w') as lock:
216     # acquire lock
217     __acquire_lock(lock)
218
219     # read config
220     config = {'busy_ports':[]}
221     logger.debug("read configuration file")
222     try:
223       with open(config_file, 'r') as f:
224         config = pickle.load(f)
225     except IOError: # empty file
226       pass
227
228     logger.debug("load busy_ports: %s"%str(config["busy_ports"]))
229
230     busy_ports = config["busy_ports"]
231     # release lock
232     __release_lock(lock)
233
234   os.umask(oldmask)
235   return busy_ports
236 #