2 # -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2013 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 from salomeLauncherUtils import formatScriptsAndArgs
38 # -----------------------------------------------------------------------------
40 from killSalome import killAllPorts
44 kill servers from a previous SALOME exection, 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 exection, if needed,
60 on the same CORBA port
63 from killSalomeWithPort import killMyPort
68 print "problem in LocalPortKill(), killMyPort("<<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 env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
94 self.CMD=['xterm', '-e']+ env_ld_library_path + ['python']
96 self.CMD=['cmd', '/c', 'start cmd.exe', '/K', '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(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 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 LoggerServer(Server):
202 def __init__(self,args):
205 from salome_utils import generateFileName
206 if sys.platform == "win32": dirpath = os.environ["HOME"]
207 else: dirpath = "/tmp"
208 logfile = generateFileName( dirpath,
214 print "==========================================================="
215 print "Logger server: put log to the file:"
217 print "==========================================================="
218 self.CMD=['SALOME_Logger_Server', logfile]
220 pass # end of LoggerServer class
224 class SessionServer(Server):
225 def __init__(self,args,modules_list,modules_root_dir):
226 self.args = args.copy()
227 # Bug 11512 (Problems with runSalome --xterm on Mandrake and Debian Sarge)
228 #self.args['xterm']=0
231 self.SCMD1=['SALOME_Session_Server']
233 if 'registry' in self.args['embedded']:
234 self.SCMD1+=['--with','Registry',
235 '(','--salome_session','theSession',')']
236 if 'moduleCatalog' in self.args['embedded']:
237 self.SCMD1+=['--with','ModuleCatalog','(','-common']
238 home_dir=os.getenv('HOME')
239 if home_dir is not None:
240 self.SCMD2+=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')]
242 if 'study' in self.args['embedded']:
243 self.SCMD2+=['--with','SALOMEDS','(',')']
244 if 'cppContainer' in self.args['embedded']:
245 self.SCMD2+=['--with','Container','(','FactoryServer',')']
246 if 'SalomeAppEngine' in self.args['embedded']:
247 self.SCMD2+=['--with','SalomeAppEngine','(',')']
249 if 'cppContainer' in self.args['standalone'] or 'cppContainer' in self.args['embedded']:
251 if 'pyContainer' in self.args['standalone'] or 'pyContainer' in self.args['embedded']:
252 raise Exception('Python containers no longer supported')
255 if self.args.has_key('session_gui'):
256 session_gui = self.args['session_gui']
259 if self.args['splash']:
260 self.SCMD2+=['SPLASH']
262 if self.args['study_hdf'] is not None:
263 self.SCMD2+=['--study-hdf=%s'%self.args['study_hdf']]
266 if self.args.has_key('pyscript') and len(self.args['pyscript']) > 0:
267 msg = json.dumps(self.args['pyscript'])
268 self.SCMD2+=['--pyscript=%s'%(msg)]
272 if self.args['noexcepthandler']:
273 self.SCMD2+=['noexcepthandler']
274 if self.args.has_key('user_config'):
275 self.SCMD2+=['--resources=%s'%self.args['user_config']]
276 if self.args.has_key('modules'):
278 #keep only modules with GUI
279 for m in modules_list:
280 if m not in modules_root_dir:
281 list_modules.insert(0,m)
283 fr1 = os.path.join(modules_root_dir[m],"share","salome","resources",m.lower(),"SalomeApp.xml")
284 fr2 = os.path.join(modules_root_dir[m],"share","salome","resources","SalomeApp.xml")
285 if os.path.exists(fr1) or os.path.exists(fr2):
286 list_modules.insert(0,m)
287 list_modules.reverse()
288 self.SCMD2+=['--modules (%s)' % ":".join(list_modules)]
292 def setpath(self,modules_list,modules_root_dir):
293 list_modules = modules_list[:]
294 list_modules.reverse()
295 if self.args["gui"] :
296 list_modules = ["KERNEL", "GUI"] + list_modules
298 list_modules = ["KERNEL"] + list_modules
300 cata_path=get_cata_path(list_modules,modules_root_dir)
302 if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
303 #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
304 self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
306 self.CMD=self.SCMD1 + self.SCMD2
307 if self.args.has_key('test'):
308 self.CMD+=['-test'] + self.args['test']
309 elif self.args.has_key('play'):
310 self.CMD+=['-play'] + self.args['play']
312 if self.args["gdb_session"] or self.args["ddd_session"]:
313 f = open(".gdbinit4salome", "w")
315 args = " ".join(self.CMD[1:])
316 args = args.replace("(", "\(")
317 args = args.replace(")", "\)")
321 if self.args["ddd_session"]:
322 self.CMD = ["ddd", "--command=.gdbinit4salome", self.CMD[0]]
323 elif self.args["gdb_session"]:
324 self.CMD = ["xterm", "-e", "gdb", "--command=.gdbinit4salome", self.CMD[0]]
328 if self.args["valgrind_session"]:
330 val = os.getenv("VALGRIND_OPTIONS")
334 self.CMD = l + self.CMD
339 class LauncherServer(Server):
340 def __init__(self,args):
343 self.SCMD1=['SALOME_LauncherServer']
346 if 'registry' in self.args['embedded']:
347 self.SCMD1+=['--with','Registry',
348 '(','--salome_session','theSession',')']
349 if 'moduleCatalog' in self.args['embedded']:
350 self.SCMD1+=['--with','ModuleCatalog','(','-common']
351 self.SCMD2+=['-personal',
352 '${HOME}/Salome/resources/CatalogModulePersonnel.xml',')']
353 if 'study' in self.args['embedded']:
354 self.SCMD2+=['--with','SALOMEDS','(',')']
355 if 'cppContainer' in self.args['embedded']:
356 self.SCMD2+=['--with','Container','(','FactoryServer',')']
358 def setpath(self,modules_list,modules_root_dir):
359 list_modules = modules_list[:]
360 list_modules.reverse()
361 if self.args["gui"] :
362 list_modules = ["KERNEL", "GUI"] + list_modules
364 list_modules = ["KERNEL"] + list_modules
366 cata_path=get_cata_path(list_modules,modules_root_dir)
368 if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
369 #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
370 self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
372 self.CMD=self.SCMD1 + self.SCMD2
374 class NotifyServer(Server):
375 def __init__(self,args,modules_root_dir):
378 self.modules_root_dir=modules_root_dir
379 myLogName = os.environ["LOGNAME"]
380 self.CMD=['notifd','-c',
381 self.modules_root_dir["KERNEL"] +'/share/salome/resources/kernel/channel.cfg',
382 '-DFactoryIORFileName=/tmp/'+myLogName+'_rdifact.ior',
383 '-DChannelIORFileName=/tmp/'+myLogName+'_rdichan.ior',
384 '-DReportLogFile=/tmp/'+myLogName+'_notifd.report',
385 '-DDebugLogFile=/tmp/'+myLogName+'_notifd.debug',
389 # -----------------------------------------------------------------------------
392 """Salome Session Graphic User Interface activation"""
396 import SALOME_ModuleCatalog
397 import SALOME_Session_idl
398 session=clt.waitNS("/Kernel/Session",SALOME.Session)
399 session.GetInterface()
401 # -----------------------------------------------------------------------------
403 def startSalome(args, modules_list, modules_root_dir):
404 """Launch all SALOME servers requested by args"""
405 init_time = os.times()
407 if verbose(): print "startSalome ", args
410 # Set server launch command
412 if args.has_key('server_launch_mode'):
413 Server.set_server_launch_mode(args['server_launch_mode'])
416 # Wake up session option
418 if args['wake_up_session']:
419 if "OMNIORB_CONFIG" not in os.environ:
420 from salome_utils import generateFileName
421 omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
423 if omniorbUserPath is not None:
424 kwargs["with_username"]=True
426 last_running_config = generateFileName(omniorbUserPath, prefix="omniORB",
431 os.environ['OMNIORB_CONFIG'] = last_running_config
436 # Initialisation ORB and Naming Service
439 clt=orbmodule.client(args)
442 # Wake up session option
444 if args['wake_up_session']:
448 import SALOME_ModuleCatalog
449 import SALOME_Session_idl
450 session = clt.waitNS("/Kernel/Session",SALOME.Session)
451 status = session.GetStatSession()
453 from salome_utils import getPortNumber
454 port = getPortNumber()
457 msg += "Session GUI for port number %s is already active."%(port)
459 msg += "If you which to wake up another session,"
461 msg += "please use variable OMNIORB_CONFIG"
463 msg += "to get the correct session object in naming service."
464 sys.stdout.write(msg+"\n")
467 session.GetInterface()
468 args["session_object"] = session
471 # Save Naming service port name into
472 # the file args["ns_port_log_file"]
473 if args.has_key('ns_port_log_file'):
474 omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
475 file_name = os.path.join(omniorbUserPath, args["ns_port_log_file"])
476 f = open(file_name, "w")
477 f.write(os.environ['NSPORT'])
480 # Launch Logger Server (optional)
481 # and wait until it is registered in naming service
485 myServer=LoggerServer(args)
487 clt.waitLogger("Logger")
489 # Notify Server launch
492 if sys.platform != "win32":
493 if verbose(): print "Notify Server to launch"
495 myServer=NotifyServer(args,modules_root_dir)
498 # Launch Session Server (to show splash ASAP)
502 mySessionServ = SessionServer(args,args['modules'],modules_root_dir)
503 mySessionServ.setpath(modules_list,modules_root_dir)
507 # Launch Registry Server,
508 # and wait until it is registered in naming service
511 if ('registry' not in args['embedded']) | (args["gui"] == 0) :
512 myServer=RegistryServer(args)
514 if sys.platform == "win32":
515 clt.waitNS("/Registry")
517 clt.waitNSPID("/Registry",myServer.PID)
520 # Launch Catalog Server,
521 # and wait until it is registered in naming service
524 if ('moduleCatalog' not in args['embedded']) | (args["gui"] == 0):
525 cataServer=CatalogServer(args)
526 cataServer.setpath(modules_list,modules_root_dir)
528 import SALOME_ModuleCatalog
529 if sys.platform == "win32":
530 clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
532 clt.waitNSPID("/Kernel/ModulCatalog",cataServer.PID,SALOME_ModuleCatalog.ModuleCatalog)
535 # Launch SalomeDS Server,
536 # and wait until it is registered in naming service
539 #print "ARGS = ",args
540 if ('study' not in args['embedded']) | (args["gui"] == 0):
542 myServer=SalomeDSServer(args)
544 if sys.platform == "win32":
545 clt.waitNS("/myStudyManager")
547 clt.waitNSPID("/myStudyManager",myServer.PID)
550 # Launch LauncherServer
553 myCmServer = LauncherServer(args)
554 myCmServer.setpath(modules_list,modules_root_dir)
558 # Launch ConnectionManagerServer
561 myConnectionServer = ConnectionManagerServer(args)
562 myConnectionServer.run()
565 from Utils_Identity import getShortHostName
567 if os.getenv("HOSTNAME") == None:
568 if os.getenv("HOST") == None:
569 os.environ["HOSTNAME"]=getShortHostName()
571 os.environ["HOSTNAME"]=os.getenv("HOST")
573 theComputer = getShortHostName()
576 # Launch local C++ Container (FactoryServer),
577 # and wait until it is registered in naming service
580 if ('cppContainer' in args['standalone']) | (args["gui"] == 0) :
581 myServer=ContainerCPPServer(args)
583 if sys.platform == "win32":
584 clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
586 clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID)
589 # Launch local Python Container (FactoryServerPy),
590 # and wait until it is registered in naming service
593 if 'pyContainer' in args['standalone']:
594 raise Exception('Python containers no longer supported')
597 # Wait until Session Server is registered in naming service
605 import SALOME_ModuleCatalog
606 import SALOME_Session_idl
607 if sys.platform == "win32":
608 session=clt.waitNS("/Kernel/Session",SALOME.Session)
610 session=clt.waitNSPID("/Kernel/Session",mySessionServ.PID,SALOME.Session)
611 args["session_object"] = session
612 end_time = os.times()
614 print "Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
617 # ASV start GUI without Loader
619 # session.GetInterface()
622 # additionnal external python interpreters
628 nbaddi = args['interp']
631 traceback.print_exc()
632 print "-------------------------------------------------------------"
633 print "-- to get an external python interpreter:runSalome --interp=1"
634 print "-------------------------------------------------------------"
636 if verbose(): print "additional external python interpreters: ", nbaddi
638 for i in range(nbaddi):
640 anInterp=InterpServer(args)
643 # set PYTHONINSPECT variable (python interpreter in interactive mode)
645 os.environ["PYTHONINSPECT"]="1"
653 # -----------------------------------------------------------------------------
655 def useSalome(args, modules_list, modules_root_dir):
657 Launch all SALOME servers requested by args,
658 save list of process, give info to user,
659 show registered objects in Naming Service.
665 clt = startSalome(args, modules_list, modules_root_dir)
668 traceback.print_exc()
671 print "--- Error during Salome launch ---"
675 from addToKillList import addToKillList
676 from killSalomeWithPort import getPiDict
678 filedict = getPiDict(args['port'])
679 for pid, cmd in process_id.items():
680 addToKillList(pid, cmd, args['port'])
683 if verbose(): print """
684 Saving of the dictionary of Salome processes in %s
685 To kill SALOME processes from a console (kill all sessions from all ports):
687 To kill SALOME from the present interpreter, if it is not closed :
688 killLocalPort() --> kill this session
689 (use CORBA port from args of runSalome)
690 givenPortKill(port) --> kill a specific session with given CORBA port
691 killAllPorts() --> kill all sessions
693 runSalome, with --killall option, starts with killing
694 the processes resulting from the previous execution.
698 # Print Naming Service directory list
704 print " --- registered objects tree in Naming Service ---"
708 if not args['gui'] or not args['session_gui']:
709 if args['shutdown_servers']:
710 class __utils__(object):
711 def __init__(self, port):
713 import killSalomeWithPort
714 self.killSalomeWithPort = killSalomeWithPort
717 self.killSalomeWithPort.killMyPort(self.port)
720 args['shutdown_servers'] = __utils__(args['port'])
724 # run python scripts, passed via --execute option
726 if args.has_key('pyscript'):
727 if args.has_key('gui') and args.has_key('session_gui'):
728 if not args['gui'] or not args['session_gui']:
729 toimport = args['pyscript']
731 command = formatScriptsAndArgs(toimport)
733 proc = subprocess.Popen(command, shell=True)
738 def execScript(script_path):
739 print 'executing', script_path
740 sys.path.insert(0, os.path.dirname(script_path))
741 execfile(script_path,globals())
744 # -----------------------------------------------------------------------------
746 def registerEnv(args, modules_list, modules_root_dir):
748 Register args, modules_list, modules_root_dir in a file
749 for further use, when SALOME is launched embedded in an other application.
751 if sys.platform == "win32":
752 fileEnv = os.getenv('TEMP')
756 fileEnv += os.getenv('USER') + "_" + str(args['port']) \
757 + '_' + args['appname'].upper() + '_env'
758 fenv=open(fileEnv,'w')
759 pickle.dump((args, modules_list, modules_root_dir),fenv)
761 os.environ["SALOME_LAUNCH_CONFIG"] = fileEnv
763 # -----------------------------------------------------------------------------
766 """Salome Launch, when embedded in other application"""
767 fileEnv = os.environ["SALOME_LAUNCH_CONFIG"]
768 fenv=open(fileEnv,'r')
769 args, modules_list, modules_root_dir = pickle.load(fenv)
772 from searchFreePort import searchFreePort
773 searchFreePort(args, 0)
774 clt = useSalome(args, modules_list, modules_root_dir)
777 # -----------------------------------------------------------------------------
780 """Salome launch as a main application"""
783 if not os.getenv("OMNIORB_USER_PATH"):
784 homePath = os.path.realpath(os.path.expanduser('~'))
785 #defaultOmniorbUserPath = os.path.join(homePath, ".salomeConfig/USERS")
786 defaultOmniorbUserPath = homePath
787 if os.getenv("APPLI"):
788 defaultOmniorbUserPath = os.path.join(homePath, os.getenv("APPLI"), "USERS")
789 os.environ["OMNIORB_USER_PATH"] = defaultOmniorbUserPath
793 from salome_utils import getHostName
794 print "runSalome running on %s" % getHostName()
795 args, modules_list, modules_root_dir = setenv.get_config()
799 if args.has_key('save_config'):
800 save_config = args['save_config']
803 if args['wake_up_session']:
807 from searchFreePort import searchFreePort
808 searchFreePort(args, save_config, args.get('useport'))
812 setenv.set_env(args, modules_list, modules_root_dir)
813 clt = useSalome(args, modules_list, modules_root_dir)
816 # -----------------------------------------------------------------------------
818 def foreGround(clt, args):
820 if "session_object" not in args:
822 session = args["session_object"]
824 # Wait until gui is arrived
833 status = session.GetStatSession()
834 gui_detected = status.activeGUI
839 from time import sleep
849 from salome_utils import getPortNumber
850 port = getPortNumber()
853 if sys.platform == "win32":
854 server.CMD = [os.getenv("PYTHONBIN"), "-m", "killSalomeWithPort", "--spy", "%s"%(os.getpid()), "%s"%(port)]
856 server.CMD = ["killSalomeWithPort.py", "--spy", "%s"%(os.getpid()), "%s"%(port)]
858 # os.system("killSalomeWithPort.py --spy %s %s &"%(os.getpid(), port))
864 status = session.GetStatSession()
865 assert status.activeGUI
868 from time import sleep
872 except KeyboardInterrupt:
873 from killSalomeWithPort import killMyPort
883 test = args['gui'] and args['session_gui']
884 test = test or args['wake_up_session']
886 # The next test covers the --pinter option or var PYTHONINSPECT setted
888 test = test and not os.environ.get('PYTHONINSPECT')
890 # The next test covers the python -i $KERNEL_ROOT_DIR/bin/salome/runSalome.py case
893 from ctypes import POINTER, c_int, cast, pythonapi
894 iflag_ptr = cast(pythonapi.Py_InteractiveFlag, POINTER(c_int))
895 test = test and not iflag_ptr.contents.value
899 test = test and os.getenv("SALOME_TEST_MODE", "0") != "1"
900 test = test and args['foreground']
903 foreGround(clt, args)
909 # -----------------------------------------------------------------------------
911 if __name__ == "__main__":