2 # -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2012 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.
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
35 if sys.platform == "win32":
40 # -----------------------------------------------------------------------------
42 from killSalome import killAllPorts
46 kill servers from a previous SALOME exection, if needed,
47 on the CORBA port given in args of runSalome
50 from killSalomeWithPort import killMyPort
51 my_port=str(args['port'])
55 print "problem in killLocalPort()"
59 def givenPortKill(port):
61 kill servers from a previous SALOME exection, if needed,
62 on the same CORBA port
65 from killSalomeWithPort import killMyPort
70 print "problem in LocalPortKill(), killMyPort("<<port<<")"
74 def kill_salome(args):
76 Kill servers from previous SALOME executions, if needed;
77 depending on args 'killall' or 'portkill', kill all executions,
78 or only execution on the same CORBA port
83 elif args['portkill']:
84 givenPortKill(str(args['port']))
86 # -----------------------------------------------------------------------------
88 # Class definitions to launch CORBA Servers
91 class InterpServer(Server):
92 def __init__(self,args):
94 if sys.platform != "win32":
95 env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
96 self.CMD=['xterm', '-e']+ env_ld_library_path + ['python']
98 self.CMD=['cmd', '/c', 'start cmd.exe', '/K', 'python']
103 print "INTERPSERVER::command = ", command
104 if sys.platform == "win32":
106 pid = win32pm.spawnpid( string.join(command, " "),'-nc' )
108 pid = os.spawnvp(os.P_NOWAIT, command[0], command)
109 process_id[pid]=self.CMD
114 def get_cata_path(list_modules,modules_root_dir):
115 """Build a list of catalog paths (cata_path) to initialize the ModuleCatalog server
120 for module in list_modules:
121 if modules_root_dir.has_key(module):
122 module_root_dir=modules_root_dir[module]
123 module_cata=module+"Catalog.xml"
124 cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources",module.lower(), module_cata)
126 if os.path.exists(cata_file):
127 cata_path.append(cata_file)
128 modules_cata[module]=cata_file
130 cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources", module_cata)
131 if os.path.exists(cata_file):
132 cata_path.append(cata_file)
133 modules_cata[module]=cata_file
135 for path in os.getenv("SALOME_CATALOGS_PATH","").split(SEP):
136 if os.path.exists(path):
137 for cata_file in glob.glob(os.path.join(path,"*Catalog.xml")):
138 module_name= os.path.basename(cata_file)[:-11]
139 if not modules_cata.has_key(module_name):
140 cata_path.append(cata_file)
141 modules_cata[module_name]=cata_file
147 class CatalogServer(Server):
148 def __init__(self,args):
151 self.SCMD1=['SALOME_ModuleCatalog_Server','-common']
153 home_dir=os.getenv('HOME')
154 if home_dir is not None:
155 self.SCMD2=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')]
157 def setpath(self,modules_list,modules_root_dir):
158 list_modules = modules_list[:]
159 list_modules.reverse()
160 if self.args["gui"] :
161 list_modules = ["KERNEL", "GUI"] + list_modules
163 list_modules = ["KERNEL"] + list_modules
165 cata_path=get_cata_path(list_modules,modules_root_dir)
167 self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
171 class SalomeDSServer(Server):
172 def __init__(self,args):
175 self.CMD=['SALOMEDS_Server']
179 class ConnectionManagerServer(Server):
180 def __init__(self,args):
183 self.CMD=['SALOME_ConnectionManagerServer']
187 class RegistryServer(Server):
188 def __init__(self,args):
191 self.CMD=['SALOME_Registry_Server', '--salome_session','theSession']
195 class ContainerCPPServer(Server):
196 def __init__(self,args):
199 self.CMD=['SALOME_Container','FactoryServer']
203 class ContainerPYServer(Server):
204 def __init__(self,args):
207 if sys.platform == "win32":
208 self.CMD=[os.environ["PYTHONBIN"], '\"'+os.environ["KERNEL_ROOT_DIR"] + '/bin/salome/SALOME_ContainerPy.py'+'\"','FactoryServerPy']
210 self.CMD=['SALOME_ContainerPy.py','FactoryServerPy']
214 class LoggerServer(Server):
215 def __init__(self,args):
218 from salome_utils import generateFileName
219 if sys.platform == "win32": dirpath = os.environ["HOME"]
220 else: dirpath = "/tmp"
221 logfile = generateFileName( dirpath,
227 print "==========================================================="
228 print "Logger server: put log to the file:"
230 print "==========================================================="
231 self.CMD=['SALOME_Logger_Server', logfile]
233 pass # end of LoggerServer class
237 class SessionServer(Server):
238 def __init__(self,args,modules_list,modules_root_dir):
239 self.args = args.copy()
240 # Bug 11512 (Problems with runSalome --xterm on Mandrake and Debian Sarge)
241 #self.args['xterm']=0
244 self.SCMD1=['SALOME_Session_Server']
246 if 'registry' in self.args['embedded']:
247 self.SCMD1+=['--with','Registry',
248 '(','--salome_session','theSession',')']
249 if 'moduleCatalog' in self.args['embedded']:
250 self.SCMD1+=['--with','ModuleCatalog','(','-common']
251 home_dir=os.getenv('HOME')
252 if home_dir is not None:
253 self.SCMD2+=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')]
255 if 'study' in self.args['embedded']:
256 self.SCMD2+=['--with','SALOMEDS','(',')']
257 if 'cppContainer' in self.args['embedded']:
258 self.SCMD2+=['--with','Container','(','FactoryServer',')']
259 if 'SalomeAppEngine' in self.args['embedded']:
260 self.SCMD2+=['--with','SalomeAppEngine','(',')']
262 if 'cppContainer' in self.args['standalone'] or 'cppContainer' in self.args['embedded']:
264 if 'pyContainer' in self.args['standalone'] or 'pyContainer' in self.args['embedded']:
268 if self.args.has_key('session_gui'):
269 session_gui = self.args['session_gui']
272 if self.args['splash']:
273 self.SCMD2+=['SPLASH']
275 if self.args['study_hdf'] is not None:
276 self.SCMD2+=['--study-hdf=%s'%self.args['study_hdf']]
279 if self.args.has_key('pyscript') and len(self.args['pyscript']) > 0:
280 self.SCMD2+=['--pyscript=%s'%(",".join(self.args['pyscript']))]
284 if self.args['noexcepthandler']:
285 self.SCMD2+=['noexcepthandler']
286 if self.args.has_key('user_config'):
287 self.SCMD2+=['--resources=%s'%self.args['user_config']]
288 if self.args.has_key('modules'):
290 #keep only modules with GUI
291 for m in modules_list:
292 if m not in modules_root_dir:
293 list_modules.insert(0,m)
295 fr1 = os.path.join(modules_root_dir[m],"share","salome","resources",m.lower(),"SalomeApp.xml")
296 fr2 = os.path.join(modules_root_dir[m],"share","salome","resources","SalomeApp.xml")
297 if os.path.exists(fr1) or os.path.exists(fr2):
298 list_modules.insert(0,m)
299 list_modules.reverse()
300 self.SCMD2+=['--modules (%s)' % ":".join(list_modules)]
304 def setpath(self,modules_list,modules_root_dir):
305 list_modules = modules_list[:]
306 list_modules.reverse()
307 if self.args["gui"] :
308 list_modules = ["KERNEL", "GUI"] + list_modules
310 list_modules = ["KERNEL"] + list_modules
312 cata_path=get_cata_path(list_modules,modules_root_dir)
314 if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
315 #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
316 self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
318 self.CMD=self.SCMD1 + self.SCMD2
319 if self.args.has_key('test'):
320 self.CMD+=['-test'] + self.args['test']
321 elif self.args.has_key('play'):
322 self.CMD+=['-play'] + self.args['play']
324 if self.args["gdb_session"] or self.args["ddd_session"]:
325 f = open(".gdbinit4salome", "w")
327 args = " ".join(self.CMD[1:])
328 args = args.replace("(", "\(")
329 args = args.replace(")", "\)")
333 if self.args["ddd_session"]:
334 self.CMD = ["ddd", "--command=.gdbinit4salome", self.CMD[0]]
335 elif self.args["gdb_session"]:
336 self.CMD = ["xterm", "-e", "gdb", "--command=.gdbinit4salome", self.CMD[0]]
340 if self.args["valgrind_session"]:
342 val = os.getenv("VALGRIND_OPTIONS")
346 self.CMD = l + self.CMD
351 class LauncherServer(Server):
352 def __init__(self,args):
355 self.SCMD1=['SALOME_LauncherServer']
358 if 'registry' in self.args['embedded']:
359 self.SCMD1+=['--with','Registry',
360 '(','--salome_session','theSession',')']
361 if 'moduleCatalog' in self.args['embedded']:
362 self.SCMD1+=['--with','ModuleCatalog','(','-common']
363 self.SCMD2+=['-personal',
364 '${HOME}/Salome/resources/CatalogModulePersonnel.xml',')']
365 if 'study' in self.args['embedded']:
366 self.SCMD2+=['--with','SALOMEDS','(',')']
367 if 'cppContainer' in self.args['embedded']:
368 self.SCMD2+=['--with','Container','(','FactoryServer',')']
370 def setpath(self,modules_list,modules_root_dir):
371 list_modules = modules_list[:]
372 list_modules.reverse()
373 if self.args["gui"] :
374 list_modules = ["KERNEL", "GUI"] + list_modules
376 list_modules = ["KERNEL"] + list_modules
378 cata_path=get_cata_path(list_modules,modules_root_dir)
380 if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
381 #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
382 self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
384 self.CMD=self.SCMD1 + self.SCMD2
386 class NotifyServer(Server):
387 def __init__(self,args,modules_root_dir):
390 self.modules_root_dir=modules_root_dir
391 myLogName = os.environ["LOGNAME"]
392 self.CMD=['notifd','-c',
393 self.modules_root_dir["KERNEL"] +'/share/salome/resources/kernel/channel.cfg',
394 '-DFactoryIORFileName=/tmp/'+myLogName+'_rdifact.ior',
395 '-DChannelIORFileName=/tmp/'+myLogName+'_rdichan.ior',
396 '-DReportLogFile=/tmp/'+myLogName+'_notifd.report',
397 '-DDebugLogFile=/tmp/'+myLogName+'_notifd.debug',
401 # -----------------------------------------------------------------------------
404 """Salome Session Graphic User Interface activation"""
408 import SALOME_ModuleCatalog
409 import SALOME_Session_idl
410 session=clt.waitNS("/Kernel/Session",SALOME.Session)
411 session.GetInterface()
413 # -----------------------------------------------------------------------------
415 def startSalome(args, modules_list, modules_root_dir):
416 """Launch all SALOME servers requested by args"""
417 init_time = os.times()
419 if verbose(): print "startSalome ", args
422 # Set server launch command
424 if args.has_key('server_launch_mode'):
425 Server.set_server_launch_mode(args['server_launch_mode'])
428 # Wake up session option
430 if args['wake_up_session']:
431 if "OMNIORB_CONFIG" not in os.environ:
432 from salome_utils import generateFileName
433 home = os.getenv("HOME")
434 appli = os.getenv("APPLI")
436 if appli is not None:
437 home = os.path.join(os.path.realpath(home), appli,"USERS")
438 kwargs["with_username"] = True
440 last_running_config = generateFileName(home, prefix="omniORB",
445 os.environ['OMNIORB_CONFIG'] = last_running_config
450 # Initialisation ORB and Naming Service
453 clt=orbmodule.client(args)
456 # Wake up session option
458 if args['wake_up_session']:
462 import SALOME_ModuleCatalog
463 import SALOME_Session_idl
464 session = clt.waitNS("/Kernel/Session",SALOME.Session)
465 status = session.GetStatSession()
467 from salome_utils import getPortNumber
468 port = getPortNumber()
471 msg += "Session GUI for port number %s is already active."%(port)
473 msg += "If you which to wake up another session,"
475 msg += "please use variable OMNIORB_CONFIG"
477 msg += "to get the correct session object in naming service."
478 sys.stdout.write(msg+"\n")
481 session.GetInterface()
482 args["session_object"] = session
485 # Save Naming service port name into
486 # the file args["ns_port_log_file"]
487 if args.has_key('ns_port_log_file'):
488 home = os.environ['HOME']
489 appli= os.environ.get("APPLI")
490 if appli is not None:
491 home = os.path.join(os.path.realpath(home), appli, "USERS")
492 file_name = os.path.join(home, args["ns_port_log_file"])
493 f = open(file_name, "w")
494 f.write(os.environ['NSPORT'])
497 # Launch Logger Server (optional)
498 # and wait until it is registered in naming service
502 myServer=LoggerServer(args)
504 clt.waitLogger("Logger")
506 # Notify Server launch
509 if sys.platform != "win32":
510 if verbose(): print "Notify Server to launch"
512 myServer=NotifyServer(args,modules_root_dir)
515 # Launch Session Server (to show splash ASAP)
519 mySessionServ = SessionServer(args,args['modules'],modules_root_dir)
520 mySessionServ.setpath(modules_list,modules_root_dir)
524 # Launch Registry Server,
525 # and wait until it is registered in naming service
528 if ('registry' not in args['embedded']) | (args["gui"] == 0) :
529 myServer=RegistryServer(args)
531 if sys.platform == "win32":
532 clt.waitNS("/Registry")
534 clt.waitNSPID("/Registry",myServer.PID)
537 # Launch Catalog Server,
538 # and wait until it is registered in naming service
541 if ('moduleCatalog' not in args['embedded']) | (args["gui"] == 0):
542 cataServer=CatalogServer(args)
543 cataServer.setpath(modules_list,modules_root_dir)
545 import SALOME_ModuleCatalog
546 if sys.platform == "win32":
547 clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
549 clt.waitNSPID("/Kernel/ModulCatalog",cataServer.PID,SALOME_ModuleCatalog.ModuleCatalog)
552 # Launch SalomeDS Server,
553 # and wait until it is registered in naming service
556 #print "ARGS = ",args
557 if ('study' not in args['embedded']) | (args["gui"] == 0):
559 myServer=SalomeDSServer(args)
561 if sys.platform == "win32":
562 clt.waitNS("/myStudyManager")
564 clt.waitNSPID("/myStudyManager",myServer.PID)
567 # Launch LauncherServer
570 myCmServer = LauncherServer(args)
571 myCmServer.setpath(modules_list,modules_root_dir)
575 # Launch ConnectionManagerServer
578 myConnectionServer = ConnectionManagerServer(args)
579 myConnectionServer.run()
582 from Utils_Identity import getShortHostName
584 if os.getenv("HOSTNAME") == None:
585 if os.getenv("HOST") == None:
586 os.environ["HOSTNAME"]=getShortHostName()
588 os.environ["HOSTNAME"]=os.getenv("HOST")
590 theComputer = getShortHostName()
593 # Launch local C++ Container (FactoryServer),
594 # and wait until it is registered in naming service
597 if ('cppContainer' in args['standalone']) | (args["gui"] == 0) :
598 myServer=ContainerCPPServer(args)
600 if sys.platform == "win32":
601 clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
603 clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID)
606 # Launch local Python Container (FactoryServerPy),
607 # and wait until it is registered in naming service
610 if 'pyContainer' in args['standalone']:
611 myServer=ContainerPYServer(args)
613 if sys.platform == "win32":
614 clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy")
616 clt.waitNSPID("/Containers/" + theComputer + "/FactoryServerPy",myServer.PID)
619 # Wait until Session Server is registered in naming service
627 import SALOME_ModuleCatalog
628 import SALOME_Session_idl
629 if sys.platform == "win32":
630 session=clt.waitNS("/Kernel/Session",SALOME.Session)
632 session=clt.waitNSPID("/Kernel/Session",mySessionServ.PID,SALOME.Session)
633 args["session_object"] = session
634 end_time = os.times()
636 print "Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
639 # ASV start GUI without Loader
641 # session.GetInterface()
644 # additionnal external python interpreters
650 nbaddi = args['interp']
653 traceback.print_exc()
654 print "-------------------------------------------------------------"
655 print "-- to get an external python interpreter:runSalome --interp=1"
656 print "-------------------------------------------------------------"
658 if verbose(): print "additional external python interpreters: ", nbaddi
660 for i in range(nbaddi):
662 anInterp=InterpServer(args)
665 # set PYTHONINSPECT variable (python interpreter in interactive mode)
667 os.environ["PYTHONINSPECT"]="1"
675 # -----------------------------------------------------------------------------
677 def useSalome(args, modules_list, modules_root_dir):
679 Launch all SALOME servers requested by args,
680 save list of process, give info to user,
681 show registered objects in Naming Service.
687 clt = startSalome(args, modules_list, modules_root_dir)
690 traceback.print_exc()
693 print "--- Error during Salome launch ---"
697 from addToKillList import addToKillList
698 from killSalomeWithPort import getPiDict
700 filedict = getPiDict(args['port'])
701 for pid, cmd in process_id.items():
702 addToKillList(pid, cmd, args['port'])
705 if verbose(): print """
706 Saving of the dictionary of Salome processes in %s
707 To kill SALOME processes from a console (kill all sessions from all ports):
709 To kill SALOME from the present interpreter, if it is not closed :
710 killLocalPort() --> kill this session
711 (use CORBA port from args of runSalome)
712 givenPortKill(port) --> kill a specific session with given CORBA port
713 killAllPorts() --> kill all sessions
715 runSalome, with --killall option, starts with killing
716 the processes resulting from the previous execution.
720 # Print Naming Service directory list
726 print " --- registered objects tree in Naming Service ---"
730 if not args['gui'] or not args['session_gui']:
731 if args['shutdown_servers']:
732 class __utils__(object):
733 def __init__(self, port):
735 import killSalomeWithPort
736 self.killSalomeWithPort = killSalomeWithPort
739 self.killSalomeWithPort.killMyPort(self.port)
742 args['shutdown_servers'] = __utils__(args['port'])
746 # run python scripts, passed via --execute option
748 if args.has_key('pyscript'):
749 if args.has_key('gui') and args.has_key('session_gui'):
750 if not args['gui'] or not args['session_gui']:
751 toimport = args['pyscript']
753 for srcname in toimport :
754 if srcname == 'killall':
759 if os.path.isabs(srcname):
760 if os.path.exists(srcname):
762 elif os.path.exists(srcname+".py"):
763 execScript(srcname+".py")
765 print "Can't execute file %s" % srcname
769 for path in [os.getcwd()] + sys.path:
770 if os.path.exists(os.path.join(path,srcname)):
771 execScript(os.path.join(path,srcname))
774 elif os.path.exists(os.path.join(path,srcname+".py")):
775 execScript(os.path.join(path,srcname+".py"))
780 print "Can't execute file %s" % srcname
788 def execScript(script_path):
789 print 'executing', script_path
790 sys.path.insert(0, os.path.dirname(script_path))
791 execfile(script_path,globals())
794 # -----------------------------------------------------------------------------
796 def registerEnv(args, modules_list, modules_root_dir):
798 Register args, modules_list, modules_root_dir in a file
799 for further use, when SALOME is launched embedded in an other application.
801 if sys.platform == "win32":
802 fileEnv = os.getenv('TEMP')
806 fileEnv += os.getenv('USER') + "_" + str(args['port']) \
807 + '_' + args['appname'].upper() + '_env'
808 fenv=open(fileEnv,'w')
809 pickle.dump((args, modules_list, modules_root_dir),fenv)
811 os.environ["SALOME_LAUNCH_CONFIG"] = fileEnv
813 # -----------------------------------------------------------------------------
816 """Salome Launch, when embedded in other application"""
817 fileEnv = os.environ["SALOME_LAUNCH_CONFIG"]
818 fenv=open(fileEnv,'r')
819 args, modules_list, modules_root_dir = pickle.load(fenv)
822 from searchFreePort import searchFreePort
823 searchFreePort(args, 0)
824 clt = useSalome(args, modules_list, modules_root_dir)
827 # -----------------------------------------------------------------------------
830 """Salome launch as a main application"""
831 from salome_utils import getHostName
832 print "runSalome running on %s" % getHostName()
833 args, modules_list, modules_root_dir = setenv.get_config()
837 if args.has_key('save_config'):
838 save_config = args['save_config']
841 if args['wake_up_session']:
845 from searchFreePort import searchFreePort
846 searchFreePort(args, save_config)
850 setenv.set_env(args, modules_list, modules_root_dir)
851 clt = useSalome(args, modules_list, modules_root_dir)
854 # -----------------------------------------------------------------------------
856 def foreGround(clt, args):
858 if "session_object" not in args:
860 session = args["session_object"]
862 # Wait until gui is arrived
871 status = session.GetStatSession()
872 gui_detected = status.activeGUI
877 from time import sleep
887 from salome_utils import getPortNumber
888 port = getPortNumber()
891 if sys.platform == "win32":
892 server.CMD = [os.getenv("PYTHONBIN"), "-m", "killSalomeWithPort", "--spy", "%s"%(os.getpid()), "%s"%(port)]
894 server.CMD = ["killSalomeWithPort.py", "--spy", "%s"%(os.getpid()), "%s"%(port)]
896 # os.system("killSalomeWithPort.py --spy %s %s &"%(os.getpid(), port))
902 status = session.GetStatSession()
903 assert status.activeGUI
906 from time import sleep
910 except KeyboardInterrupt:
911 from killSalomeWithPort import killMyPort
916 # -----------------------------------------------------------------------------
918 if __name__ == "__main__":
922 test = args['gui'] and args['session_gui']
923 test = test or args['wake_up_session']
925 # The next test covers the --pinter option or var PYTHONINSPECT setted
927 test = test and not os.environ.get('PYTHONINSPECT')
929 # The next test covers the python -i $KERNEL_ROOT_DIR/bin/salome/runSalome.py case
932 from ctypes import POINTER, c_int, cast, pythonapi
933 iflag_ptr = cast(pythonapi.Py_InteractiveFlag, POINTER(c_int))
934 test = test and not iflag_ptr.contents.value
938 test = test and os.getenv("SALOME_TEST_MODE", "0") != "1"
939 test = test and args['foreground']
942 foreGround(clt, args)