]> SALOME platform Git repositories - modules/kernel.git/blob - bin/PortManager.py
Salome HOME
Merge branch 'V8_0_0_BR'
[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
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
67 def _getConfigurationFilename():
68   omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
69
70   from salome_utils import generateFileName
71   portmanager_config = generateFileName(omniorbUserPath,
72                                         prefix="omniORB",
73                                         suffix="PortManager",
74                                         extension="cfg",
75                                         hidden=True)
76   import tempfile
77   temp = tempfile.NamedTemporaryFile()
78   lock_file = os.path.join(os.path.dirname(temp.name), ".omniORB_PortManager.lock")
79   temp.close()
80
81   return (portmanager_config, lock_file)
82 #
83
84 def __isPortUsed(port, busy_ports):
85   return (port in busy_ports) or __isNetworkConnectionActiveOnPort(port)
86 #
87
88 def __isNetworkConnectionActiveOnPort(port):
89   # :NOTE: Under windows:
90   #        netstat options -l and -t are unavailable
91   #        grep command is unavailable
92   from subprocess import Popen, PIPE
93   stdout, _ = Popen(['netstat','-an'], stdout=PIPE).communicate()
94   import StringIO
95   buf = StringIO.StringIO(stdout)
96   ports = buf.readlines()
97   # search for TCP - LISTEN connections
98   import re
99   regObj = re.compile( ".*tcp.*:([0-9]+).*:.*listen", re.IGNORECASE );
100   for item in ports:
101     try:
102       p = int(regObj.match(item).group(1))
103       if p == port: return True
104     except:
105       pass
106 #
107
108 def getPort(preferedPort=None):
109   logger.debug("GET PORT")
110
111   config_file, lock_file = _getConfigurationFilename()
112   oldmask = os.umask(0)
113   with open(lock_file, 'w') as lock:
114     # acquire lock
115     __acquire_lock(lock)
116
117     # read config
118     config = {'busy_ports':[]}
119     logger.debug("read configuration file")
120     try:
121       with open(config_file, 'r') as f:
122         config = pickle.load(f)
123     except:
124       logger.info("Problem loading PortManager file: %s"%config_file)
125       # In this case config dictionary is reset
126
127     logger.debug("load busy_ports: %s"%str(config["busy_ports"]))
128
129     # append port
130     busy_ports = config["busy_ports"]
131     port = preferedPort
132     if not port or __isPortUsed(port, busy_ports):
133       port = 2810
134       while __isPortUsed(port, busy_ports):
135         if port == 2810+100:
136           msg  = "\n"
137           msg += "Can't find a free port to launch omniNames\n"
138           msg += "Try to kill the running servers and then launch SALOME again.\n"
139           raise RuntimeError, msg
140         logger.debug("Port %s seems to be busy"%str(port))
141         if not port in config["busy_ports"]:
142           config["busy_ports"].append(port)
143         port = port + 1
144     logger.debug("found free port: %s"%str(port))
145     config["busy_ports"].append(port)
146
147     # write config
148     logger.debug("write busy_ports: %s"%str(config["busy_ports"]))
149     try:
150       with open(config_file, 'w') as f:
151         pickle.dump(config, f)
152     except IOError:
153       pass
154
155     # release lock
156     __release_lock(lock)
157   #
158
159   os.umask(oldmask)
160   logger.debug("get port: %s"%str(port))
161   return port
162 #
163
164 def releasePort(port):
165   port = int(port)
166   logger.debug("RELEASE PORT (%s)"%port)
167
168   config_file, lock_file = _getConfigurationFilename()
169   oldmask = os.umask(0)
170   with open(lock_file, 'w') as lock:
171     # acquire lock
172     __acquire_lock(lock)
173
174     # read config
175     config = {'busy_ports':[]}
176     logger.debug("read configuration file")
177     try:
178       with open(config_file, 'r') as f:
179         config = pickle.load(f)
180     except IOError: # empty file
181       pass
182
183     logger.debug("load busy_ports: %s"%str(config["busy_ports"]))
184
185     # remove port from list
186     busy_ports = config["busy_ports"]
187
188     if port in busy_ports:
189       busy_ports.remove(port)
190       config["busy_ports"] = busy_ports
191
192     # write config
193     logger.debug("write busy_ports: %s"%str(config["busy_ports"]))
194     try:
195       with open(config_file, 'w') as f:
196         pickle.dump(config, f)
197     except IOError:
198       pass
199
200     # release lock
201     __release_lock(lock)
202
203     logger.debug("released port port: %s"%str(port))
204
205   os.umask(oldmask)
206 #
207
208 def getBusyPorts():
209   busy_ports = []
210   config_file, lock_file = _getConfigurationFilename()
211   oldmask = os.umask(0)
212   with open(lock_file, 'w') as lock:
213     # acquire lock
214     __acquire_lock(lock)
215
216     # read config
217     config = {'busy_ports':[]}
218     logger.debug("read configuration file")
219     try:
220       with open(config_file, 'r') as f:
221         config = pickle.load(f)
222     except IOError: # empty file
223       pass
224
225     logger.debug("load busy_ports: %s"%str(config["busy_ports"]))
226
227     busy_ports = config["busy_ports"]
228     # release lock
229     __release_lock(lock)
230
231   os.umask(oldmask)
232   return busy_ports
233 #