]> SALOME platform Git repositories - modules/kernel.git/blob - bin/PortManager.py
Salome HOME
Bug fix on launcher for concurrent execution
[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.
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 from Singleton import Singleton
25
26 import multiprocessing
27 import time
28 import socket
29
30 import os
31 import sys
32 import threading
33 import SocketServer
34
35 try:
36   import cPickle as pickle
37 except:
38   import pickle
39
40 import struct
41 import ctypes
42
43 import logging
44 def createLogger():
45   logger = logging.getLogger(__name__)
46 #  logger.setLevel(logging.DEBUG)
47   ch = logging.StreamHandler()
48   ch.setLevel(logging.DEBUG)
49   formatter = logging.Formatter("%(levelname)s:%(threadName)s:%(message)s")
50   ch.setFormatter(formatter)
51   logger.addHandler(ch)
52   return logger
53 #
54 logger = createLogger()
55
56
57 if sys.platform == 'win32':
58   import multiprocessing.reduction    # make sockets pickable/inheritable
59
60 multiprocessing.freeze_support() # Add support for when a program which uses multiprocessing has been frozen to produce a Windows executable.
61
62 #------------------------------------
63 # A file locker (Linux only)
64 import fcntl
65 class PortManagerLock:
66   def __init__(self, filename, readonly=False, blocking=True):
67     # This will create it if it does not exist already
68     logger.debug("Create lock on %s"%filename)
69     self.__readonly = readonly
70     self.__blocking = blocking
71     self.__filename = filename
72     flag = 'w'
73     if self.__readonly:
74       flag = 'r'
75     self.handle = open(self.__filename, 'a+')
76
77   def acquire(self):
78     mode = fcntl.LOCK_EX
79     if not self.__blocking: # Raise an IOError exception if file has already been locked
80       mode = mode | fcntl.LOCK_NB
81     fcntl.flock(self.handle, mode)
82     logger.debug("lock acquired %s"%self.__blocking)
83
84   def release(self):
85     fcntl.flock(self.handle, fcntl.LOCK_UN)
86     logger.debug("lock released")
87
88   def __del__(self):
89     logger.debug("Close lock file")
90     self.handle.close()
91     os.remove(self.__filename)
92 #
93
94 def _getConfigurationFilename():
95   omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
96
97   from salome_utils import generateFileName
98   portmanager_config = generateFileName(omniorbUserPath,
99                                         prefix="omniORB",
100                                         suffix="PortManager",
101                                         extension="cfg",
102                                         hidden=True)
103   lock_file = portmanager_config + "-lock"
104   return (portmanager_config, lock_file)
105 #
106
107 def __isPortUsed(port, busy_ports):
108   return (port in busy_ports) or __isNetworkConnectionActiveOnPort(port)
109 #
110
111 def __isNetworkConnectionActiveOnPort(port):
112   # :NOTE: Under windows:
113   #        netstat options -l and -t are unavailable
114   #        grep command is unavailable
115   from subprocess import Popen, PIPE
116   (stdout, stderr) = Popen(['netstat','-an'], stdout=PIPE).communicate()
117   import StringIO
118   buf = StringIO.StringIO(stdout)
119   ports = buf.readlines()
120   # search for TCP - LISTEN connections
121   import re
122   regObj = re.compile( ".*tcp.*:([0-9]+).*:.*listen", re.IGNORECASE );
123   for item in ports:
124     try:
125       p = int(regObj.match(item).group(1))
126       if p == port: return True
127     except:
128       pass
129 #
130
131 def getPort(preferedPort=None):
132   logger.debug("GET PORT")
133
134   config_file, lock_file = _getConfigurationFilename()
135   with open(lock_file, 'w') as lock:
136     # acquire lock
137     fcntl.flock(lock, fcntl.LOCK_EX)
138
139     # read config
140     config = {'busy_ports':[]}
141     logger.debug("read configuration file")
142     try:
143       with open(config_file, 'r') as f:
144         config = pickle.load(f)
145     except IOError: # empty file
146       pass
147
148     logger.debug("load busy_ports: %s"%str(config["busy_ports"]))
149
150     # append port
151     busy_ports = config["busy_ports"]
152     port = preferedPort
153     if not port or __isPortUsed(port, busy_ports):
154       port = 2810
155       while __isPortUsed(port, busy_ports):
156         if port == 2810+100:
157           msg  = "\n"
158           msg += "Can't find a free port to launch omniNames\n"
159           msg += "Try to kill the running servers and then launch SALOME again.\n"
160           raise RuntimeError, msg
161         port = port + 1
162     logger.debug("found free port: %s"%str(port))
163     config["busy_ports"].append(port)
164
165     # write config
166     logger.debug("write busy_ports: %s"%str(config["busy_ports"]))
167     try:
168       with open(config_file, 'w') as f:
169         pickle.dump(config, f)
170     except IOError:
171       pass
172
173     # release lock
174     fcntl.flock(lock, fcntl.LOCK_UN)
175
176     logger.debug("get port: %s"%str(port))
177     return port
178 #
179
180 def releasePort(port):
181   port = int(port)
182   logger.debug("RELEASE PORT (%s)"%port)
183
184   config_file, lock_file = _getConfigurationFilename()
185   with open(lock_file, 'w') as lock:
186     # acquire lock
187     fcntl.flock(lock, fcntl.LOCK_EX)
188
189     # read config
190     config = {'busy_ports':[]}
191     logger.debug("read configuration file")
192     try:
193       with open(config_file, 'r') as f:
194         config = pickle.load(f)
195     except IOError: # empty file
196       pass
197
198     logger.debug("load busy_ports: %s"%str(config["busy_ports"]))
199
200     # remove port from list
201     busy_ports = config["busy_ports"]
202
203     if port in busy_ports:
204       busy_ports.remove(port)
205       config["busy_ports"] = busy_ports
206
207     # write config
208     logger.debug("write busy_ports: %s"%str(config["busy_ports"]))
209     try:
210       with open(config_file, 'w') as f:
211         pickle.dump(config, f)
212     except IOError:
213       pass
214
215     # release lock
216     fcntl.flock(lock, fcntl.LOCK_UN)
217
218     logger.debug("released port port: %s"%str(port))
219 #
220
221 def getBusyPorts():
222   config_file, lock_file = _getConfigurationFilename()
223   with open(lock_file, 'w') as lock:
224     # acquire lock
225     fcntl.flock(lock, fcntl.LOCK_EX)
226
227     # read config
228     config = {'busy_ports':[]}
229     logger.debug("read configuration file")
230     try:
231       with open(config_file, 'r') as f:
232         config = pickle.load(f)
233     except IOError: # empty file
234       pass
235
236     logger.debug("load busy_ports: %s"%str(config["busy_ports"]))
237
238     busy_ports = config["busy_ports"]
239     # release lock
240     fcntl.flock(lock, fcntl.LOCK_UN)
241
242     return busy_ports
243 #