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 # -----------------------------------------------------------------------------
37 from killSalome import killAllPorts
41 kill servers from a previous SALOME exection, if needed,
42 on the CORBA port given in args of runSalome
45 from killSalomeWithPort import killMyPort
46 my_port=str(args['port'])
50 print "problem in killLocalPort()"
54 def givenPortKill(port):
56 kill servers from a previous SALOME exection, if needed,
57 on the same CORBA port
60 from killSalomeWithPort import killMyPort
65 print "problem in LocalPortKill(), killMyPort("<<port<<")"
69 def kill_salome(args):
71 Kill servers from previous SALOME executions, if needed;
72 depending on args 'killall' or 'portkill', kill all executions,
73 or only execution on the same CORBA port
78 elif args['portkill']:
79 givenPortKill(str(args['port']))
81 # -----------------------------------------------------------------------------
83 # Class definitions to launch CORBA Servers
86 class InterpServer(Server):
87 def __init__(self,args):
89 if sys.platform != "win32":
90 env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
91 self.CMD=['xterm', '-e']+ env_ld_library_path + ['python']
93 self.CMD=['cmd', '/c', 'start cmd.exe', '/K', 'python']
98 print "INTERPSERVER::command = ", command
99 if sys.platform == "win32":
101 pid = win32pm.spawnpid( string.join(command, " "),'-nc' )
103 pid = os.spawnvp(os.P_NOWAIT, command[0], command)
104 process_id[pid]=self.CMD
109 def get_cata_path(list_modules,modules_root_dir):
110 """Build a list of catalog paths (cata_path) to initialize the ModuleCatalog server
115 for module in list_modules:
116 if modules_root_dir.has_key(module):
117 module_root_dir=modules_root_dir[module]
118 module_cata=module+"Catalog.xml"
119 cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources",module.lower(), module_cata)
121 if os.path.exists(cata_file):
122 cata_path.append(cata_file)
123 modules_cata[module]=cata_file
125 cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources", module_cata)
126 if os.path.exists(cata_file):
127 cata_path.append(cata_file)
128 modules_cata[module]=cata_file
130 for path in os.getenv("SALOME_CATALOGS_PATH","").split(os.pathsep):
131 if os.path.exists(path):
132 for cata_file in glob.glob(os.path.join(path,"*Catalog.xml")):
133 module_name= os.path.basename(cata_file)[:-11]
134 if not modules_cata.has_key(module_name):
135 cata_path.append(cata_file)
136 modules_cata[module_name]=cata_file
142 class CatalogServer(Server):
143 def __init__(self,args):
146 self.SCMD1=['SALOME_ModuleCatalog_Server','-common']
148 home_dir=os.getenv('HOME')
149 if home_dir is not None:
150 self.SCMD2=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')]
152 def setpath(self,modules_list,modules_root_dir):
153 list_modules = modules_list[:]
154 list_modules.reverse()
155 if self.args["gui"] :
156 list_modules = ["KERNEL", "GUI"] + list_modules
158 list_modules = ["KERNEL"] + list_modules
160 cata_path=get_cata_path(list_modules,modules_root_dir)
162 self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
166 class SalomeDSServer(Server):
167 def __init__(self,args):
170 self.CMD=['SALOMEDS_Server']
174 class ConnectionManagerServer(Server):
175 def __init__(self,args):
178 self.CMD=['SALOME_ConnectionManagerServer']
182 class RegistryServer(Server):
183 def __init__(self,args):
186 self.CMD=['SALOME_Registry_Server', '--salome_session','theSession']
190 class ContainerCPPServer(Server):
191 def __init__(self,args):
194 self.CMD=['SALOME_Container','FactoryServer']
198 class LoggerServer(Server):
199 def __init__(self,args):
202 from salome_utils import generateFileName
203 if sys.platform == "win32": dirpath = os.environ["HOME"]
204 else: dirpath = "/tmp"
205 logfile = generateFileName( dirpath,
211 print "==========================================================="
212 print "Logger server: put log to the file:"
214 print "==========================================================="
215 self.CMD=['SALOME_Logger_Server', logfile]
217 pass # end of LoggerServer class
221 class SessionServer(Server):
222 def __init__(self,args,modules_list,modules_root_dir):
223 self.args = args.copy()
224 # Bug 11512 (Problems with runSalome --xterm on Mandrake and Debian Sarge)
225 #self.args['xterm']=0
228 self.SCMD1=['SALOME_Session_Server']
230 if 'registry' in self.args['embedded']:
231 self.SCMD1+=['--with','Registry',
232 '(','--salome_session','theSession',')']
233 if 'moduleCatalog' in self.args['embedded']:
234 self.SCMD1+=['--with','ModuleCatalog','(','-common']
235 home_dir=os.getenv('HOME')
236 if home_dir is not None:
237 self.SCMD2+=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')]
239 if 'study' in self.args['embedded']:
240 self.SCMD2+=['--with','SALOMEDS','(',')']
241 if 'cppContainer' in self.args['embedded']:
242 self.SCMD2+=['--with','Container','(','FactoryServer',')']
243 if 'SalomeAppEngine' in self.args['embedded']:
244 self.SCMD2+=['--with','SalomeAppEngine','(',')']
246 if 'cppContainer' in self.args['standalone'] or 'cppContainer' in self.args['embedded']:
248 if 'pyContainer' in self.args['standalone'] or 'pyContainer' in self.args['embedded']:
249 raise Exception('Python containers no longer supported')
252 if self.args.has_key('session_gui'):
253 session_gui = self.args['session_gui']
256 if self.args['splash']:
257 self.SCMD2+=['SPLASH']
259 if self.args['study_hdf'] is not None:
260 self.SCMD2+=['--study-hdf=%s'%self.args['study_hdf']]
263 if self.args.has_key('pyscript') and len(self.args['pyscript']) > 0:
264 self.SCMD2+=['--pyscript=%s'%(",".join(self.args['pyscript']))]
268 if self.args['noexcepthandler']:
269 self.SCMD2+=['noexcepthandler']
270 if self.args.has_key('user_config'):
271 self.SCMD2+=['--resources=%s'%self.args['user_config']]
272 if self.args.has_key('modules'):
274 #keep only modules with GUI
275 for m in modules_list:
276 if m not in modules_root_dir:
277 list_modules.insert(0,m)
279 fr1 = os.path.join(modules_root_dir[m],"share","salome","resources",m.lower(),"SalomeApp.xml")
280 fr2 = os.path.join(modules_root_dir[m],"share","salome","resources","SalomeApp.xml")
281 if os.path.exists(fr1) or os.path.exists(fr2):
282 list_modules.insert(0,m)
283 list_modules.reverse()
284 self.SCMD2+=['--modules (%s)' % ":".join(list_modules)]
288 def setpath(self,modules_list,modules_root_dir):
289 list_modules = modules_list[:]
290 list_modules.reverse()
291 if self.args["gui"] :
292 list_modules = ["KERNEL", "GUI"] + list_modules
294 list_modules = ["KERNEL"] + list_modules
296 cata_path=get_cata_path(list_modules,modules_root_dir)
298 if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
299 #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
300 self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
302 self.CMD=self.SCMD1 + self.SCMD2
303 if self.args.has_key('test'):
304 self.CMD+=['-test'] + self.args['test']
305 elif self.args.has_key('play'):
306 self.CMD+=['-play'] + self.args['play']
308 if self.args["gdb_session"] or self.args["ddd_session"]:
309 f = open(".gdbinit4salome", "w")
311 args = " ".join(self.CMD[1:])
312 args = args.replace("(", "\(")
313 args = args.replace(")", "\)")
317 if self.args["ddd_session"]:
318 self.CMD = ["ddd", "--command=.gdbinit4salome", self.CMD[0]]
319 elif self.args["gdb_session"]:
320 self.CMD = ["xterm", "-e", "gdb", "--command=.gdbinit4salome", self.CMD[0]]
324 if self.args["valgrind_session"]:
326 val = os.getenv("VALGRIND_OPTIONS")
330 self.CMD = l + self.CMD
335 class LauncherServer(Server):
336 def __init__(self,args):
339 self.SCMD1=['SALOME_LauncherServer']
342 if 'registry' in self.args['embedded']:
343 self.SCMD1+=['--with','Registry',
344 '(','--salome_session','theSession',')']
345 if 'moduleCatalog' in self.args['embedded']:
346 self.SCMD1+=['--with','ModuleCatalog','(','-common']
347 self.SCMD2+=['-personal',
348 '${HOME}/Salome/resources/CatalogModulePersonnel.xml',')']
349 if 'study' in self.args['embedded']:
350 self.SCMD2+=['--with','SALOMEDS','(',')']
351 if 'cppContainer' in self.args['embedded']:
352 self.SCMD2+=['--with','Container','(','FactoryServer',')']
354 def setpath(self,modules_list,modules_root_dir):
355 list_modules = modules_list[:]
356 list_modules.reverse()
357 if self.args["gui"] :
358 list_modules = ["KERNEL", "GUI"] + list_modules
360 list_modules = ["KERNEL"] + list_modules
362 cata_path=get_cata_path(list_modules,modules_root_dir)
364 if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
365 #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
366 self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
368 self.CMD=self.SCMD1 + self.SCMD2
370 class NotifyServer(Server):
371 def __init__(self,args,modules_root_dir):
374 self.modules_root_dir=modules_root_dir
375 myLogName = os.environ["LOGNAME"]
376 self.CMD=['notifd','-c',
377 self.modules_root_dir["KERNEL"] +'/share/salome/resources/kernel/channel.cfg',
378 '-DFactoryIORFileName=/tmp/'+myLogName+'_rdifact.ior',
379 '-DChannelIORFileName=/tmp/'+myLogName+'_rdichan.ior',
380 '-DReportLogFile=/tmp/'+myLogName+'_notifd.report',
381 '-DDebugLogFile=/tmp/'+myLogName+'_notifd.debug',
385 # -----------------------------------------------------------------------------
388 """Salome Session Graphic User Interface activation"""
392 import SALOME_ModuleCatalog
393 import SALOME_Session_idl
394 session=clt.waitNS("/Kernel/Session",SALOME.Session)
395 session.GetInterface()
397 # -----------------------------------------------------------------------------
399 def startSalome(args, modules_list, modules_root_dir):
400 """Launch all SALOME servers requested by args"""
401 init_time = os.times()
403 if verbose(): print "startSalome ", args
406 # Set server launch command
408 if args.has_key('server_launch_mode'):
409 Server.set_server_launch_mode(args['server_launch_mode'])
412 # Wake up session option
414 if args['wake_up_session']:
415 if "OMNIORB_CONFIG" not in os.environ:
416 from salome_utils import generateFileName
417 home = os.getenv("HOME")
418 appli = os.getenv("APPLI")
420 if appli is not None:
421 home = os.path.join(os.path.realpath(home), appli,"USERS")
422 kwargs["with_username"] = True
424 last_running_config = generateFileName(home, prefix="omniORB",
429 os.environ['OMNIORB_CONFIG'] = last_running_config
434 # Initialisation ORB and Naming Service
437 clt=orbmodule.client(args)
440 # Wake up session option
442 if args['wake_up_session']:
446 import SALOME_ModuleCatalog
447 import SALOME_Session_idl
448 session = clt.waitNS("/Kernel/Session",SALOME.Session)
449 status = session.GetStatSession()
451 from salome_utils import getPortNumber
452 port = getPortNumber()
455 msg += "Session GUI for port number %s is already active."%(port)
457 msg += "If you which to wake up another session,"
459 msg += "please use variable OMNIORB_CONFIG"
461 msg += "to get the correct session object in naming service."
462 sys.stdout.write(msg+"\n")
465 session.GetInterface()
466 args["session_object"] = session
469 # Save Naming service port name into
470 # the file args["ns_port_log_file"]
471 if args.has_key('ns_port_log_file'):
472 home = os.environ['HOME']
473 appli= os.environ.get("APPLI")
474 if appli is not None:
475 home = os.path.join(os.path.realpath(home), appli, "USERS")
476 file_name = os.path.join(home, args["ns_port_log_file"])
477 f = open(file_name, "w")
478 f.write(os.environ['NSPORT'])
481 # Launch Logger Server (optional)
482 # and wait until it is registered in naming service
486 myServer=LoggerServer(args)
488 clt.waitLogger("Logger")
490 # Notify Server launch
493 if sys.platform != "win32":
494 if verbose(): print "Notify Server to launch"
496 myServer=NotifyServer(args,modules_root_dir)
499 # Launch Session Server (to show splash ASAP)
503 mySessionServ = SessionServer(args,args['modules'],modules_root_dir)
504 mySessionServ.setpath(modules_list,modules_root_dir)
508 # Launch Registry Server,
509 # and wait until it is registered in naming service
512 if ('registry' not in args['embedded']) | (args["gui"] == 0) :
513 myServer=RegistryServer(args)
515 if sys.platform == "win32":
516 clt.waitNS("/Registry")
518 clt.waitNSPID("/Registry",myServer.PID)
521 # Launch Catalog Server,
522 # and wait until it is registered in naming service
525 if ('moduleCatalog' not in args['embedded']) | (args["gui"] == 0):
526 cataServer=CatalogServer(args)
527 cataServer.setpath(modules_list,modules_root_dir)
529 import SALOME_ModuleCatalog
530 if sys.platform == "win32":
531 clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
533 clt.waitNSPID("/Kernel/ModulCatalog",cataServer.PID,SALOME_ModuleCatalog.ModuleCatalog)
536 # Launch SalomeDS Server,
537 # and wait until it is registered in naming service
540 #print "ARGS = ",args
541 if ('study' not in args['embedded']) | (args["gui"] == 0):
543 myServer=SalomeDSServer(args)
545 if sys.platform == "win32":
546 clt.waitNS("/myStudyManager")
548 clt.waitNSPID("/myStudyManager",myServer.PID)
551 # Launch LauncherServer
554 myCmServer = LauncherServer(args)
555 myCmServer.setpath(modules_list,modules_root_dir)
559 # Launch ConnectionManagerServer
562 myConnectionServer = ConnectionManagerServer(args)
563 myConnectionServer.run()
566 from Utils_Identity import getShortHostName
568 if os.getenv("HOSTNAME") == None:
569 if os.getenv("HOST") == None:
570 os.environ["HOSTNAME"]=getShortHostName()
572 os.environ["HOSTNAME"]=os.getenv("HOST")
574 theComputer = getShortHostName()
577 # Launch local C++ Container (FactoryServer),
578 # and wait until it is registered in naming service
581 if ('cppContainer' in args['standalone']) | (args["gui"] == 0) :
582 myServer=ContainerCPPServer(args)
584 if sys.platform == "win32":
585 clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
587 clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID)
590 # Launch local Python Container (FactoryServerPy),
591 # and wait until it is registered in naming service
594 if 'pyContainer' in args['standalone']:
595 raise Exception('Python containers no longer supported')
598 # Wait until Session Server is registered in naming service
606 import SALOME_ModuleCatalog
607 import SALOME_Session_idl
608 if sys.platform == "win32":
609 session=clt.waitNS("/Kernel/Session",SALOME.Session)
611 session=clt.waitNSPID("/Kernel/Session",mySessionServ.PID,SALOME.Session)
612 args["session_object"] = session
613 end_time = os.times()
615 print "Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
618 # ASV start GUI without Loader
620 # session.GetInterface()
623 # additionnal external python interpreters
629 nbaddi = args['interp']
632 traceback.print_exc()
633 print "-------------------------------------------------------------"
634 print "-- to get an external python interpreter:runSalome --interp=1"
635 print "-------------------------------------------------------------"
637 if verbose(): print "additional external python interpreters: ", nbaddi
639 for i in range(nbaddi):
641 anInterp=InterpServer(args)
644 # set PYTHONINSPECT variable (python interpreter in interactive mode)
646 os.environ["PYTHONINSPECT"]="1"
654 # -----------------------------------------------------------------------------
656 def useSalome(args, modules_list, modules_root_dir):
658 Launch all SALOME servers requested by args,
659 save list of process, give info to user,
660 show registered objects in Naming Service.
666 clt = startSalome(args, modules_list, modules_root_dir)
669 traceback.print_exc()
672 print "--- Error during Salome launch ---"
676 from addToKillList import addToKillList
677 from killSalomeWithPort import getPiDict
679 filedict = getPiDict(args['port'])
680 for pid, cmd in process_id.items():
681 addToKillList(pid, cmd, args['port'])
684 if verbose(): print """
685 Saving of the dictionary of Salome processes in %s
686 To kill SALOME processes from a console (kill all sessions from all ports):
688 To kill SALOME from the present interpreter, if it is not closed :
689 killLocalPort() --> kill this session
690 (use CORBA port from args of runSalome)
691 givenPortKill(port) --> kill a specific session with given CORBA port
692 killAllPorts() --> kill all sessions
694 runSalome, with --killall option, starts with killing
695 the processes resulting from the previous execution.
699 # Print Naming Service directory list
705 print " --- registered objects tree in Naming Service ---"
709 if not args['gui'] or not args['session_gui']:
710 if args['shutdown_servers']:
711 class __utils__(object):
712 def __init__(self, port):
714 import killSalomeWithPort
715 self.killSalomeWithPort = killSalomeWithPort
718 self.killSalomeWithPort.killMyPort(self.port)
721 args['shutdown_servers'] = __utils__(args['port'])
725 # run python scripts, passed via --execute option
727 if args.has_key('pyscript'):
728 if args.has_key('gui') and args.has_key('session_gui'):
729 if not args['gui'] or not args['session_gui']:
730 toimport = args['pyscript']
732 for srcname in toimport :
733 if srcname == 'killall':
738 if os.path.isabs(srcname):
739 if os.path.exists(srcname):
741 elif os.path.exists(srcname+".py"):
742 execScript(srcname+".py")
744 print "Can't execute file %s" % srcname
748 for path in [os.getcwd()] + sys.path:
749 if os.path.exists(os.path.join(path,srcname)):
750 execScript(os.path.join(path,srcname))
753 elif os.path.exists(os.path.join(path,srcname+".py")):
754 execScript(os.path.join(path,srcname+".py"))
759 print "Can't execute file %s" % srcname
767 def execScript(script_path):
768 print 'executing', script_path
769 sys.path.insert(0, os.path.dirname(script_path))
770 execfile(script_path,globals())
773 # -----------------------------------------------------------------------------
775 def registerEnv(args, modules_list, modules_root_dir):
777 Register args, modules_list, modules_root_dir in a file
778 for further use, when SALOME is launched embedded in an other application.
780 if sys.platform == "win32":
781 fileEnv = os.getenv('TEMP')
785 fileEnv += os.getenv('USER') + "_" + str(args['port']) \
786 + '_' + args['appname'].upper() + '_env'
787 fenv=open(fileEnv,'w')
788 pickle.dump((args, modules_list, modules_root_dir),fenv)
790 os.environ["SALOME_LAUNCH_CONFIG"] = fileEnv
792 # -----------------------------------------------------------------------------
795 """Salome Launch, when embedded in other application"""
796 fileEnv = os.environ["SALOME_LAUNCH_CONFIG"]
797 fenv=open(fileEnv,'r')
798 args, modules_list, modules_root_dir = pickle.load(fenv)
801 from searchFreePort import searchFreePort
802 searchFreePort(args, 0)
803 clt = useSalome(args, modules_list, modules_root_dir)
806 # -----------------------------------------------------------------------------
809 """Salome launch as a main application"""
810 from salome_utils import getHostName
811 print "runSalome running on %s" % getHostName()
812 args, modules_list, modules_root_dir = setenv.get_config()
816 if args.has_key('save_config'):
817 save_config = args['save_config']
820 if args['wake_up_session']:
824 from searchFreePort import searchFreePort
825 searchFreePort(args, save_config)
829 setenv.set_env(args, modules_list, modules_root_dir)
830 clt = useSalome(args, modules_list, modules_root_dir)
833 # -----------------------------------------------------------------------------
835 def foreGround(clt, args):
837 if "session_object" not in args:
839 session = args["session_object"]
841 # Wait until gui is arrived
850 status = session.GetStatSession()
851 gui_detected = status.activeGUI
856 from time import sleep
866 from salome_utils import getPortNumber
867 port = getPortNumber()
870 if sys.platform == "win32":
871 server.CMD = [os.getenv("PYTHONBIN"), "-m", "killSalomeWithPort", "--spy", "%s"%(os.getpid()), "%s"%(port)]
873 server.CMD = ["killSalomeWithPort.py", "--spy", "%s"%(os.getpid()), "%s"%(port)]
875 # os.system("killSalomeWithPort.py --spy %s %s &"%(os.getpid(), port))
881 status = session.GetStatSession()
882 assert status.activeGUI
885 from time import sleep
889 except KeyboardInterrupt:
890 from killSalomeWithPort import killMyPort
900 test = args['gui'] and args['session_gui']
901 test = test or args['wake_up_session']
903 # The next test covers the --pinter option or var PYTHONINSPECT setted
905 test = test and not os.environ.get('PYTHONINSPECT')
907 # The next test covers the python -i $KERNEL_ROOT_DIR/bin/salome/runSalome.py case
910 from ctypes import POINTER, c_int, cast, pythonapi
911 iflag_ptr = cast(pythonapi.Py_InteractiveFlag, POINTER(c_int))
912 test = test and not iflag_ptr.contents.value
916 test = test and os.getenv("SALOME_TEST_MODE", "0") != "1"
917 test = test and args['foreground']
920 foreGround(clt, args)
926 # -----------------------------------------------------------------------------
928 if __name__ == "__main__":