X-Git-Url: http://git.salome-platform.org/gitweb/?a=blobdiff_plain;f=bin%2FrunSalome.py;h=c4b62a01c765399918c2503f85b958a71a437979;hb=45756e00c158937ef73a76dc447317e12172d90c;hp=c61998d896dd61c79d92a7744cee68277ec1d658;hpb=0657026ba3957eb1f47cdc69f704a68a20232058;p=modules%2Fkernel.git diff --git a/bin/runSalome.py b/bin/runSalome.py index c61998d89..c4b62a01c 100755 --- a/bin/runSalome.py +++ b/bin/runSalome.py @@ -1,429 +1,1045 @@ #!/usr/bin/env python - -usage="""USAGE: runSalome.py [options] - -[command line options] : ---help : affichage de l'aide ---gui : lancement du GUI ---logger : redirection des messages dans un fichier ---xterm : les serveurs ouvrent une fenêtre xterm et les messages sont affichés dans cette fenêtre ---modules=module1,module2,... : où modulen est le nom d'un module Salome à charger dans le catalogue ---containers=cpp,python,superv: lancement des containers cpp, python et de supervision - - La variable d'environnement _ROOT_DIR doit etre préalablement - positionnée (modulen doit etre en majuscule). - KERNEL_ROOT_DIR est obligatoire. -""" - -def message(code, msg=''): - if msg: print msg - sys.exit(code) - -import sys,os,string,glob,time,signal,pickle,getopt - -init_time=os.times() -opts, args=getopt.getopt(sys.argv[1:], 'hmglxc:', ['help','modules=','gui','logger','xterm','containers=']) -modules_root_dir={} -process_id={} -liste_modules={} -liste_containers={} -with_gui=0 -with_logger=0 -with_xterm=0 - -with_container_cpp=0 -with_container_python=0 -with_container_superv=0 - -try: - for o, a in opts: - if o in ('-h', '--help'): - print usage - sys.exit(1) - elif o in ('-g', '--gui'): - with_gui=1 - elif o in ('-l', '--logger'): - with_logger=1 - elif o in ('-x', '--xterm'): - with_xterm=1 - elif o in ('-m', '--modules'): - liste_modules = [x.upper() for x in a.split(',')] - elif o in ('-c', '--containers'): - liste_containers = [x.lower() for x in a.split(',')] - for r in liste_containers: - if r not in ('cpp', 'python', 'superv'): - message(1, 'Invalid -c/--containers option: %s' % a) - if 'cpp' in liste_containers: - with_container_cpp=1 - else: - with_container_cpp=0 - if 'python' in liste_containers: - with_container_python=1 - else: - with_container_python=0 - if 'superv' in liste_containers: - with_container_superv=1 - else: - with_container_superv=0 - -except getopt.error, msg: - print usage - sys.exit(1) - -# ----------------------------------------------------------------------------- -# -# Vérification des variables d'environnement -# -try: - kernel_root_dir=os.environ["KERNEL_ROOT_DIR"] - modules_root_dir["KERNEL"]=kernel_root_dir -except: - print usage - sys.exit(1) - -for module in liste_modules : - try: - module=module.upper() - module_root_dir=os.environ[module +"_ROOT_DIR"] - modules_root_dir[module]=module_root_dir - except: - print usage - sys.exit(1) - -# il faut KERNEL en premier dans la liste des modules -# - l'ordre des modules dans le catalogue sera identique -# - la liste des modules presents dans le catalogue est exploitée pour charger les modules CORBA python, -# il faut charger les modules python du KERNEL en premier - -if "KERNEL" in liste_modules:liste_modules.remove("KERNEL") -liste_modules[:0]=["KERNEL"] -#print liste_modules -#print modules_root_dir - -if "SUPERV" in liste_modules:with_container_superv=1 - -import orbmodule - -# ----------------------------------------------------------------------------- +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE # -# Définition des classes d'objets pour le lancement des Server CORBA +# Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, +# CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS # - -class Server: - CMD=[] - if with_xterm: - ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-e'] - else: - ARGS=[] - - def run(self): - args = self.ARGS+self.CMD - #print "args = ", args - pid = os.spawnvp(os.P_NOWAIT, args[0], args) - process_id[pid]=self.CMD - -class CatalogServer(Server): - SCMD1=['SALOME_ModuleCatalog_Server','-common'] - SCMD2=['-personal','${HOME}/Salome/resources/CatalogModulePersonnel.xml'] - - def setpath(self,liste_modules): - cata_path=[] - for module in liste_modules: - module_root_dir=modules_root_dir[module] - module_cata=module+"Catalog.xml" - print " ", module_cata - cata_path.extend(glob.glob(os.path.join(module_root_dir,"share","salome","resources",module_cata))) - self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2 - -class SalomeDSServer(Server): - CMD=['SALOMEDS_Server'] - -class RegistryServer(Server): - CMD=['SALOME_Registry_Server', '--salome_session','theSession'] - -class ContainerCPPServer(Server): - CMD=['SALOME_Container','FactoryServer','-ORBInitRef','NameService=corbaname::localhost'] - -class ContainerPYServer(Server): - CMD=['SALOME_ContainerPy.py','FactoryServerPy','-ORBInitRef','NameService=corbaname::localhost'] - -class ContainerSUPERVServer(Server): - CMD=['SALOME_Container','SuperVisionContainer','-ORBInitRef','NameService=corbaname::localhost'] - -class LoggerServer(Server): - CMD=['SALOME_Logger_Server', 'logger.log'] - -class SessionLoader(Server): - CMD=['SALOME_Session_Loader'] - if with_container_cpp: - CMD=CMD+['CPP'] - if with_container_python: - CMD=CMD+['PY'] - if with_container_superv: - CMD=CMD+['SUPERV'] - if with_gui: - CMD=CMD+['GUI'] - -class SessionServer(Server): - CMD=['SALOME_Session_Server'] - -class NotifyServer(Server): - CMD=['notifd','-c','${KERNEL_ROOT_DIR}/share/salome/resources/channel.cfg -DFactoryIORFileName=/tmp/${LOGNAME}_rdifact.ior -DChannelIORFileName=/tmp/${LOGNAME}_rdichan.ior'] - -# ----------------------------------------------------------------------------- +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License. # -# Fonction d'arrêt de salome +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. # - -def killSalome(): - print "arret des serveurs SALOME" - for pid, cmd in process_id.items(): - print "arret du process %s : %s"% (pid, cmd[0]) - os.kill(pid,signal.SIGKILL) - print "arret du naming service" - os.system("killall -9 omniNames") - -# ----------------------------------------------------------------------------- +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # -# Fonction de test +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -def test(clt): - # create an LifeCycleCORBA instance - import LifeCycleCORBA - lcc = LifeCycleCORBA.LifeCycleCORBA(clt.orb) - med = lcc.FindOrLoadComponent("FactoryServer", "MED") - #pycalc = lcc.FindOrLoadComponent("FactoryServerPy", "CalculatorPy") - -# ----------------------------------------------------------------------------- +## @package runSalome +# \brief Module that provides services to launch SALOME # -# Fonctions helper pour ajouter des variables d'environnement -# - -def add_path(directory): - os.environ["PATH"]=directory + ":" + os.environ["PATH"] -def add_ld_library_path(directory): - os.environ["LD_LIBRARY_PATH"]=directory + ":" + os.environ["LD_LIBRARY_PATH"] +import sys, os, string, glob, time, pickle, re +import orbmodule +import setenv +from launchConfigureParser import verbose +from server import process_id, Server -def add_python_path(directory): - os.environ["PYTHONPATH"]=directory + ":" + os.environ["PYTHONPATH"] - sys.path[:0]=[directory] +if sys.platform == "win32": + SEP = ";" +else: + SEP = ":" # ----------------------------------------------------------------------------- -# -# initialisation des variables d'environnement -# -python_version="python%d.%d" % sys.version_info[0:2] +from killSalome import killAllPorts + +def killLocalPort(): + """ + kill servers from a previous SALOME exection, if needed, + on the CORBA port given in args of runSalome + """ + + from killSalomeWithPort import killMyPort + my_port=str(args['port']) + try: + killMyPort(my_port) + except: + print "problem in killLocalPort()" + pass + pass + +def givenPortKill(port): + """ + kill servers from a previous SALOME exection, if needed, + on the same CORBA port + """ + + from killSalomeWithPort import killMyPort + my_port=port + try: + killMyPort(my_port) + except: + print "problem in LocalPortKill(), killMyPort("< 0: + self.SCMD2+=['--pyscript=%s'%(",".join(self.args['pyscript']))] + + def setpath(self,modules_list,modules_root_dir): + list_modules = modules_list[:] + list_modules.reverse() + if self.args["gui"] : + list_modules = ["KERNEL", "GUI"] + list_modules + else : + list_modules = ["KERNEL"] + list_modules + + cata_path=get_cata_path(list_modules,modules_root_dir) + + if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']): + #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform + self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2 + else: + self.CMD=self.SCMD1 + self.SCMD2 + if self.args.has_key('test'): + self.CMD+=['-test'] + self.args['test'] + elif self.args.has_key('play'): + self.CMD+=['-play'] + self.args['play'] + + if self.args["gdb_session"] or self.args["ddd_session"]: + f = open(".gdbinit4salome", "w") + f.write("set args ") + args = " ".join(self.CMD[1:]) + args = args.replace("(", "\(") + args = args.replace(")", "\)") + f.write(args) + f.write("\n") + f.close() + if self.args["ddd_session"]: + self.CMD = ["ddd", "--command=.gdbinit4salome", self.CMD[0]] + elif self.args["gdb_session"]: + self.CMD = ["xterm", "-e", "gdb", "--command=.gdbinit4salome", self.CMD[0]] + pass + pass + + if self.args["valgrind_session"]: + l = ["valgrind"] + val = os.getenv("VALGRIND_OPTIONS") + if val: + l += val.split() + pass + self.CMD = l + self.CMD + pass + +# --- + +class LauncherServer(Server): + def __init__(self,args): + self.args=args + self.initArgs() + self.SCMD1=['SALOME_LauncherServer'] + self.SCMD2=[] + if args["gui"] : + if 'registry' in self.args['embedded']: + self.SCMD1+=['--with','Registry', + '(','--salome_session','theSession',')'] + if 'moduleCatalog' in self.args['embedded']: + self.SCMD1+=['--with','ModuleCatalog','(','-common'] + self.SCMD2+=['-personal', + '${HOME}/Salome/resources/CatalogModulePersonnel.xml',')'] + if 'study' in self.args['embedded']: + self.SCMD2+=['--with','SALOMEDS','(',')'] + if 'cppContainer' in self.args['embedded']: + self.SCMD2+=['--with','Container','(','FactoryServer',')'] + + def setpath(self,modules_list,modules_root_dir): + list_modules = modules_list[:] + list_modules.reverse() + if self.args["gui"] : + list_modules = ["KERNEL", "GUI"] + list_modules + else : + list_modules = ["KERNEL"] + list_modules + + cata_path=get_cata_path(list_modules,modules_root_dir) + + if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']): + #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform + self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2 + else: + self.CMD=self.SCMD1 + self.SCMD2 - # - # Lancement Container Supervision local - # +class NotifyServer(Server): + def __init__(self,args,modules_root_dir): + self.args=args + self.initArgs() + self.modules_root_dir=modules_root_dir + myLogName = os.environ["LOGNAME"] + self.CMD=['notifd','-c', + self.modules_root_dir["KERNEL"] +'/share/salome/resources/kernel/channel.cfg', + '-DFactoryIORFileName=/tmp/'+myLogName+'_rdifact.ior', + '-DChannelIORFileName=/tmp/'+myLogName+'_rdichan.ior', + '-DReportLogFile=/tmp/'+myLogName+'_notifd.report', + '-DDebugLogFile=/tmp/'+myLogName+'_notifd.debug', + ] - ContainerSUPERVServer().run() +# +# ----------------------------------------------------------------------------- - # - # Attente de la disponibilité du Container Supervision local dans le Naming Service - # +def startGUI(clt): + """Salome Session Graphic User Interface activation""" + import Engines + import SALOME + import SALOMEDS + import SALOME_ModuleCatalog + import SALOME_Session_idl + session=clt.waitNS("/Kernel/Session",SALOME.Session) + session.GetInterface() + +# ----------------------------------------------------------------------------- - clt.waitNS("/Containers/" + theComputer + "/SuperVisionContainer") +def startSalome(args, modules_list, modules_root_dir): + """Launch all SALOME servers requested by args""" + init_time = os.times() + + if verbose(): print "startSalome ", args + + # + # Set server launch command + # + if args.has_key('server_launch_mode'): + Server.set_server_launch_mode(args['server_launch_mode']) + + # + # Wake up session option + # + if args['wake_up_session']: + if "OMNIORB_CONFIG" not in os.environ: + from salome_utils import generateFileName + home = os.getenv("HOME") + appli = os.getenv("APPLI") + kwargs={} + if appli is not None: + home = os.path.join(home, appli,"USERS") + kwargs["with_username"] = True + pass + last_running_config = generateFileName(home, prefix="omniORB", + suffix="last", + extension="cfg", + hidden=True, + **kwargs) + os.environ['OMNIORB_CONFIG'] = last_running_config + pass + pass + + # + # Initialisation ORB and Naming Service + # + + clt=orbmodule.client(args) + + # + # Wake up session option + # + if args['wake_up_session']: + import Engines + import SALOME + import SALOMEDS + import SALOME_ModuleCatalog + import SALOME_Session_idl + session = clt.waitNS("/Kernel/Session",SALOME.Session) + status = session.GetStatSession() + if status.activeGUI: + from salome_utils import getPortNumber + port = getPortNumber() + msg = "Warning :" + msg += "\n" + msg += "Session GUI for port number %s is already active."%(port) + msg += "\n" + msg += "If you which to wake up another session," + msg += "\n" + msg += "please use variable OMNIORB_CONFIG" + msg += "\n" + msg += "to get the correct session object in naming service." + sys.stdout.write(msg+"\n") + sys.stdout.flush() + return clt + session.GetInterface() + args["session_object"] = session + return clt + + # Save Naming service port name into + # the file args["ns_port_log_file"] + if args.has_key('ns_port_log_file'): + home = os.environ['HOME'] + appli= os.environ.get("APPLI") + if appli is not None: + home = os.path.join(home, appli, "USERS") + file_name = os.path.join(home, args["ns_port_log_file"]) + f = open(file_name, "w") + f.write(os.environ['NSPORT']) + f.close() + + # Launch Logger Server (optional) + # and wait until it is registered in naming service + # + + if args['logger']: + myServer=LoggerServer(args) + myServer.run() + clt.waitLogger("Logger") + + # Notify Server launch + # + + if sys.platform != "win32": + if verbose(): print "Notify Server to launch" + + myServer=NotifyServer(args,modules_root_dir) + myServer.run() + + # Launch Session Server (to show splash ASAP) + # + + if args["gui"]: + mySessionServ = SessionServer(args,args['modules'],modules_root_dir) + mySessionServ.setpath(modules_list,modules_root_dir) + mySessionServ.run() + + # + # Launch Registry Server, + # and wait until it is registered in naming service + # + + if ('registry' not in args['embedded']) | (args["gui"] == 0) : + myServer=RegistryServer(args) + myServer.run() + if sys.platform == "win32": + clt.waitNS("/Registry") + else: + clt.waitNSPID("/Registry",myServer.PID) + + # + # Launch Catalog Server, + # and wait until it is registered in naming service + # + + if ('moduleCatalog' not in args['embedded']) | (args["gui"] == 0): + cataServer=CatalogServer(args) + cataServer.setpath(modules_list,modules_root_dir) + cataServer.run() + import SALOME_ModuleCatalog + if sys.platform == "win32": + clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog) + else: + clt.waitNSPID("/Kernel/ModulCatalog",cataServer.PID,SALOME_ModuleCatalog.ModuleCatalog) + + # + # Launch SalomeDS Server, + # and wait until it is registered in naming service + # + + #print "ARGS = ",args + if ('study' not in args['embedded']) | (args["gui"] == 0): + print "RunStudy" + myServer=SalomeDSServer(args) + myServer.run() + if sys.platform == "win32": + clt.waitNS("/myStudyManager") + else: + clt.waitNSPID("/myStudyManager",myServer.PID) + + # + # Launch LauncherServer + # + + myCmServer = LauncherServer(args) + myCmServer.setpath(modules_list,modules_root_dir) + myCmServer.run() + + # + # Launch ConnectionManagerServer + # + + myConnectionServer = ConnectionManagerServer(args) + myConnectionServer.run() + + + from Utils_Identity import getShortHostName + + if os.getenv("HOSTNAME") == None: + if os.getenv("HOST") == None: + os.environ["HOSTNAME"]=getShortHostName() + else: + os.environ["HOSTNAME"]=os.getenv("HOST") + + theComputer = getShortHostName() + + # + # Launch local C++ Container (FactoryServer), + # and wait until it is registered in naming service + # + + if ('cppContainer' in args['standalone']) | (args["gui"] == 0) : + myServer=ContainerCPPServer(args) + myServer.run() + if sys.platform == "win32": + clt.waitNS("/Containers/" + theComputer + "/FactoryServer") + else: + clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID) + + # + # Launch local Python Container (FactoryServerPy), + # and wait until it is registered in naming service + # + + if 'pyContainer' in args['standalone']: + myServer=ContainerPYServer(args) + myServer.run() + if sys.platform == "win32": + clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy") + else: + clt.waitNSPID("/Containers/" + theComputer + "/FactoryServerPy",myServer.PID) + + # + # Wait until Session Server is registered in naming service + # + + if args["gui"]: +##---------------- + import Engines + import SALOME + import SALOMEDS + import SALOME_ModuleCatalog + import SALOME_Session_idl + if sys.platform == "win32": + session=clt.waitNS("/Kernel/Session",SALOME.Session) + else: + session=clt.waitNSPID("/Kernel/Session",mySessionServ.PID,SALOME.Session) + args["session_object"] = session + end_time = os.times() + if verbose(): print + print "Start SALOME, elapsed time : %5.1f seconds"% (end_time[4] + - init_time[4]) + + # ASV start GUI without Loader + #if args['gui']: + # session.GetInterface() + + # + # additionnal external python interpreters + # + nbaddi=0 + + try: + if 'interp' in args: + nbaddi = args['interp'] + except: + import traceback + traceback.print_exc() + print "-------------------------------------------------------------" + print "-- to get an external python interpreter:runSalome --interp=1" + print "-------------------------------------------------------------" + + if verbose(): print "additional external python interpreters: ", nbaddi + if nbaddi: + for i in range(nbaddi): + print "i=",i + anInterp=InterpServer(args) + anInterp.run() + + # set PYTHONINSPECT variable (python interpreter in interactive mode) + if args['pinter']: + os.environ["PYTHONINSPECT"]="1" + try: + import readline + except ImportError: + pass + + return clt +# ----------------------------------------------------------------------------- - # - # Activation du GUI de Session Server - # - - #session.GetInterface() +def useSalome(args, modules_list, modules_root_dir): + """ + Launch all SALOME servers requested by args, + save list of process, give info to user, + show registered objects in Naming Service. + """ + global process_id + + clt=None + try: + clt = startSalome(args, modules_list, modules_root_dir) + except: + import traceback + traceback.print_exc() + print + print + print "--- Error during Salome launch ---" + + #print process_id + + from addToKillList import addToKillList + from killSalomeWithPort import getPiDict + + filedict = getPiDict(args['port']) + for pid, cmd in process_id.items(): + addToKillList(pid, cmd, args['port']) + pass + + if verbose(): print """ + Saving of the dictionary of Salome processes in %s + To kill SALOME processes from a console (kill all sessions from all ports): + python killSalome.py + To kill SALOME from the present interpreter, if it is not closed : + killLocalPort() --> kill this session + (use CORBA port from args of runSalome) + givenPortKill(port) --> kill a specific session with given CORBA port + killAllPorts() --> kill all sessions + + runSalome, with --killall option, starts with killing + the processes resulting from the previous execution. + """%filedict + + # + # Print Naming Service directory list + # + + if clt != None: + if verbose(): + print + print " --- registered objects tree in Naming Service ---" + clt.showNS() + pass + + if not args['gui'] or not args['session_gui']: + if args['shutdown_servers']: + class __utils__(object): + def __init__(self, port): + self.port = port + import killSalomeWithPort + self.killSalomeWithPort = killSalomeWithPort + return + def __del__(self): + self.killSalomeWithPort.killMyPort(self.port) + return + pass + args['shutdown_servers'] = __utils__(args['port']) + pass + pass + + # run python scripts, passed via --execute option + toimport = [] + if args.has_key('pyscript'): + if args.has_key('gui') and args.has_key('session_gui'): + if not args['gui'] or not args['session_gui']: + toimport = args['pyscript'] + + for srcname in toimport : + if srcname == 'killall': + clt.showNS() + killAllPorts() + sys.exit(0) + else: + if os.path.isabs(srcname): + if os.path.exists(srcname): + execScript(srcname) + elif os.path.exists(srcname+".py"): + execScript(srcname+".py") + else: + print "Can't execute file %s" % srcname + pass + else: + found = False + for path in [os.getcwd()] + sys.path: + if os.path.exists(os.path.join(path,srcname)): + execScript(os.path.join(path,srcname)) + found = True + break + elif os.path.exists(os.path.join(path,srcname+".py")): + execScript(os.path.join(path,srcname+".py")) + found = True + break + pass + if not found: + print "Can't execute file %s" % srcname + pass + pass + pass + pass + pass + return clt + +def execScript(script_path): + print 'executing', script_path + sys.path.insert(0, os.path.dirname(script_path)) + execfile(script_path,globals()) + del sys.path[0] - end_time = os.times() - print - print "Start SALOME, elpased time : %5.1f seconds"% (end_time[4] - init_time[4]) +# ----------------------------------------------------------------------------- - return clt +def registerEnv(args, modules_list, modules_root_dir): + """ + Register args, modules_list, modules_root_dir in a file + for further use, when SALOME is launched embedded in an other application. + """ + if sys.platform == "win32": + fileEnv = os.getenv('TEMP') + else: + fileEnv = '/tmp/' + + fileEnv += os.getenv('USER') + "_" + str(args['port']) \ + + '_' + args['appname'].upper() + '_env' + fenv=open(fileEnv,'w') + pickle.dump((args, modules_list, modules_root_dir),fenv) + fenv.close() + os.environ["SALOME_LAUNCH_CONFIG"] = fileEnv -# # ----------------------------------------------------------------------------- -# - -clt=None -try: - clt = startSalome() -except: - print - print - print "--- erreur au lancement Salome ---" -#print process_id +def searchFreePort(args, save_config=1): + print "Searching for a free port for naming service:", + # + if sys.platform == "win32": + tmp_file = os.getenv('TEMP'); + else: + tmp_file = '/tmp' + tmp_file = os.path.join(tmp_file, '.netstat_%s'%os.getpid()) + # + ###status = os.system("netstat -ltn | grep -E :%s > /dev/null 2>&1"%(NSPORT)) + os.system( "netstat -a -n > %s" % tmp_file ); + f = open( tmp_file, 'r' ); + ports = f.readlines(); + f.close(); + os.remove( tmp_file ); + # + def portIsUsed(port, data): + regObj = re.compile( ".*tcp.*:([0-9]+).*:.*listen", re.IGNORECASE ); + for item in data: + try: + p = int(regObj.match(item).group(1)) + if p == port: return True + pass + except: + pass + pass + return False + # + NSPORT=2810 + limit=NSPORT+100 + # + while 1: + if not portIsUsed(NSPORT, ports): + print "%s - OK"%(NSPORT) + # + from salome_utils import generateFileName, getHostName + hostname = getHostName() + # + home = os.getenv("HOME") + appli = os.getenv("APPLI") + kwargs={} + if appli is not None: + home = os.path.join(home, appli,"USERS") + kwargs["with_username"]=True + # + omniorb_config = generateFileName(home, prefix="omniORB", + extension="cfg", + hidden=True, + with_hostname=True, + with_port=NSPORT, + **kwargs) + orbdata = [] + initref = "NameService=corbaname::%s:%s"%(hostname, NSPORT) + from omniORB import CORBA + if CORBA.ORB_ID == "omniORB4": + orbdata.append("InitRef = %s"%(initref)) + orbdata.append("giopMaxMsgSize = 2097152000 # 2 GBytes") + orbdata.append("traceLevel = 0 # critical errors only") + else: + orbdata.append("ORBInitRef %s"%(initref)) + orbdata.append("ORBgiopMaxMsgSize = 2097152000 # 2 GBytes") + orbdata.append("ORBtraceLevel = 0 # critical errors only") + pass + orbdata.append("") + f = open(omniorb_config, "w") + f.write("\n".join(orbdata)) + f.close() + # + os.environ['OMNIORB_CONFIG'] = omniorb_config + os.environ['NSPORT'] = "%s"%(NSPORT) + os.environ['NSHOST'] = "%s"%(hostname) + args['port'] = os.environ['NSPORT'] + # + if save_config: + last_running_config = generateFileName(home, prefix="omniORB", + suffix="last", + extension="cfg", + hidden=True, + **kwargs) + try: + if sys.platform == "win32": + import shutil + shutil.copyfile(omniorb_config, last_running_config) + else: + try: + os.remove(last_running_config) + except OSError: + pass + os.symlink(omniorb_config, last_running_config) + pass + pass + except: + pass + break + print "%s"%(NSPORT), + if NSPORT == limit: + msg = "\n" + msg += "Can't find a free port to launch omniNames\n" + msg += "Try to kill the running servers and then launch SALOME again.\n" + raise RuntimeError, msg + NSPORT=NSPORT+1 + pass + return + +# ----------------------------------------------------------------------------- +def no_main(): + """Salome Launch, when embedded in other application""" + fileEnv = os.environ["SALOME_LAUNCH_CONFIG"] + fenv=open(fileEnv,'r') + args, modules_list, modules_root_dir = pickle.load(fenv) + fenv.close() + kill_salome(args) + searchFreePort(args, 0) + clt = useSalome(args, modules_list, modules_root_dir) + return clt -filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict' -#filedict='/tmp/'+os.getlogin()+'_SALOME_pidict' +# ----------------------------------------------------------------------------- -fpid=open(filedict, 'w') -pickle.dump(process_id,fpid) -fpid.close() +def main(): + """Salome launch as a main application""" + from salome_utils import getHostName + print "runSalome running on %s" % getHostName() + args, modules_list, modules_root_dir = setenv.get_config() + kill_salome(args) + save_config = True + if args.has_key('save_config'): + save_config = args['save_config'] + # -- + test = True + if args['wake_up_session']: + test = False + pass + if test: + searchFreePort(args, save_config) + pass + # -- + #setenv.main() + setenv.set_env(args, modules_list, modules_root_dir) + clt = useSalome(args, modules_list, modules_root_dir) + return clt,args -print -print "Sauvegarde du dictionnaire des process dans ", filedict -print "Pour tuer les process SALOME, executer : python killSalome.py depuis" -print "une console, ou bien killSalome() depuis le present interpreteur," -print "s'il n'est pas fermé." -print "runSalome commence par tuer les process restants d'une execution précédente." +# ----------------------------------------------------------------------------- -# -# Impression arborescence Naming Service -# +def foreGround(clt, args): + # -- + if "session_object" not in args: + return + session = args["session_object"] + # -- + # Wait until gui is arrived + # tmax = nbtot * dt + # -- + gui_detected = False + dt = 0.1 + nbtot = 100 + nb = 0 + while 1: + try: + status = session.GetStatSession() + gui_detected = status.activeGUI + except: + pass + if gui_detected: + break + from time import sleep + sleep(dt) + nb += 1 + if nb == nbtot: + break + pass + # -- + if not gui_detected: + return + # -- + from salome_utils import getPortNumber + port = getPortNumber() + # -- + server = Server({}) + if sys.platform == "win32": + server.CMD = [os.getenv("PYTHONBIN"), "-m", "killSalomeWithPort", "--spy", "%s"%(os.getpid()), "%s"%(port)] + else: + server.CMD = ["killSalomeWithPort.py", "--spy", "%s"%(os.getpid()), "%s"%(port)] + server.run() + # os.system("killSalomeWithPort.py --spy %s %s &"%(os.getpid(), port)) + # -- + dt = 1.0 + try: + while 1: + try: + status = session.GetStatSession() + assert status.activeGUI + except: + break + from time import sleep + sleep(dt) + pass + pass + except KeyboardInterrupt: + from killSalomeWithPort import killMyPort + killMyPort(port) + pass + return -if clt != None: - print - print " --- registered objects tree in Naming Service ---" - clt.showNS() +# ----------------------------------------------------------------------------- +if __name__ == "__main__": + import user + clt,args = main() + # -- + test = args['gui'] and args['session_gui'] + test = test or args['wake_up_session'] + # -- + # The next test covers the --pinter option or var PYTHONINSPECT setted + # -- + test = test and not os.environ.get('PYTHONINSPECT') + # -- + # The next test covers the python -i $KERNEL_ROOT_DIR/bin/salome/runSalome.py case + # -- + try: + from ctypes import POINTER, c_int, cast, pythonapi + iflag_ptr = cast(pythonapi.Py_InteractiveFlag, POINTER(c_int)) + test = test and not iflag_ptr.contents.value + except: + pass + # -- + test = test and os.getenv("SALOME_TEST_MODE", "0") != "1" + test = test and args['foreground'] + # -- + if test: + foreGround(clt, args) + pass + # -- + pass