Salome HOME
updated copyright message
[modules/kernel.git] / bin / searchFreePort.py
1 #  -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2023  CEA, EDF, OPEN CASCADE
3 #
4 # Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
5 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 #
7 # This library is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU Lesser General Public
9 # License as published by the Free Software Foundation; either
10 # version 2.1 of the License, or (at your option) any later version.
11 #
12 # This library is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 # Lesser General Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser General Public
18 # License along with this library; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
20 #
21 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 #
23
24 import os
25 import sys
26
27 def __setup_config(nsport, args, save_config):
28   #
29   from salome_utils import generateFileName, getHostName
30   hostname = getHostName()
31   #
32   omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
33   kwargs={}
34   if omniorbUserPath is not None:
35     kwargs["with_username"]=True
36   #
37   from ORBConfigFile import writeORBConfigFile
38   omniorb_config, giopsize = writeORBConfigFile(omniorbUserPath, hostname, nsport, kwargs)
39   args['port'] = os.environ['NSPORT']
40   #
41   if save_config:
42     last_running_config = generateFileName(omniorbUserPath, prefix="omniORB",
43                                            suffix="last",
44                                            extension="cfg",
45                                            hidden=True,
46                                            **kwargs)
47     os.environ['LAST_RUNNING_CONFIG'] = last_running_config
48     try:
49       if sys.platform == "win32":
50         import shutil
51         shutil.copyfile(omniorb_config, last_running_config)
52       else:
53         try:
54           if os.access(last_running_config, os.F_OK):
55             os.remove(last_running_config)
56         except OSError:
57           pass
58         os.symlink(omniorb_config, last_running_config)
59         pass
60       pass
61     except Exception:
62       pass
63   #
64 #
65
66 def searchFreePort_withPortManager(queue, args={}, save_config=1, use_port=None):
67   from PortManager import getPort
68   port = getPort(use_port)
69
70   if use_port:
71     print("Check if port can be used: %d" % use_port, end=' ')
72     if port == use_port and port != -1:
73       print("- OK")
74       __setup_config(use_port, args, save_config)
75       queue.put([os.environ['OMNIORB_CONFIG'],
76                  os.environ['NSPORT'],
77                  os.environ['NSHOST']])
78       return
79     else:
80       print("- KO: port is busy")
81       pass
82   #
83   print("Searching for a free port for naming service:", end=' ')
84   if port == -1: # try again
85     port = getPort(use_port)
86
87   if port != -1:
88     print("%s - OK"%(port))
89     __setup_config(port, args, save_config)
90   else:
91     print("Unable to obtain port")
92
93   queue.put([os.environ['OMNIORB_CONFIG'],
94              os.environ['NSPORT'],
95              os.environ['NSHOST']])
96 #
97
98 def __savePortToFile(args):
99   # Save Naming service port name into
100   # the file args["ns_port_log_file"]
101   if 'ns_port_log_file' in args:
102     omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
103     file_name = os.path.join(omniorbUserPath, args["ns_port_log_file"])
104     with open(file_name, "w") as f:
105       f.write(os.environ['NSPORT'])
106 #
107
108 def searchFreePort(args={}, save_config=1, use_port=None):
109   """
110   Search free port for SALOME session.
111   Returns first found free port number.
112   """
113   try:
114     import PortManager # mandatory
115     from multiprocessing import Process, Queue
116     queue = Queue()
117     p = Process(target = searchFreePort_withPortManager, args=(queue, args, save_config, use_port,))
118     p.start()
119     info = queue.get()
120
121     os.environ['OMNIORB_CONFIG'] = info[0]
122     os.environ['NSPORT'] = info[1]
123     args['port'] = os.environ['NSPORT']
124     os.environ['NSHOST'] = info[2]
125     __savePortToFile(args)
126
127     p.join() # this blocks until the process terminates
128   except ImportError:
129     raise Exception('PortManager module not found')
130 #