Salome HOME
Restore registering CORBA objects, removed by previous wrong commit
[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   if sys.platform == "win32":
94     out, _ = Popen(['netstat','-a','-n','-p tcp'], stdout=PIPE).communicate()
95   else:
96     out, _ = Popen(['netstat','-ant'], stdout=PIPE).communicate()
97   import StringIO
98   buf = StringIO.StringIO(out)
99   ports = buf.readlines()
100   # search for TCP - LISTEN connections
101   import re
102   regObj = re.compile( ".*tcp.*:([0-9]+).*:.*listen", re.IGNORECASE );
103   for item in ports:
104     try:
105       p = int(regObj.match(item).group(1))
106       if p == port: return True
107     except:
108       pass
109   return False
110 #
111
112 def getPort(preferedPort=None):
113   logger.debug("GET PORT")
114
115   config_file, lock_file = _getConfigurationFilename()
116   oldmask = os.umask(0)
117   with open(lock_file, 'w') as lock:
118     # acquire lock
119     __acquire_lock(lock)
120
121     # read config
122     config = {'busy_ports':[]}
123     logger.debug("read configuration file")
124     try:
125       with open(config_file, 'r') as f:
126         config = pickle.load(f)
127     except:
128       logger.info("Problem loading PortManager file: %s"%config_file)
129       # In this case config dictionary is reset
130
131     logger.debug("load busy_ports: %s"%str(config["busy_ports"]))
132
133     # append port
134     busy_ports = config["busy_ports"]
135     port = preferedPort
136     if not port or __isPortUsed(port, busy_ports):
137       port = 2810
138       while __isPortUsed(port, busy_ports):
139         if port == 2810+100:
140           msg  = "\n"
141           msg += "Can't find a free port to launch omniNames\n"
142           msg += "Try to kill the running servers and then launch SALOME again.\n"
143           raise RuntimeError, msg
144         logger.debug("Port %s seems to be busy"%str(port))
145         if not port in config["busy_ports"]:
146           config["busy_ports"].append(port)
147         port = port + 1
148     logger.debug("found free port: %s"%str(port))
149     config["busy_ports"].append(port)
150
151     # write config
152     logger.debug("write busy_ports: %s"%str(config["busy_ports"]))
153     try:
154       with open(config_file, 'w') as f:
155         pickle.dump(config, f)
156     except IOError:
157       pass
158
159     # release lock
160     __release_lock(lock)
161   #
162
163   os.umask(oldmask)
164   logger.debug("get port: %s"%str(port))
165   return port
166 #
167
168 def releasePort(port):
169   port = int(port)
170   logger.debug("RELEASE PORT (%s)"%port)
171
172   config_file, lock_file = _getConfigurationFilename()
173   oldmask = os.umask(0)
174   with open(lock_file, 'w') as lock:
175     # acquire lock
176     __acquire_lock(lock)
177
178     # read config
179     config = {'busy_ports':[]}
180     logger.debug("read configuration file")
181     try:
182       with open(config_file, 'r') as f:
183         config = pickle.load(f)
184     except IOError: # empty file
185       pass
186
187     logger.debug("load busy_ports: %s"%str(config["busy_ports"]))
188
189     # remove port from list
190     busy_ports = config["busy_ports"]
191
192     if port in busy_ports:
193       busy_ports.remove(port)
194       config["busy_ports"] = busy_ports
195
196     # write config
197     logger.debug("write busy_ports: %s"%str(config["busy_ports"]))
198     try:
199       with open(config_file, 'w') as f:
200         pickle.dump(config, f)
201     except IOError:
202       pass
203
204     # release lock
205     __release_lock(lock)
206
207     logger.debug("released port port: %s"%str(port))
208
209   os.umask(oldmask)
210 #
211
212 def getBusyPorts():
213   busy_ports = []
214   config_file, lock_file = _getConfigurationFilename()
215   oldmask = os.umask(0)
216   with open(lock_file, 'w') as lock:
217     # acquire lock
218     __acquire_lock(lock)
219
220     # read config
221     config = {'busy_ports':[]}
222     logger.debug("read configuration file")
223     try:
224       with open(config_file, 'r') as f:
225         config = pickle.load(f)
226     except IOError: # empty file
227       pass
228
229     logger.debug("load busy_ports: %s"%str(config["busy_ports"]))
230
231     busy_ports = config["busy_ports"]
232     # release lock
233     __release_lock(lock)
234
235   os.umask(oldmask)
236   return busy_ports
237 #