2 # -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2022 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, or (at your option) any later version.
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
26 # \brief Module that provides services to launch SALOME
29 import sys, os, string, glob, time, pickle, re
32 from launchConfigureParser import verbose
33 from server import process_id, Server
36 from salomeContextUtils import ScriptAndArgsObjectEncoder
38 from runSalomeCommon import setVerbose, InterpServer, CatalogServer, SalomeDSServer, ConnectionManagerServer, RegistryServer, ContainerCPPServer, LoggerServer, CommonSessionServer, SessionServer, LauncherServer
39 # -----------------------------------------------------------------------------
41 from killSalome import killAllPorts
45 kill servers from a previous SALOME execution, if needed,
46 on the CORBA port given in args of runSalome
49 from killSalomeWithPort import killMyPort
50 my_port=str(args['port'])
54 print("problem in killLocalPort()")
58 def givenPortKill(port):
60 kill servers from a previous SALOME execution, if needed,
61 on the same CORBA port
64 from killSalomeWithPort import killMyPort
69 print("problem in LocalPortKill(), killMyPort(%s)"%port)
73 def kill_salome(args):
75 Kill servers from previous SALOME executions, if needed;
76 depending on args 'killall' or 'portkill', kill all executions,
77 or only execution on the same CORBA port
82 elif args['portkill']:
83 givenPortKill(str(args['port']))
86 """Salome Session Graphic User Interface activation"""
90 import SALOME_ModuleCatalog
91 import SALOME_Session_idl
92 session=clt.waitNS("/Kernel/Session",SALOME.Session)
93 session.GetInterface()
95 # -----------------------------------------------------------------------------
97 def startSalome(args, modules_list, modules_root_dir):
98 """Launch all SALOME servers requested by args"""
99 init_time = os.times()
101 if verbose(): print("startSalome ", args)
104 # Set server launch command
106 if 'server_launch_mode' in args:
107 Server.set_server_launch_mode(args['server_launch_mode'])
110 # Wake up session option
112 if args['wake_up_session']:
113 if "OMNIORB_CONFIG" not in os.environ:
114 from salome_utils import generateFileName
115 omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
117 if omniorbUserPath is not None:
118 kwargs["with_username"]=True
120 last_running_config = generateFileName(omniorbUserPath, prefix="omniORB",
125 os.environ['OMNIORB_CONFIG'] = last_running_config
130 # Initialisation ORB and Naming Service
133 clt=orbmodule.client(args)
137 # Wake up session option
139 if args['wake_up_session']:
143 import SALOME_ModuleCatalog
144 import SALOME_Session_idl
145 session = clt.waitNS("/Kernel/Session",SALOME.Session)
146 status = session.GetStatSession()
148 from salome_utils import getPortNumber
149 port = getPortNumber()
152 msg += "Session GUI for port number %s is already active."%(port)
154 msg += "If you which to wake up another session,"
156 msg += "please use variable OMNIORB_CONFIG"
158 msg += "to get the correct session object in naming service."
159 sys.stdout.write(msg+"\n")
162 session.GetInterface()
163 args["session_object"] = session
166 # Launch Logger Server (optional)
167 # and wait until it is registered in naming service
171 myServer=LoggerServer(args)
173 clt.waitLogger("Logger")
176 # Launch Session Server (to show splash ASAP)
179 if args["gui"] and not args['launcher_only']:
180 mySessionServ = SessionServer(args,args['modules'],modules_root_dir)
181 mySessionServ.setpath(modules_list,modules_root_dir)
186 # Launch Registry Server,
187 # and wait until it is registered in naming service
190 if ('registry' not in args['embedded']) | (args["gui"] == 0) :
191 myServer=RegistryServer(args)
193 if sys.platform == "win32":
194 clt.waitNS("/Registry")
196 clt.waitNSPID("/Registry",myServer.PID)
200 # Launch Catalog Server,
201 # and wait until it is registered in naming service
204 if ('moduleCatalog' not in args['embedded']) | (args["gui"] == 0):
205 cataServer=CatalogServer(args)
206 cataServer.setpath(modules_list,modules_root_dir)
208 import SALOME_ModuleCatalog
209 if sys.platform == "win32":
210 clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
212 clt.waitNSPID("/Kernel/ModulCatalog",cataServer.PID,SALOME_ModuleCatalog.ModuleCatalog)
216 # Launch SalomeDS Server,
217 # and wait until it is registered in naming service
220 # print("ARGS = ",args)
221 if ('study' not in args['embedded']) | (args["gui"] == 0):
223 myServer=SalomeDSServer(args)
225 if sys.platform == "win32":
228 clt.waitNSPID("/Study",myServer.PID)
232 # Launch LauncherServer
235 if not 'launcher' in args:
236 myCmServer = LauncherServer(args)
237 myCmServer.setpath(modules_list,modules_root_dir)
242 # Launch ConnectionManagerServer
245 if not args['launcher_only']:
246 myConnectionServer = ConnectionManagerServer(args)
247 myConnectionServer.run()
249 from Utils_Identity import getShortHostName
251 if os.getenv("HOSTNAME") == None:
252 if os.getenv("HOST") == None:
253 os.environ["HOSTNAME"]=getShortHostName()
255 os.environ["HOSTNAME"]=os.getenv("HOST")
257 theComputer = getShortHostName()
260 # Launch local C++ Container (FactoryServer),
261 # and wait until it is registered in naming service
264 if ('cppContainer' in args['standalone']) | (args["gui"] == 0) :
265 myServer=ContainerCPPServer(args, with_gui=args["gui"]!=0)
267 if sys.platform == "win32":
268 clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
270 clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID)
273 if 'pyContainer' in args['standalone']:
274 raise Exception('Python containers no longer supported')
277 # Wait until Session Server is registered in naming service
280 if args["gui"] and not args['launcher_only']:
285 import SALOME_ModuleCatalog
286 import SALOME_Session_idl
287 if sys.platform == "win32":
288 session=clt.waitNS("/Kernel/Session",SALOME.Session)
290 session=clt.waitNSPID("/Kernel/Session",mySessionServ.PID,SALOME.Session)
291 args["session_object"] = session
292 end_time = os.times()
293 if verbose(): print()
294 print("Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
297 # ASV start GUI without Loader
299 # session.GetInterface()
302 # additional external python interpreters
308 nbaddi = args['interp']
311 traceback.print_exc()
312 print("-------------------------------------------------------------")
313 print("-- to get an external python interpreter:runSalome --interp=1")
314 print("-------------------------------------------------------------")
316 if verbose(): print("additional external python interpreters: ", nbaddi)
318 for i in range(nbaddi):
320 anInterp=InterpServer(args)
323 # set PYTHONINSPECT variable (python interpreter in interactive mode)
325 os.environ["PYTHONINSPECT"]="1"
333 # -----------------------------------------------------------------------------
335 def useSalome(args, modules_list, modules_root_dir):
337 Launch all SALOME servers requested by args,
338 save list of process, give info to user,
339 show registered objects in Naming Service.
345 clt = startSalome(args, modules_list, modules_root_dir)
348 traceback.print_exc()
351 print("--- Error during Salome launch ---")
355 from addToKillList import addToKillList
356 from killSalomeWithPort import getPiDict
358 filedict = getPiDict(args['port'])
359 for pid, cmd in list(process_id.items()):
360 addToKillList(pid, cmd, args['port'])
363 if verbose(): print("""
364 Saving of the dictionary of Salome processes in %s
365 To kill SALOME processes from a console (kill all sessions from all ports):
367 To kill SALOME from the present interpreter, if it is not closed :
368 killLocalPort() --> kill this session
369 (use CORBA port from args of runSalome)
370 givenPortKill(port) --> kill a specific session with given CORBA port
371 killAllPorts() --> kill all sessions
373 runSalome, with --killall option, starts with killing
374 the processes resulting from the previous execution.
378 # Print Naming Service directory list
384 print(" --- registered objects tree in Naming Service ---")
388 if not args['gui'] or not args['session_gui']:
389 if args['shutdown_servers']:
391 def __init__(self, port):
393 import killSalomeWithPort
394 self.killSalomeWithPort = killSalomeWithPort
397 self.killSalomeWithPort.killMyPort(self.port)
403 atexit.register(func, __utils__(args['port']))
407 # run python scripts, passed as command line arguments
409 if 'gui' in args and 'session_gui' in args:
410 if not args['gui'] or not args['session_gui']:
411 if 'study_hdf' in args:
412 toopen = args['study_hdf']
415 salome.salome_init_with_session(path=toopen)
416 if 'pyscript' in args:
417 toimport = args['pyscript']
418 from salomeContextUtils import formatScriptsAndArgs
419 command = formatScriptsAndArgs(toimport, escapeSpaces=True)
421 proc = subprocess.Popen(command, shell=True)
422 addToKillList(proc.pid, command, args['port'])
424 if res: sys.exit(1) # if there's an error when executing script, we should explicitly exit
428 def execScript(script_path):
429 print('executing', script_path)
430 sys.path.insert(0, os.path.realpath(os.path.dirname(script_path)))
431 exec(compile(open(script_path).read(), script_path, 'exec'),globals())
434 # -----------------------------------------------------------------------------
436 def registerEnv(args, modules_list, modules_root_dir):
438 Register args, modules_list, modules_root_dir in a file
439 for further use, when SALOME is launched embedded in an other application.
441 from salome_utils import getTmpDir
442 fileEnv = getTmpDir()
443 from salome_utils import getUserName
444 fileEnv += getUserName() + "_" + str(args['port']) \
445 + '_' + args['appname'].upper() + '_env'
446 fenv=open(fileEnv,'w')
447 pickle.dump((args, modules_list, modules_root_dir),fenv)
449 os.environ["SALOME_LAUNCH_CONFIG"] = fileEnv
451 # -----------------------------------------------------------------------------
454 """Salome Launch, when embedded in other application"""
455 fileEnv = os.environ["SALOME_LAUNCH_CONFIG"]
456 fenv=open(fileEnv,'r')
457 args, modules_list, modules_root_dir = pickle.load(fenv)
460 from searchFreePort import searchFreePort
461 searchFreePort(args, 0)
462 clt = useSalome(args, modules_list, modules_root_dir)
465 # -----------------------------------------------------------------------------
467 def addToPidict(args):
469 from addToKillList import addToKillList
470 for pid, cmd in list(process_id.items()):
471 addToKillList(pid, cmd, args['port'])
473 # -----------------------------------------------------------------------------
475 def main(exeName=None):
476 """Salome launch as a main application"""
478 # define folder to store omniorb config (initially in virtual application folder)
480 from salomeContextUtils import setOmniOrbUserPath
482 except Exception as e:
486 from salome_utils import getHostName
487 keep_env = not os.getenv('SALOME_PLEASE_SETUP_ENVIRONMENT_AS_BEFORE')
488 args, modules_list, modules_root_dir = setenv.get_config(exeName=exeName, keepEnvironment=keep_env)
489 print("runSalome running on %s" % getHostName())
493 if 'save_config' in args:
494 save_config = args['save_config']
497 if args['wake_up_session']:
500 if test and not 'launcher' in args:
501 from searchFreePort import searchFreePort
502 searchFreePort(args, save_config, args.get('useport'))
506 setenv.set_env(args, modules_list, modules_root_dir, keepEnvironment=keep_env)
507 clt = useSalome(args, modules_list, modules_root_dir)
510 # -----------------------------------------------------------------------------
512 def foreGround(clt, args):
514 if "session_object" not in args:
516 session = args["session_object"]
518 # Wait until gui is arrived
528 status = session.GetStatSession()
529 gui_detected = status.activeGUI
530 session_pid = session.getPID()
535 from time import sleep
545 from salome_utils import getPortNumber
546 port = getPortNumber()
549 if sys.platform == "win32":
550 server.CMD = [os.getenv("PYTHONBIN"), "-m", "killSalomeWithPort", "--spy", "%s"%(session_pid or os.getpid()), "%s"%(port)]
552 server.CMD = ["killSalomeWithPort.py", "--spy", "%s"%(session_pid or os.getpid()), "%s"%(port)]
554 # os.system("killSalomeWithPort.py --spy %s %s &"%(os.getpid(), port))
560 status = session.GetStatSession()
561 assert status.activeGUI
564 from time import sleep
568 except KeyboardInterrupt:
569 from killSalomeWithPort import killMyPort
578 test = args['gui'] and args['session_gui']
579 test = test or args['wake_up_session']
581 # The next test covers the --pinter option or if var PYTHONINSPECT is set
583 test = test and not os.environ.get('PYTHONINSPECT')
585 # The next test covers the python -i $KERNEL_ROOT_DIR/bin/salome/runSalome.py case
588 from ctypes import POINTER, c_int, cast, pythonapi
589 iflag_ptr = cast(pythonapi.Py_InteractiveFlag, POINTER(c_int))
590 test = test and not iflag_ptr.contents.value
594 # test = test and os.getenv("SALOME_TEST_MODE", "0") != "1"
595 test = test and args['foreground']
598 from time import sleep
600 foreGround(clt, args)
605 # -----------------------------------------------------------------------------
607 if __name__ == "__main__":