2 # -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2019 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 # -----------------------------------------------------------------------------
40 from killSalome import killAllPorts
44 kill servers from a previous SALOME execution, if needed,
45 on the CORBA port given in args of runSalome
48 from killSalomeWithPort import killMyPort
49 my_port=str(args['port'])
53 print("problem in killLocalPort()")
57 def givenPortKill(port):
59 kill servers from a previous SALOME execution, if needed,
60 on the same CORBA port
63 from killSalomeWithPort import killMyPort
68 print("problem in LocalPortKill(), killMyPort(%s)"%port)
72 def kill_salome(args):
74 Kill servers from previous SALOME executions, if needed;
75 depending on args 'killall' or 'portkill', kill all executions,
76 or only execution on the same CORBA port
81 elif args['portkill']:
82 givenPortKill(str(args['port']))
84 # -----------------------------------------------------------------------------
86 # Class definitions to launch CORBA Servers
89 class InterpServer(Server):
90 def __init__(self,args):
92 if sys.platform == "win32":
93 self.CMD=['cmd', '/c', 'start cmd.exe', '/K', 'python']
94 elif sys.platform == "darwin":
95 env_ld_library_path=['env', 'DYLD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
96 self.CMD=['xterm', '-e'] + env_ld_library_path + ['python']
98 env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
99 self.CMD=['xterm', '-e'] + env_ld_library_path + ['python']
104 print("INTERPSERVER::command = ", command)
106 pid = subprocess.Popen(command).pid
107 process_id[pid]=self.CMD
112 def get_cata_path(list_modules,modules_root_dir):
113 """Build a list of catalog paths (cata_path) to initialize the ModuleCatalog server
118 for module in list_modules:
119 if module in modules_root_dir:
120 module_root_dir=modules_root_dir[module]
121 module_cata=module+"Catalog.xml"
122 cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources",module.lower(), module_cata)
124 if os.path.exists(cata_file):
125 cata_path.append(cata_file)
126 modules_cata[module]=cata_file
128 cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources", module_cata)
129 if os.path.exists(cata_file):
130 cata_path.append(cata_file)
131 modules_cata[module]=cata_file
133 for path in os.getenv("SALOME_CATALOGS_PATH","").split(os.pathsep):
134 if os.path.exists(path):
135 for cata_file in glob.glob(os.path.join(path,"*Catalog.xml")):
136 module_name= os.path.basename(cata_file)[:-11]
137 if module_name not in modules_cata:
138 cata_path.append(cata_file)
139 modules_cata[module_name]=cata_file
143 class CatalogServer(Server):
144 def __init__(self,args):
147 self.SCMD1=['SALOME_ModuleCatalog_Server','-common']
149 home_dir=os.getenv('HOME')
150 if home_dir is not None:
151 self.SCMD2=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')]
153 def setpath(self,modules_list,modules_root_dir):
154 list_modules = modules_list[:]
155 list_modules.reverse()
156 if self.args["gui"] :
157 list_modules = ["KERNEL", "GUI"] + list_modules
159 list_modules = ["KERNEL"] + list_modules
161 cata_path=get_cata_path(list_modules,modules_root_dir)
163 self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
167 class SalomeDSServer(Server):
168 def __init__(self,args):
171 self.CMD=['SALOMEDS_Server']
175 class ConnectionManagerServer(Server):
176 def __init__(self,args):
179 self.CMD=['SALOME_ConnectionManagerServer']
180 if 'launcher' in self.args:
181 pos = args['launcher'].find(":")
183 self.CMD+=['-ORBInitRef']
184 machine = args['launcher'][0:pos]
185 port = args['launcher'][pos+1:]
186 self.CMD+=["NameService=corbaname::" + machine + ":" + port]
191 class RegistryServer(Server):
192 def __init__(self,args):
195 self.CMD=['SALOME_Registry_Server', '--salome_session','theSession']
199 class ContainerCPPServer(Server):
200 def __init__(self,args,with_gui=False):
203 self.CMD=['SALOME_Container','FactoryServer']
204 if not with_gui and self.args["valgrind_session"]:
206 val = os.getenv("VALGRIND_OPTIONS")
210 self.CMD = l + self.CMD
215 class LoggerServer(Server):
216 def __init__(self,args):
219 from salome_utils import generateFileName, getLogDir
220 logfile = generateFileName( getLogDir(),
226 print("===========================================================")
227 print("Logger server: put log to the file:")
229 print("===========================================================")
230 self.CMD=['SALOME_Logger_Server', logfile]
232 pass # end of LoggerServer class
236 class SessionServer(Server):
237 def __init__(self,args,modules_list,modules_root_dir):
238 self.args = args.copy()
239 # Bug 11512 (Problems with runSalome --xterm on Mandrake and Debian Sarge)
240 #self.args['xterm']=0
243 self.SCMD1=['SALOME_Session_Server']
245 if 'launcher' in self.args:
246 pos = args['launcher'].find(":")
248 self.SCMD1+=['-ORBInitRef']
249 machine = args['launcher'][0:pos]
250 port = args['launcher'][pos+1:]
251 self.SCMD1+=["NameService=corbaname::" + machine + ":" + port]
252 if 'registry' in self.args['embedded']:
253 self.SCMD1+=['--with','Registry',
254 '(','--salome_session','theSession',')']
255 if 'moduleCatalog' in self.args['embedded']:
256 self.SCMD1+=['--with','ModuleCatalog','(','-common']
257 home_dir=os.getenv('HOME')
258 if home_dir is not None:
259 self.SCMD2+=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')]
261 if 'study' in self.args['embedded']:
262 self.SCMD2+=['--with','SALOMEDS','(',')']
263 if 'cppContainer' in self.args['embedded']:
264 self.SCMD2+=['--with','Container','(','FactoryServer',')']
265 if 'SalomeAppEngine' in self.args['embedded']:
266 self.SCMD2+=['--with','SalomeAppEngine','(',')']
268 if 'cppContainer' in self.args['standalone'] or 'cppContainer' in self.args['embedded']:
270 if 'pyContainer' in self.args['standalone'] or 'pyContainer' in self.args['embedded']:
271 raise Exception('Python containers no longer supported')
274 if 'session_gui' in self.args:
275 session_gui = self.args['session_gui']
278 if self.args['splash']:
279 self.SCMD2+=['SPLASH']
281 if self.args['study_hdf'] is not None:
282 self.SCMD2+=['--study-hdf=%s'%self.args['study_hdf']]
285 if 'pyscript' in self.args and len(self.args['pyscript']) > 0:
286 msg = json.dumps(self.args['pyscript'], cls=ScriptAndArgsObjectEncoder)
287 self.SCMD2+=['--pyscript=%s'%(msg)]
291 if self.args['noexcepthandler']:
292 self.SCMD2+=['noexcepthandler']
293 if 'user_config' in self.args:
294 self.SCMD2+=['--resources=%s'%self.args['user_config']]
295 if 'modules' in self.args:
297 #keep only modules with GUI
298 for m in modules_list:
299 if m not in modules_root_dir:
300 list_modules.insert(0,m)
302 fr1 = os.path.join(modules_root_dir[m],"share","salome","resources",m.lower(),"SalomeApp.xml")
303 fr2 = os.path.join(modules_root_dir[m],"share","salome","resources","SalomeApp.xml")
304 if os.path.exists(fr1) or os.path.exists(fr2):
305 list_modules.insert(0,m)
306 list_modules.reverse()
307 self.SCMD2+=['--modules (%s)' % ":".join(list_modules)]
309 if 'language' in self.args:
310 self.SCMD2+=['--language=%s' % self.args['language']]
313 def setpath(self,modules_list,modules_root_dir):
314 list_modules = modules_list[:]
315 list_modules.reverse()
316 if self.args["gui"] :
317 list_modules = ["KERNEL", "GUI"] + list_modules
319 list_modules = ["KERNEL"] + list_modules
321 cata_path=get_cata_path(list_modules,modules_root_dir)
323 if ("gui" in self.args) & ('moduleCatalog' in self.args['embedded']):
324 #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
325 self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
327 self.CMD=self.SCMD1 + self.SCMD2
328 if 'test' in self.args:
329 self.CMD+=['-test'] + self.args['test']
330 elif 'play' in self.args:
331 self.CMD+=['-play'] + self.args['play']
333 if self.args["gdb_session"] or self.args["ddd_session"]:
334 f = open(".gdbinit4salome", "w")
336 args = " ".join(self.CMD[1:])
337 args = args.replace("(", "\(")
338 args = args.replace(")", "\)")
342 if self.args["ddd_session"]:
343 self.CMD = ["ddd", "--command=.gdbinit4salome", self.CMD[0]]
344 elif self.args["gdb_session"]:
345 self.CMD = ["xterm", "-e", "gdb", "--command=.gdbinit4salome", self.CMD[0]]
349 if self.args["valgrind_session"]:
351 val = os.getenv("VALGRIND_OPTIONS")
355 self.CMD = l + self.CMD
360 class LauncherServer(Server):
361 def __init__(self,args):
364 self.SCMD1=['SALOME_LauncherServer']
367 if 'registry' in self.args['embedded']:
368 self.SCMD1+=['--with','Registry',
369 '(','--salome_session','theSession',')']
370 if 'moduleCatalog' in self.args['embedded']:
371 self.SCMD1+=['--with','ModuleCatalog','(','-common']
372 self.SCMD2+=['-personal',
373 '${HOME}/Salome/resources/CatalogModulePersonnel.xml',')']
374 if 'study' in self.args['embedded']:
375 self.SCMD2+=['--with','SALOMEDS','(',')']
376 if 'cppContainer' in self.args['embedded']:
377 self.SCMD2+=['--with','Container','(','FactoryServer',')']
379 def setpath(self,modules_list,modules_root_dir):
380 list_modules = modules_list[:]
381 list_modules.reverse()
382 if self.args["gui"] :
383 list_modules = ["KERNEL", "GUI"] + list_modules
385 list_modules = ["KERNEL"] + list_modules
387 cata_path=get_cata_path(list_modules,modules_root_dir)
389 if ("gui" in self.args) & ('moduleCatalog' in self.args['embedded']):
390 #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
391 self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
393 self.CMD=self.SCMD1 + self.SCMD2
395 # -----------------------------------------------------------------------------
398 """Salome Session Graphic User Interface activation"""
402 import SALOME_ModuleCatalog
403 import SALOME_Session_idl
404 session=clt.waitNS("/Kernel/Session",SALOME.Session)
405 session.GetInterface()
407 # -----------------------------------------------------------------------------
409 def startSalome(args, modules_list, modules_root_dir):
410 """Launch all SALOME servers requested by args"""
411 init_time = os.times()
413 if verbose(): print("startSalome ", args)
416 # Set server launch command
418 if 'server_launch_mode' in args:
419 Server.set_server_launch_mode(args['server_launch_mode'])
422 # Wake up session option
424 if args['wake_up_session']:
425 if "OMNIORB_CONFIG" not in os.environ:
426 from salome_utils import generateFileName
427 omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
429 if omniorbUserPath is not None:
430 kwargs["with_username"]=True
432 last_running_config = generateFileName(omniorbUserPath, prefix="omniORB",
437 os.environ['OMNIORB_CONFIG'] = last_running_config
442 # Initialisation ORB and Naming Service
445 clt=orbmodule.client(args)
448 # Wake up session option
450 if args['wake_up_session']:
454 import SALOME_ModuleCatalog
455 import SALOME_Session_idl
456 session = clt.waitNS("/Kernel/Session",SALOME.Session)
457 status = session.GetStatSession()
459 from salome_utils import getPortNumber
460 port = getPortNumber()
463 msg += "Session GUI for port number %s is already active."%(port)
465 msg += "If you which to wake up another session,"
467 msg += "please use variable OMNIORB_CONFIG"
469 msg += "to get the correct session object in naming service."
470 sys.stdout.write(msg+"\n")
473 session.GetInterface()
474 args["session_object"] = session
477 # Launch Logger Server (optional)
478 # and wait until it is registered in naming service
482 myServer=LoggerServer(args)
484 clt.waitLogger("Logger")
486 # Launch Session Server (to show splash ASAP)
489 if args["gui"] and not args['launcher_only']:
490 mySessionServ = SessionServer(args,args['modules'],modules_root_dir)
491 mySessionServ.setpath(modules_list,modules_root_dir)
495 # Launch Registry Server,
496 # and wait until it is registered in naming service
499 if ('registry' not in args['embedded']) | (args["gui"] == 0) :
500 myServer=RegistryServer(args)
502 if sys.platform == "win32":
503 clt.waitNS("/Registry")
505 clt.waitNSPID("/Registry",myServer.PID)
508 # Launch Catalog Server,
509 # and wait until it is registered in naming service
512 if ('moduleCatalog' not in args['embedded']) | (args["gui"] == 0):
513 cataServer=CatalogServer(args)
514 cataServer.setpath(modules_list,modules_root_dir)
516 import SALOME_ModuleCatalog
517 if sys.platform == "win32":
518 clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
520 clt.waitNSPID("/Kernel/ModulCatalog",cataServer.PID,SALOME_ModuleCatalog.ModuleCatalog)
523 # Launch SalomeDS Server,
524 # and wait until it is registered in naming service
527 # print("ARGS = ",args)
528 if ('study' not in args['embedded']) | (args["gui"] == 0):
530 myServer=SalomeDSServer(args)
532 if sys.platform == "win32":
535 clt.waitNSPID("/Study",myServer.PID)
538 # Launch LauncherServer
541 if not 'launcher' in args:
542 myCmServer = LauncherServer(args)
543 myCmServer.setpath(modules_list,modules_root_dir)
547 # Launch ConnectionManagerServer
550 if not args['launcher_only']:
551 myConnectionServer = ConnectionManagerServer(args)
552 myConnectionServer.run()
554 from Utils_Identity import getShortHostName
556 if os.getenv("HOSTNAME") == None:
557 if os.getenv("HOST") == None:
558 os.environ["HOSTNAME"]=getShortHostName()
560 os.environ["HOSTNAME"]=os.getenv("HOST")
562 theComputer = getShortHostName()
565 # Launch local C++ Container (FactoryServer),
566 # and wait until it is registered in naming service
569 if ('cppContainer' in args['standalone']) | (args["gui"] == 0) :
570 myServer=ContainerCPPServer(args, with_gui=args["gui"]!=0)
572 if sys.platform == "win32":
573 clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
575 clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID)
577 if 'pyContainer' in args['standalone']:
578 raise Exception('Python containers no longer supported')
581 # Wait until Session Server is registered in naming service
584 if args["gui"] and not args['launcher_only']:
589 import SALOME_ModuleCatalog
590 import SALOME_Session_idl
591 if sys.platform == "win32":
592 session=clt.waitNS("/Kernel/Session",SALOME.Session)
594 session=clt.waitNSPID("/Kernel/Session",mySessionServ.PID,SALOME.Session)
595 args["session_object"] = session
596 end_time = os.times()
597 if verbose(): print()
598 print("Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
601 # ASV start GUI without Loader
603 # session.GetInterface()
606 # additional external python interpreters
612 nbaddi = args['interp']
615 traceback.print_exc()
616 print("-------------------------------------------------------------")
617 print("-- to get an external python interpreter:runSalome --interp=1")
618 print("-------------------------------------------------------------")
620 if verbose(): print("additional external python interpreters: ", nbaddi)
622 for i in range(nbaddi):
624 anInterp=InterpServer(args)
627 # set PYTHONINSPECT variable (python interpreter in interactive mode)
629 os.environ["PYTHONINSPECT"]="1"
637 # -----------------------------------------------------------------------------
639 def useSalome(args, modules_list, modules_root_dir):
641 Launch all SALOME servers requested by args,
642 save list of process, give info to user,
643 show registered objects in Naming Service.
649 clt = startSalome(args, modules_list, modules_root_dir)
652 traceback.print_exc()
655 print("--- Error during Salome launch ---")
659 from addToKillList import addToKillList
660 from killSalomeWithPort import getPiDict
662 filedict = getPiDict(args['port'])
663 for pid, cmd in list(process_id.items()):
664 addToKillList(pid, cmd, args['port'])
667 if verbose(): print("""
668 Saving of the dictionary of Salome processes in %s
669 To kill SALOME processes from a console (kill all sessions from all ports):
671 To kill SALOME from the present interpreter, if it is not closed :
672 killLocalPort() --> kill this session
673 (use CORBA port from args of runSalome)
674 givenPortKill(port) --> kill a specific session with given CORBA port
675 killAllPorts() --> kill all sessions
677 runSalome, with --killall option, starts with killing
678 the processes resulting from the previous execution.
682 # Print Naming Service directory list
688 print(" --- registered objects tree in Naming Service ---")
692 if not args['gui'] or not args['session_gui']:
693 if args['shutdown_servers']:
694 class __utils__(object):
695 def __init__(self, port):
697 import killSalomeWithPort
698 self.killSalomeWithPort = killSalomeWithPort
701 self.killSalomeWithPort.killMyPort(self.port)
707 atexit.register(func, __utils__(args['port']))
711 # run python scripts, passed as command line arguments
713 if 'gui' in args and 'session_gui' in args:
714 if not args['gui'] or not args['session_gui']:
715 if 'study_hdf' in args:
716 toopen = args['study_hdf']
719 salome.salome_init(path=toopen)
720 if 'pyscript' in args:
721 toimport = args['pyscript']
722 from salomeContextUtils import formatScriptsAndArgs
723 command = formatScriptsAndArgs(toimport)
725 proc = subprocess.Popen(command, shell=True)
726 addToKillList(proc.pid, command, args['port'])
728 if res: sys.exit(1) # if there's an error when executing script, we should explicitly exit
732 def execScript(script_path):
733 print('executing', script_path)
734 sys.path.insert(0, os.path.realpath(os.path.dirname(script_path)))
735 exec(compile(open(script_path).read(), script_path, 'exec'),globals())
738 # -----------------------------------------------------------------------------
740 def registerEnv(args, modules_list, modules_root_dir):
742 Register args, modules_list, modules_root_dir in a file
743 for further use, when SALOME is launched embedded in an other application.
745 from salome_utils import getTmpDir
746 fileEnv = getTmpDir()
747 from salome_utils import getUserName
748 fileEnv += getUserName() + "_" + str(args['port']) \
749 + '_' + args['appname'].upper() + '_env'
750 fenv=open(fileEnv,'w')
751 pickle.dump((args, modules_list, modules_root_dir),fenv)
753 os.environ["SALOME_LAUNCH_CONFIG"] = fileEnv
755 # -----------------------------------------------------------------------------
758 """Salome Launch, when embedded in other application"""
759 fileEnv = os.environ["SALOME_LAUNCH_CONFIG"]
760 fenv=open(fileEnv,'r')
761 args, modules_list, modules_root_dir = pickle.load(fenv)
764 from searchFreePort import searchFreePort
765 searchFreePort(args, 0)
766 clt = useSalome(args, modules_list, modules_root_dir)
769 # -----------------------------------------------------------------------------
771 def main(exeName=None):
772 """Salome launch as a main application"""
774 # define folder to store omniorb config (initially in virtual application folder)
776 from salomeContextUtils import setOmniOrbUserPath
778 except Exception as e:
782 from salome_utils import getHostName
783 args, modules_list, modules_root_dir = setenv.get_config(exeName=exeName)
784 print("runSalome running on %s" % getHostName())
788 if 'save_config' in args:
789 save_config = args['save_config']
792 if args['wake_up_session']:
795 if test and not 'launcher' in args:
796 from searchFreePort import searchFreePort
797 searchFreePort(args, save_config, args.get('useport'))
801 setenv.set_env(args, modules_list, modules_root_dir)
802 clt = useSalome(args, modules_list, modules_root_dir)
805 # -----------------------------------------------------------------------------
807 def foreGround(clt, args):
809 if "session_object" not in args:
811 session = args["session_object"]
813 # Wait until gui is arrived
822 status = session.GetStatSession()
823 gui_detected = status.activeGUI
828 from time import sleep
838 from salome_utils import getPortNumber
839 port = getPortNumber()
842 if sys.platform == "win32":
843 server.CMD = [os.getenv("PYTHONBIN"), "-m", "killSalomeWithPort", "--spy", "%s"%(os.getpid()), "%s"%(port)]
845 server.CMD = ["killSalomeWithPort.py", "--spy", "%s"%(os.getpid()), "%s"%(port)]
847 # os.system("killSalomeWithPort.py --spy %s %s &"%(os.getpid(), port))
853 status = session.GetStatSession()
854 assert status.activeGUI
857 from time import sleep
861 except KeyboardInterrupt:
862 from killSalomeWithPort import killMyPort
871 test = args['gui'] and args['session_gui']
872 test = test or args['wake_up_session']
874 # The next test covers the --pinter option or if var PYTHONINSPECT is set
876 test = test and not os.environ.get('PYTHONINSPECT')
878 # The next test covers the python -i $KERNEL_ROOT_DIR/bin/salome/runSalome.py case
881 from ctypes import POINTER, c_int, cast, pythonapi
882 iflag_ptr = cast(pythonapi.Py_InteractiveFlag, POINTER(c_int))
883 test = test and not iflag_ptr.contents.value
887 test = test and os.getenv("SALOME_TEST_MODE", "0") != "1"
888 test = test and args['foreground']
891 foreGround(clt, args)
896 # -----------------------------------------------------------------------------
898 if __name__ == "__main__":