Salome HOME
Revert "Synchronize adm files"
[modules/kernel.git] / bin / searchFreePort.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
25 import os
26 import sys
27
28 def __setup_config(nsport, args, save_config):
29   #
30   from salome_utils import generateFileName, getHostName
31   hostname = getHostName()
32   #
33   omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
34   kwargs={}
35   if omniorbUserPath is not None:
36     kwargs["with_username"]=True
37   #
38   from ORBConfigFile import writeORBConfigFile
39   omniorb_config, giopsize = writeORBConfigFile(omniorbUserPath, hostname, nsport, kwargs)
40   args['port'] = os.environ['NSPORT']
41   #
42   if save_config:
43     last_running_config = generateFileName(omniorbUserPath, prefix="omniORB",
44                                            suffix="last",
45                                            extension="cfg",
46                                            hidden=True,
47                                            **kwargs)
48     os.environ['LAST_RUNNING_CONFIG'] = last_running_config
49     try:
50       if sys.platform == "win32":
51         import shutil
52         shutil.copyfile(omniorb_config, last_running_config)
53       else:
54         try:
55           if os.access(last_running_config, os.F_OK):
56             os.remove(last_running_config)
57         except OSError:
58           pass
59         os.symlink(omniorb_config, last_running_config)
60         pass
61       pass
62     except:
63       pass
64   #
65 #
66
67 def searchFreePort_withoutPortManager(args={}, save_config=1, use_port=None):
68   # :NOTE: Under windows:
69   #        netstat options -l and -t are unavailable
70   #        grep command is unavailable
71   from subprocess import Popen, PIPE
72   (stdout, stderr) = Popen(['netstat','-an'], stdout=PIPE).communicate()
73   import StringIO
74   buf = StringIO.StringIO(stdout)
75   ports = buf.readlines()
76
77   #
78   def portIsUsed(port, data):
79     import re
80     regObj = re.compile( ".*tcp.*:([0-9]+).*:.*listen", re.IGNORECASE );
81     for item in data:
82       try:
83         p = int(regObj.match(item).group(1))
84         if p == port: return True
85         pass
86       except:
87         pass
88       pass
89     return False
90   #
91
92   if use_port:
93     print "Check if port can be used: %d" % use_port,
94     if not portIsUsed(use_port, ports):
95       print "- OK"
96       __setup_config(use_port, args, save_config)
97       return
98     else:
99       print "- KO: port is busy"
100     pass
101   #
102
103   print "Searching for a free port for naming service:",
104   #
105
106   NSPORT=2810
107   limit=NSPORT+100
108   #
109
110   while 1:
111     if not portIsUsed(NSPORT, ports):
112       print "%s - OK"%(NSPORT)
113       __setup_config(NSPORT, args, save_config)
114       break
115     print "%s"%(NSPORT),
116     if NSPORT == limit:
117       msg  = "\n"
118       msg += "Can't find a free port to launch omniNames\n"
119       msg += "Try to kill the running servers and then launch SALOME again.\n"
120       raise RuntimeError, msg
121     NSPORT=NSPORT+1
122     pass
123   #
124 #
125
126 def searchFreePort_withPortManager(queue, args={}, save_config=1, use_port=None):
127   from PortManager import getPort
128   port = getPort(use_port)
129
130   if use_port:
131     print "Check if port can be used: %d" % use_port,
132     if port == use_port and port != -1:
133       print "- OK"
134       __setup_config(use_port, args, save_config)
135       return
136     else:
137       print "- KO: port is busy"
138       pass
139   #
140   print "Searching for a free port for naming service:",
141   if port == -1: # try again
142     port = getPort(use_port)
143
144   if port != -1:
145     print "%s - OK"%(port)
146     __setup_config(port, args, save_config)
147   else:
148     print "Unable to obtain port"
149
150   queue.put([os.environ['OMNIORB_CONFIG'],
151              os.environ['NSPORT'],
152              os.environ['NSHOST']])
153 #
154
155 def __savePortToFile(args):
156   # Save Naming service port name into
157   # the file args["ns_port_log_file"]
158   if args.has_key('ns_port_log_file'):
159     omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
160     file_name = os.path.join(omniorbUserPath, args["ns_port_log_file"])
161     with open(file_name, "w") as f:
162       f.write(os.environ['NSPORT'])
163 #
164
165 def searchFreePort(args={}, save_config=1, use_port=None):
166   """
167   Search free port for SALOME session.
168   Returns first found free port number.
169   """
170   try:
171     import PortManager # mandatory
172     from multiprocessing import Process, Queue
173     queue = Queue()
174     p = Process(target = searchFreePort_withPortManager, args=(queue, args, save_config, use_port,))
175     p.start()
176     info = queue.get()
177
178     os.environ['OMNIORB_CONFIG'] = info[0]
179     os.environ['NSPORT'] = info[1]
180     args['port'] = os.environ['NSPORT']
181     os.environ['NSHOST'] = info[2]
182     __savePortToFile(args)
183
184     p.join() # this blocks until the process terminates
185   except ImportError:
186     searchFreePort_withoutPortManager(args, save_config, use_port)
187     __savePortToFile(args)
188 #