2 # -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2010 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
33 from launchConfigureParser import verbose
34 from server import process_id
36 if sys.platform == "win32":
41 # -----------------------------------------------------------------------------
43 from killSalome import killAllPorts
47 kill servers from a previous SALOME exection, if needed,
48 on the CORBA port given in args of runSalome
51 from killSalomeWithPort import killMyPort
52 my_port=str(args['port'])
56 print "problem in killLocalPort()"
60 def givenPortKill(port):
62 kill servers from a previous SALOME exection, if needed,
63 on the same CORBA port
66 from killSalomeWithPort import killMyPort
71 print "problem in LocalPortKill(), killMyPort("<<port<<")"
75 def kill_salome(args):
77 Kill servers from previous SALOME executions, if needed;
78 depending on args 'killall' or 'portkill', kill all executions,
79 or only execution on the same CORBA port
84 elif args['portkill']:
85 givenPortKill(str(args['port']))
87 # -----------------------------------------------------------------------------
89 # Class definitions to launch CORBA Servers
92 class InterpServer(Server):
93 def __init__(self,args):
95 env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
96 self.CMD=['xterm', '-e']+ env_ld_library_path + ['python']
101 print "INTERPSERVER::command = ", command
102 if sys.platform == "win32":
104 pid = win32pm.spawnpid( string.join(command, " "),'-nc' )
106 pid = os.spawnvp(os.P_NOWAIT, command[0], command)
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 modules_root_dir.has_key(module):
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(SEP):
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 not modules_cata.has_key(module_name):
138 cata_path.append(cata_file)
139 modules_cata[module_name]=cata_file
145 class CatalogServer(Server):
146 def __init__(self,args):
149 self.SCMD1=['SALOME_ModuleCatalog_Server','-common']
151 home_dir=os.getenv('HOME')
152 if home_dir is not None:
153 self.SCMD2=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')]
155 def setpath(self,modules_list,modules_root_dir):
156 list_modules = modules_list[:]
157 list_modules.reverse()
158 if self.args["gui"] :
159 list_modules = ["KERNEL", "GUI"] + list_modules
161 list_modules = ["KERNEL"] + list_modules
163 cata_path=get_cata_path(list_modules,modules_root_dir)
165 self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
169 class SalomeDSServer(Server):
170 def __init__(self,args):
173 self.CMD=['SALOMEDS_Server']
177 class ConnectionManagerServer(Server):
178 def __init__(self,args):
181 self.CMD=['SALOME_ConnectionManagerServer']
185 class RegistryServer(Server):
186 def __init__(self,args):
189 self.CMD=['SALOME_Registry_Server', '--salome_session','theSession']
193 class ContainerCPPServer(Server):
194 def __init__(self,args):
197 self.CMD=['SALOME_Container','FactoryServer']
201 class ContainerPYServer(Server):
202 def __init__(self,args):
205 if sys.platform == "win32":
206 self.CMD=[os.environ["PYTHONBIN"], '\"'+os.environ["KERNEL_ROOT_DIR"] + '/bin/salome/SALOME_ContainerPy.py'+'\"','FactoryServerPy']
208 self.CMD=['SALOME_ContainerPy.py','FactoryServerPy']
212 class LoggerServer(Server):
213 def __init__(self,args):
216 from salome_utils import generateFileName
217 if sys.platform == "win32": dirpath = os.environ["HOME"]
218 else: dirpath = "/tmp"
219 logfile = generateFileName( dirpath,
225 print "==========================================================="
226 print "Logger server: put log to the file:"
228 print "==========================================================="
229 self.CMD=['SALOME_Logger_Server', logfile]
231 pass # end of LoggerServer class
235 class SessionServer(Server):
236 def __init__(self,args):
237 self.args = args.copy()
238 # Bug 11512 (Problems with runSalome --xterm on Mandrake and Debian Sarge)
239 #self.args['xterm']=0
242 self.SCMD1=['SALOME_Session_Server']
244 if 'registry' in self.args['embedded']:
245 self.SCMD1+=['--with','Registry',
246 '(','--salome_session','theSession',')']
247 if 'moduleCatalog' in self.args['embedded']:
248 self.SCMD1+=['--with','ModuleCatalog','(','-common']
249 home_dir=os.getenv('HOME')
250 if home_dir is not None:
251 self.SCMD2+=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')]
253 if 'study' in self.args['embedded']:
254 self.SCMD2+=['--with','SALOMEDS','(',')']
255 if 'cppContainer' in self.args['embedded']:
256 self.SCMD2+=['--with','Container','(','FactoryServer',')']
257 if 'SalomeAppEngine' in self.args['embedded']:
258 self.SCMD2+=['--with','SalomeAppEngine','(',')']
260 if 'cppContainer' in self.args['standalone'] or 'cppContainer' in self.args['embedded']:
262 if 'pyContainer' in self.args['standalone'] or 'pyContainer' in self.args['embedded']:
266 if self.args.has_key('session_gui'):
267 session_gui = self.args['session_gui']
270 if self.args['splash']:
271 self.SCMD2+=['SPLASH']
273 if self.args['study_hdf'] is not None:
274 self.SCMD2+=['--study-hdf=%s'%self.args['study_hdf']]
278 if self.args['noexcepthandler']:
279 self.SCMD2+=['noexcepthandler']
280 if self.args.has_key('user_config'):
281 self.SCMD2+=['--resources=%s'%self.args['user_config']]
282 if self.args.has_key('modules'):
283 self.SCMD2+=['--modules (%s)'%":".join(self.args['modules'])]
284 if self.args.has_key('pyscript') and len(self.args['pyscript']) > 0:
285 self.SCMD2+=['--pyscript=%s'%(",".join(self.args['pyscript']))]
287 def setpath(self,modules_list,modules_root_dir):
288 list_modules = modules_list[:]
289 list_modules.reverse()
290 if self.args["gui"] :
291 list_modules = ["KERNEL", "GUI"] + list_modules
293 list_modules = ["KERNEL"] + list_modules
295 cata_path=get_cata_path(list_modules,modules_root_dir)
297 if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
298 #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
299 self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
301 self.CMD=self.SCMD1 + self.SCMD2
302 if self.args.has_key('test'):
303 self.CMD+=['-test'] + self.args['test']
304 elif self.args.has_key('play'):
305 self.CMD+=['-play'] + self.args['play']
307 if self.args["gdb_session"] or self.args["ddd_session"]:
308 f = open(".gdbinit4salome", "w")
310 args = " ".join(self.CMD[1:])
311 args = args.replace("(", "\(")
312 args = args.replace(")", "\)")
316 if self.args["ddd_session"]:
317 self.CMD = ["ddd", "--command=.gdbinit4salome", self.CMD[0]]
318 elif self.args["gdb_session"]:
319 self.CMD = ["xterm", "-e", "gdb", "--command=.gdbinit4salome", self.CMD[0]]
323 if self.args["valgrind_session"]:
325 val = os.getenv("VALGRIND_OPTIONS")
329 self.CMD = l + self.CMD
334 class LauncherServer(Server):
335 def __init__(self,args):
338 self.SCMD1=['SALOME_LauncherServer']
341 if 'registry' in self.args['embedded']:
342 self.SCMD1+=['--with','Registry',
343 '(','--salome_session','theSession',')']
344 if 'moduleCatalog' in self.args['embedded']:
345 self.SCMD1+=['--with','ModuleCatalog','(','-common']
346 self.SCMD2+=['-personal',
347 '${HOME}/Salome/resources/CatalogModulePersonnel.xml',')']
348 if 'study' in self.args['embedded']:
349 self.SCMD2+=['--with','SALOMEDS','(',')']
350 if 'cppContainer' in self.args['embedded']:
351 self.SCMD2+=['--with','Container','(','FactoryServer',')']
353 def setpath(self,modules_list,modules_root_dir):
354 list_modules = modules_list[:]
355 list_modules.reverse()
356 if self.args["gui"] :
357 list_modules = ["KERNEL", "GUI"] + list_modules
359 list_modules = ["KERNEL"] + list_modules
361 cata_path=get_cata_path(list_modules,modules_root_dir)
363 if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
364 #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
365 self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
367 self.CMD=self.SCMD1 + self.SCMD2
369 class NotifyServer(Server):
370 def __init__(self,args,modules_root_dir):
373 self.modules_root_dir=modules_root_dir
374 myLogName = os.environ["LOGNAME"]
375 self.CMD=['notifd','-c',
376 self.modules_root_dir["KERNEL"] +'/share/salome/resources/kernel/channel.cfg',
377 '-DFactoryIORFileName=/tmp/'+myLogName+'_rdifact.ior',
378 '-DChannelIORFileName=/tmp/'+myLogName+'_rdichan.ior',
379 '-DReportLogFile=/tmp/'+myLogName+'_notifd.report',
380 '-DDebugLogFile=/tmp/'+myLogName+'_notifd.debug',
384 # -----------------------------------------------------------------------------
387 """Salome Session Graphic User Interface activation"""
391 import SALOME_ModuleCatalog
392 import SALOME_Session_idl
393 session=clt.waitNS("/Kernel/Session",SALOME.Session)
394 session.GetInterface()
396 # -----------------------------------------------------------------------------
398 def startSalome(args, modules_list, modules_root_dir):
399 """Launch all SALOME servers requested by args"""
400 init_time = os.times()
402 if verbose(): print "startSalome ", args
405 # Initialisation ORB and Naming Service
408 clt=orbmodule.client(args)
409 # Save Naming service port name into
410 # the file args["ns_port_log_file"]
411 if args.has_key('ns_port_log_file'):
412 home = os.environ['HOME']
413 appli= os.environ.get("APPLI")
414 if appli is not None:
415 home='%s/%s'%(home,appli)
417 file_name= '%s/%s'%(home, args["ns_port_log_file"])
418 f = open(file_name, "w")
419 f.write(os.environ['NSPORT'])
422 # Launch Logger Server (optional)
423 # and wait until it is registered in naming service
427 myServer=LoggerServer(args)
429 clt.waitLogger("Logger")
431 # Notify Server launch
434 if sys.platform != "win32":
435 if verbose(): print "Notify Server to launch"
437 myServer=NotifyServer(args,modules_root_dir)
440 # Launch Session Server (to show splash ASAP)
444 mySessionServ = SessionServer(args)
445 mySessionServ.setpath(modules_list,modules_root_dir)
449 # Launch Registry Server,
450 # and wait until it is registered in naming service
453 if ('registry' not in args['embedded']) | (args["gui"] == 0) :
454 myServer=RegistryServer(args)
456 if sys.platform == "win32":
457 clt.waitNS("/Registry")
459 clt.waitNSPID("/Registry",myServer.PID)
462 # Launch Catalog Server,
463 # and wait until it is registered in naming service
466 if ('moduleCatalog' not in args['embedded']) | (args["gui"] == 0):
467 cataServer=CatalogServer(args)
468 cataServer.setpath(modules_list,modules_root_dir)
470 import SALOME_ModuleCatalog
471 if sys.platform == "win32":
472 clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
474 clt.waitNSPID("/Kernel/ModulCatalog",cataServer.PID,SALOME_ModuleCatalog.ModuleCatalog)
477 # Launch SalomeDS Server,
478 # and wait until it is registered in naming service
481 #print "ARGS = ",args
482 if ('study' not in args['embedded']) | (args["gui"] == 0):
484 myServer=SalomeDSServer(args)
486 if sys.platform == "win32":
487 clt.waitNS("/myStudyManager")
489 clt.waitNSPID("/myStudyManager",myServer.PID)
492 # Launch LauncherServer
495 myCmServer = LauncherServer(args)
496 myCmServer.setpath(modules_list,modules_root_dir)
500 # Launch ConnectionManagerServer
503 myConnectionServer = ConnectionManagerServer(args)
504 myConnectionServer.run()
507 from Utils_Identity import getShortHostName
509 if os.getenv("HOSTNAME") == None:
510 if os.getenv("HOST") == None:
511 os.environ["HOSTNAME"]=getShortHostName()
513 os.environ["HOSTNAME"]=os.getenv("HOST")
515 theComputer = getShortHostName()
518 # Launch local C++ Container (FactoryServer),
519 # and wait until it is registered in naming service
522 if ('cppContainer' in args['standalone']) | (args["gui"] == 0) :
523 myServer=ContainerCPPServer(args)
525 if sys.platform == "win32":
526 clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
528 clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID)
531 # Launch local Python Container (FactoryServerPy),
532 # and wait until it is registered in naming service
535 if 'pyContainer' in args['standalone']:
536 myServer=ContainerPYServer(args)
538 if sys.platform == "win32":
539 clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy")
541 clt.waitNSPID("/Containers/" + theComputer + "/FactoryServerPy",myServer.PID)
544 # Wait until Session Server is registered in naming service
552 import SALOME_ModuleCatalog
553 import SALOME_Session_idl
554 if sys.platform == "win32":
555 session=clt.waitNS("/Kernel/Session",SALOME.Session)
557 session=clt.waitNSPID("/Kernel/Session",mySessionServ.PID,SALOME.Session)
558 end_time = os.times()
560 print "Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
563 # ASV start GUI without Loader
565 # session.GetInterface()
568 # additionnal external python interpreters
574 nbaddi = args['interp']
577 traceback.print_exc()
578 print "-------------------------------------------------------------"
579 print "-- to get an external python interpreter:runSalome --interp=1"
580 print "-------------------------------------------------------------"
582 print "additional external python interpreters: ", nbaddi
584 for i in range(nbaddi):
586 anInterp=InterpServer(args)
589 # set PYTHONINSPECT variable (python interpreter in interactive mode)
591 os.environ["PYTHONINSPECT"]="1"
596 # -----------------------------------------------------------------------------
598 def useSalome(args, modules_list, modules_root_dir):
600 Launch all SALOME servers requested by args,
601 save list of process, give info to user,
602 show registered objects in Naming Service.
608 clt = startSalome(args, modules_list, modules_root_dir)
611 traceback.print_exc()
614 print "--- Error during Salome launch ---"
618 from addToKillList import addToKillList
619 from killSalomeWithPort import getPiDict
621 filedict = getPiDict(args['port'])
622 for pid, cmd in process_id.items():
623 addToKillList(pid, cmd, args['port'])
626 if verbose(): print """
627 Saving of the dictionary of Salome processes in %s
628 To kill SALOME processes from a console (kill all sessions from all ports):
630 To kill SALOME from the present interpreter, if it is not closed :
631 killLocalPort() --> kill this session
632 (use CORBA port from args of runSalome)
633 givenPortKill(port) --> kill a specific session with given CORBA port
634 killAllPorts() --> kill all sessions
636 runSalome, with --killall option, starts with killing
637 the processes resulting from the previous execution.
641 # Print Naming Service directory list
647 print " --- registered objects tree in Naming Service ---"
651 if not args['gui'] or not args['session_gui']:
652 if args['shutdown_servers']:
653 class __utils__(object):
654 def __init__(self, port):
656 import killSalomeWithPort
657 self.killSalomeWithPort = killSalomeWithPort
660 self.killSalomeWithPort.killMyPort(self.port)
663 args['shutdown_servers'] = __utils__(args['port'])
667 # run python scripts, passed via --execute option
669 if args.has_key('pyscript'):
670 if args.has_key('gui') and args.has_key('session_gui'):
671 if not args['gui'] or not args['session_gui']:
672 toimport = args['pyscript']
674 for srcname in toimport :
675 if srcname == 'killall':
680 if os.path.isabs(srcname):
681 if os.path.exists(srcname):
683 elif os.path.exists(srcname+".py"):
684 execScript(srcname+".py")
686 print "Can't execute file %s" % srcname
690 for path in [os.getcwd()] + sys.path:
691 if os.path.exists(os.path.join(path,srcname)):
692 execScript(os.path.join(path,srcname))
695 elif os.path.exists(os.path.join(path,srcname+".py")):
696 execScript(os.path.join(path,srcname+".py"))
701 print "Can't execute file %s" % srcname
709 def execScript(script_path):
710 print 'executing', script_path
711 sys.path.insert(0, os.path.dirname(script_path))
712 execfile(script_path,globals())
715 # -----------------------------------------------------------------------------
717 def registerEnv(args, modules_list, modules_root_dir):
719 Register args, modules_list, modules_root_dir in a file
720 for further use, when SALOME is launched embedded in an other application.
722 if sys.platform == "win32":
723 fileEnv = os.getenv('TEMP')
727 fileEnv += os.getenv('USER') + "_" + str(args['port']) \
728 + '_' + args['appname'].upper() + '_env'
729 fenv=open(fileEnv,'w')
730 pickle.dump((args, modules_list, modules_root_dir),fenv)
732 os.environ["SALOME_LAUNCH_CONFIG"] = fileEnv
734 # -----------------------------------------------------------------------------
736 def searchFreePort(args, save_config=1):
737 print "Searching for a free port for naming service:",
739 if sys.platform == "win32":
740 tmp_file = os.getenv('TEMP');
743 tmp_file = os.path.join(tmp_file, '.netstat_%s'%os.getpid())
745 ###status = os.system("netstat -ltn | grep -E :%s > /dev/null 2>&1"%(NSPORT))
746 os.system( "netstat -a -n > %s" % tmp_file );
747 f = open( tmp_file, 'r' );
748 ports = f.readlines();
750 os.remove( tmp_file );
752 def portIsUsed(port, data):
753 regObj = re.compile( ".*tcp.*:([0-9]+).*:.*listen", re.IGNORECASE );
756 p = int(regObj.match(item).group(1))
757 if p == port: return True
768 if not portIsUsed(NSPORT, ports):
769 print "%s - OK"%(NSPORT)
771 from salome_utils import generateFileName, getHostName
772 hostname = getHostName()
774 home = os.getenv("HOME")
775 appli = os.getenv("APPLI")
777 if appli is not None:
778 home = os.path.join(home, appli,"USERS")
779 kwargs["with_username"]=True
781 omniorb_config = generateFileName(home, prefix="omniORB",
788 initref = "NameService=corbaname::%s:%s"%(hostname, NSPORT)
789 from omniORB import CORBA
790 if CORBA.ORB_ID == "omniORB4":
791 orbdata.append("InitRef = %s"%(initref))
792 orbdata.append("giopMaxMsgSize = 2097152000 # 2 GBytes")
793 orbdata.append("traceLevel = 0 # critical errors only")
795 orbdata.append("ORBInitRef %s"%(initref))
796 orbdata.append("ORBgiopMaxMsgSize = 2097152000 # 2 GBytes")
797 orbdata.append("ORBtraceLevel = 0 # critical errors only")
800 f = open(omniorb_config, "w")
801 f.write("\n".join(orbdata))
804 os.environ['OMNIORB_CONFIG'] = omniorb_config
805 os.environ['NSPORT'] = "%s"%(NSPORT)
806 os.environ['NSHOST'] = "%s"%(hostname)
807 args['port'] = os.environ['NSPORT']
810 last_running_config = generateFileName(home, prefix="omniORB",
816 if sys.platform == "win32":
818 shutil.copyfile(omniorb_config, last_running_config)
821 os.remove(last_running_config)
824 os.symlink(omniorb_config, last_running_config)
833 msg += "Can't find a free port to launch omniNames\n"
834 msg += "Try to kill the running servers and then launch SALOME again.\n"
835 raise RuntimeError, msg
840 # -----------------------------------------------------------------------------
843 """Salome Launch, when embedded in other application"""
844 fileEnv = os.environ["SALOME_LAUNCH_CONFIG"]
845 fenv=open(fileEnv,'r')
846 args, modules_list, modules_root_dir = pickle.load(fenv)
849 searchFreePort(args, 0)
850 clt = useSalome(args, modules_list, modules_root_dir)
853 # -----------------------------------------------------------------------------
856 """Salome launch as a main application"""
857 from salome_utils import getHostName
858 print "runSalome running on %s" % getHostName()
859 args, modules_list, modules_root_dir = setenv.get_config()
862 if args.has_key('save_config'):
863 save_config = args['save_config']
864 searchFreePort(args, save_config)
866 setenv.set_env(args, modules_list, modules_root_dir)
867 clt = useSalome(args, modules_list, modules_root_dir)
870 # -----------------------------------------------------------------------------
872 if __name__ == "__main__":