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