2 # -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2013 CEA/DEN, EDF R&D, OPEN CASCADE
5 # Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
6 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
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.
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.
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
22 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
25 def searchFreePort(args={}, save_config=1, use_port=None):
27 Search free port for SALOME session.
28 Returns first found free port number.
30 import sys, os, re, shutil
32 # :NOTE: Under windows:
33 # netstat options -l and -t are unavailable
34 # grep command is unavailable
36 from subprocess import Popen, PIPE
37 (stdout, stderr) = Popen(['netstat','-an'], stdout=PIPE).communicate()
39 buf = StringIO.StringIO(stdout)
40 ports = buf.readlines()
43 def portIsUsed(port, data):
44 regObj = re.compile( ".*tcp.*:([0-9]+).*:.*listen", re.IGNORECASE );
47 p = int(regObj.match(item).group(1))
48 if p == port: return True
56 def setup_config(nsport):
58 from salome_utils import generateFileName, getHostName
59 hostname = getHostName()
61 omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
63 if omniorbUserPath is not None:
64 kwargs["with_username"]=True
66 from ORBConfigFile import writeORBConfigFile
67 omniorb_config, giopsize = writeORBConfigFile(omniorbUserPath, hostname, nsport, kwargs)
68 args['port'] = os.environ['NSPORT']
71 last_running_config = generateFileName(omniorbUserPath, prefix="omniORB",
76 os.environ['LAST_RUNNING_CONFIG'] = last_running_config
78 if sys.platform == "win32":
80 shutil.copyfile(omniorb_config, last_running_config)
83 if os.access(last_running_config, os.F_OK):
84 os.remove(last_running_config)
87 os.symlink(omniorb_config, last_running_config)
95 print "Check if port can be used: %d" % use_port,
96 if not portIsUsed(use_port, ports):
98 setup_config(use_port)
101 print "- KO: port is busy"
105 print "Searching for a free port for naming service:",
113 if not portIsUsed(NSPORT, ports):
114 print "%s - OK"%(NSPORT)
120 msg += "Can't find a free port to launch omniNames\n"
121 msg += "Try to kill the running servers and then launch SALOME again.\n"
122 raise RuntimeError, msg