Salome HOME
Merge from V6_main 15/03/2013
[modules/kernel.git] / bin / searchFreePort.py
1 #!/usr/bin/env python
2 #  -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2012  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
25 def searchFreePort(args={}, save_config=1, use_port=None):
26   """
27   Search free port for SALOME session.
28   Returns first found free port number.
29   """
30   import sys, os, re, shutil
31
32   # :NOTE: Under windows:
33   #        netstat options -l and -t are unavailable
34   #        grep command is unavailable
35
36   from subprocess import Popen, PIPE
37   (stdout, stderr) = Popen(['netstat','-an'], stdout=PIPE).communicate()
38   import StringIO
39   buf = StringIO.StringIO(stdout)
40   ports = buf.readlines()
41
42   #
43   def portIsUsed(port, data):
44     regObj = re.compile( ".*tcp.*:([0-9]+).*:.*listen", re.IGNORECASE );
45     for item in data:
46       try:
47         p = int(regObj.match(item).group(1))
48         if p == port: return True
49         pass
50       except:
51         pass
52       pass
53     return False
54   #
55
56   def setup_config(nsport):
57       #
58       from salome_utils import generateFileName, getHostName
59       hostname = getHostName()
60       #
61       home  = os.getenv("HOME")
62       appli = os.getenv("APPLI")
63       kwargs={}
64       if appli is not None:
65         home = os.path.join(os.path.realpath(home), appli, "USERS")
66         kwargs["with_username"]=True
67       #
68       from ORBConfigFile import writeORBConfigFile
69       omniorb_config, giopsize = writeORBConfigFile(home, hostname, nsport, kwargs)
70       args['port'] = os.environ['NSPORT']
71       #
72       if save_config:
73         last_running_config = generateFileName(home, prefix="omniORB",
74                                                suffix="last",
75                                                extension="cfg",
76                                                hidden=True,
77                                                **kwargs)
78         os.environ['LAST_RUNNING_CONFIG'] = last_running_config
79         try:
80           if sys.platform == "win32":
81             import shutil
82             shutil.copyfile(omniorb_config, last_running_config)
83           else:
84             try:
85               if os.access(last_running_config, os.F_OK):
86                 os.remove(last_running_config)
87             except OSError:
88               pass
89             os.symlink(omniorb_config, last_running_config)
90             pass
91           pass
92         except:
93           pass
94       #
95
96   if use_port:
97     print "Check if port can be used: %d" % use_port,
98     if not portIsUsed(use_port, ports):
99       print "- OK"
100       setup_config(use_port)
101       return
102     else:
103       print "- KO: port is busy"
104     pass
105   #
106   
107   print "Searching for a free port for naming service:",
108   #
109
110   NSPORT=2810
111   limit=NSPORT+100
112   #
113
114   while 1:
115     if not portIsUsed(NSPORT, ports):
116       print "%s - OK"%(NSPORT)
117       setup_config(NSPORT)
118       break
119     print "%s"%(NSPORT),
120     if NSPORT == limit:
121       msg  = "\n"
122       msg += "Can't find a free port to launch omniNames\n"
123       msg += "Try to kill the running servers and then launch SALOME again.\n"
124       raise RuntimeError, msg
125     NSPORT=NSPORT+1
126     pass
127   #
128   
129   return