X-Git-Url: http://git.salome-platform.org/gitweb/?a=blobdiff_plain;f=bin%2FrunSalome.py;h=ce89f82697bdc37771fd5109f20e25185e725fd9;hb=03b27bb3323e9cfeb8761be2306a2a57d945a7f5;hp=4348e148b7d22a0cf0b59b3dda766efb9e6e6205;hpb=e0c86149d9bc71a5e7e3f7c688263d358d249a75;p=modules%2Fkernel.git diff --git a/bin/runSalome.py b/bin/runSalome.py index 4348e148b..ce89f8269 100755 --- a/bin/runSalome.py +++ b/bin/runSalome.py @@ -1,16 +1,47 @@ #!/usr/bin/env python +# Copyright (C) 2007-2008 CEA/DEN, EDF R&D, OPEN CASCADE +# +# Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, +# CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS +# +# 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. +# +# 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. +# +# 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 +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +## @package runSalome +# \brief Module that provides services to launch SALOME +# +# -import sys, os, string, glob, time, pickle - -### read launch configure xml file and command line options -import launchConfigureParser -args = launchConfigureParser.args +import sys, os, string, glob, time, pickle, re +import orbmodule +import setenv +from server import * +from launchConfigureParser import verbose +from server import process_id -### kill servers if it is need +# ----------------------------------------------------------------------------- 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: @@ -20,424 +51,811 @@ def killLocalPort(): pass pass -if args['killall']: - killAllPorts() -elif args['portkill']: - killLocalPort() - -# ----------------------------------------------------------------------------- -# -# Fonctions helper pour ajouter des variables d'environnement -# - -def add_path(directory, variable_name): - if not os.environ.has_key(variable_name): - os.environ[variable_name] = "" - pass - if os.path.exists(directory): - for _dir in os.environ[variable_name].split(":"): - if os.path.exists(_dir): - if os.path.samefile(_dir, directory): - return - else: - if os.path.abspath(_dir) == os.path.abspath(directory): - return - pass - if os.environ[variable_name] == "": - os.environ[variable_name] = directory - else: - os.environ[variable_name] = directory + ":" + os.environ[variable_name] - if variable_name == "PYTHONPATH": - sys.path[:0] = [directory] - - -init_time = os.times() -# ----------------------------------------------------------------------------- -# -# Check variables _ROOT_DIR and set list of used modules (without KERNEL) -# Add to the PATH-variables modules' specific paths -# -modules_list = [] -if args.has_key("modules"): - modules_list += args["modules"] -modules_list[:0] = ["KERNEL"] # KERNEL must be last in the list to locate it at the first place in PATH variables -modules_list.reverse() - -modules_root_dir = {} -modules_root_dir_list = [] -python_version="python%d.%d" % sys.version_info[0:2] - -to_remove_list=[] -for module in modules_list : - module_variable=module.upper()+"_ROOT_DIR" - if not os.environ.has_key(module_variable): - print "*******************************************************************************" - print "*" - print "* Environment variable",module_variable,"must be set" - print "* Module", module, "will be not available" - print "*" - print "*******************************************************************************" - to_remove_list.append(module) - continue +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): + cata_path=[] + list_modules = modules_list[:] + list_modules.reverse() + if self.args["gui"] : + list_modules = ["KERNEL", "GUI"] + list_modules + else : + list_modules = ["KERNEL"] + list_modules + for module in list_modules: + module_root_dir=modules_root_dir[module] + module_cata=module+"Catalog.xml" + #print " ", module_cata + if os.path.exists(os.path.join(module_root_dir, + "share",setenv.salome_subdir, + "resources",module.lower(), + module_cata)): + cata_path.extend( + glob.glob(os.path.join(module_root_dir,"share", + setenv.salome_subdir,"resources", + module.lower(),module_cata))) + else: + cata_path.extend( + glob.glob(os.path.join(module_root_dir,"share", + setenv.salome_subdir,"resources", + module_cata))) + pass + 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 + 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 + +# --- + +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): + cata_path=[] + list_modules = modules_list[:] + list_modules.reverse() + if self.args["gui"] : + list_modules = ["GUI"] + list_modules + for module in ["KERNEL"] + list_modules: + if modules_root_dir.has_key(module): + module_root_dir=modules_root_dir[module] + module_cata=module+"Catalog.xml" + #print " ", module_cata + if os.path.exists(os.path.join(module_root_dir, + "share",setenv.salome_subdir, + "resources",module.lower(), + module_cata)): + cata_path.extend( + glob.glob(os.path.join(module_root_dir,"share", + setenv.salome_subdir,"resources", + module.lower(),module_cata))) + else: + cata_path.extend( + glob.glob(os.path.join(module_root_dir,"share", + setenv.salome_subdir,"resources", + module_cata))) + pass + pass + if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']): + self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2 + else: + self.CMD=self.SCMD1 + self.SCMD2 class NotifyServer(Server): - myLogName = os.environ["LOGNAME"] - CMD=['notifd','-c',modules_root_dir["KERNEL"]+'/share/salome/resources/channel.cfg', '-DFactoryIORFileName=/tmp/'+myLogName+'_rdifact.ior', '-DChannelIORFileName=/tmp/'+myLogName+'_rdichan.ior'] - -# ----------------------------------------------------------------------------- -# -# initialisation des variables d'environnement -# - -os.environ["SALOME_trace"]="local" -if args['logger']: - os.environ["SALOME_trace"]="with_logger" - locdir=os.environ['PWD'] - libtracedir=os.path.join(locdir,"libSalomeTrace") - libtrace = os.path.join(modules_root_dir["KERNEL"],"lib",args['appname'],"libSALOMELoggerClient.so.0.0.0") - libtraceln = os.path.join(libtracedir,"libSALOMELocalTrace.so") - aCommand = 'rm -rf ' + libtracedir + "; " - aCommand += 'mkdir ' + libtracedir + "; " - aCommand += 'ln -s ' + libtrace + " " + libtraceln + "; " - aCommand += 'ln -s ' + libtrace + " " + libtraceln + ".0; " - aCommand += 'ln -s ' + libtrace + " " + libtraceln + ".0.0.0; " - os.system(aCommand) - add_path(libtracedir, "LD_LIBRARY_PATH") - -# set environment for SMESH plugins - -if "SMESH" in modules_list: - os.environ["SMESH_MeshersList"]="StdMeshers" - if not os.environ.has_key("SALOME_StdMeshersResources"): - os.environ["SALOME_StdMeshersResources"] = modules_root_dir["SMESH"]+"/share/"+args["appname"]+"/resources" - pass - if args.has_key("SMESH_plugins"): - for plugin in args["SMESH_plugins"]: - if os.environ.has_key(plugin.upper()+"_ROOT_DIR"): - os.environ["SMESH_MeshersList"]=os.environ["SMESH_MeshersList"]+":"+plugin - plugin_root = os.environ[plugin.upper()+"_ROOT_DIR"] - if not os.environ.has_key("SALOME_"+plugin+"Resources"): - os.environ["SALOME_"+plugin+"Resources"] = plugin_root+"/share/"+args["appname"]+"/resources" - add_path(os.path.join(plugin_root,"lib",python_version,"site-packages",args['appname']), "PYTHONPATH") - add_path(os.path.join(plugin_root,"lib",args['appname']), "PYTHONPATH") - add_path(os.path.join(plugin_root,"lib",args['appname']), "LD_LIBRARY_PATH") - add_path(os.path.join(plugin_root,"bin",args['appname']), "PYTHONPATH") - add_path(os.path.join(plugin_root,"bin",args['appname']), "PATH") - pass - pass - -import orbmodule + 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', + ] # # ----------------------------------------------------------------------------- -# def startGUI(): - import SALOME - session=clt.waitNS("/Kernel/Session",SALOME.Session) - - # - # Activation du GUI de Session Server - # - - session.GetInterface() + """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() -# # ----------------------------------------------------------------------------- -# -def startSalome(): +def startSalome(args, modules_list, modules_root_dir): + """Launch all SALOME servers requested by args""" + init_time = os.times() - # - # Lancement Session Loader - # + if verbose(): print "startSalome ", args + + # + # Initialisation ORB and Naming Service + # + + clt=orbmodule.client(args) + # 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='%s/%s'%(home,appli) + pass + file_name= '%s/%s'%(home, args["ns_port_log_file"]) + f = open(file_name, "w") + f.write(os.environ['NSPORT']) + f.close() - if args['gui']: - SessionLoader().run() + # Launch Logger Server (optional) + # and wait until it is registered in naming service + # - # - # Initialisation ORB et Naming Service - # - - clt=orbmodule.client() - - # (non obligatoire) Lancement Logger Server et attente de sa disponibilite dans le naming service - # - - if args['logger']: - LoggerServer().run() - clt.waitLogger("Logger") - - # Notify Server launch - # - NotifyServer().run() - - # - # Lancement Registry Server, attente de la disponibilité du Registry dans le Naming Service - # - if 'registry' not in args['embedded']: - RegistryServer().run() - clt.waitNS("/Registry") - - # - # Lancement Catalog Server, attente de la disponibilité du Catalog Server dans le Naming Service - # - - if 'moduleCatalog' not in args['embedded']: - cataServer=CatalogServer() - cataServer.setpath(modules_list) - cataServer.run() - import SALOME_ModuleCatalog - clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog) - - # - # Lancement SalomeDS Server, attente de la disponibilité du SalomeDS dans le Naming Service - # - - os.environ["CSF_PluginDefaults"]=os.path.join(modules_root_dir["KERNEL"],"share",args['appname'],"resources") - os.environ["CSF_SALOMEDS_ResourcesDefaults"]=os.path.join(modules_root_dir["KERNEL"],"share",args['appname'],"resources") - - if "GEOM" in modules_list: - print "GEOM OCAF Resources" - os.environ["CSF_GEOMDS_ResourcesDefaults"]=os.path.join(modules_root_dir["GEOM"],"share",args['appname'],"resources") - - if 'study' not in args['embedded']: - SalomeDSServer().run() - clt.waitNS("/myStudyManager") - - # - # Lancement Session Server - # - - mySessionServ=SessionServer() - mySessionServ.setpath(modules_list) - mySessionServ.run() - - # - # Attente de la disponibilité du Session Server dans le Naming Service - # - - #import SALOME - #session=clt.waitNS("/Kernel/Session",SALOME.Session) - - if os.getenv("HOSTNAME") == None: - if os.getenv("HOST") == None: - os.environ["HOSTNAME"]="localhost" - else: - os.environ["HOSTNAME"]=os.getenv("HOST") - - theComputer = os.getenv("HOSTNAME") - computerSplitName = theComputer.split('.') - theComputer = computerSplitName[0] - - # - # Lancement Container C++ local, attente de la disponibilité du Container C++ local dans le Naming Service - # + if args['logger']: + myServer=LoggerServer(args) + myServer.run() + clt.waitLogger("Logger") - if 'cppContainer' in args['standalone']: - ContainerCPPServer().run() - clt.waitNS("/Containers/" + theComputer + "/FactoryServer") + # Notify Server launch + # - # - # Lancement Container Python local, attente de la disponibilité du Container Python local dans le Naming Service - # + if sys.platform != "win32": + if verbose(): print "Notify Server to launch" + + myServer=NotifyServer(args,modules_root_dir) + myServer.run() - if 'pyContainer' in args['standalone']: - ContainerPYServer().run() - clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy") + # Launch Session Server (to show splash ASAP) + # - # - # Lancement Container Supervision local, attente de la disponibilité du Container Supervision local dans le Naming Service - # + if args["gui"]: + mySessionServ = SessionServer(args) + mySessionServ.setpath(modules_list,modules_root_dir) + mySessionServ.run() - if 'supervContainer' in args['standalone']: - ContainerSUPERVServer().run() - clt.waitNS("/Containers/" + theComputer + "/SuperVisionContainer") + # + # 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) - end_time = os.times() - print - print "Start SALOME, elapsed time : %5.1f seconds"% (end_time[4] - init_time[4]) + # + # Launch Catalog Server, + # and wait until it is registered in naming service + # - return clt + 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) + 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 "-------------------------------------------------------------" + + 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" + import readline + + return clt -# # ----------------------------------------------------------------------------- -# -process_id = {} -if __name__ == "__main__": +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() + clt = startSalome(args, modules_list, modules_root_dir) except: + import traceback + traceback.print_exc() print print - print "--- erreur au lancement Salome ---" + print "--- Error during Salome launch ---" #print process_id - - filedict='/tmp/'+os.getenv('USER')+"_"+str(args['port'])+'_'+args['appname'].upper()+'_pidict' - #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict' - - - process_ids = [] - try: - fpid=open(filedict, 'r') - process_ids=pickle.load(fpid) - fpid.close() - except: + + 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 - - fpid=open(filedict, 'w') - process_ids.append(process_id) - pickle.dump(process_ids,fpid) - fpid.close() - - print """ + + 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 - killAllPorts() --> kill all sessions + 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. + runSalome, with --killall option, starts with killing + the processes resulting from the previous execution. """%filedict # - # Impression arborescence Naming Service + # Print Naming Service directory list # if clt != None: - print - print " --- registered objects tree in Naming Service ---" - clt.showNS() + 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'] + i = 0 + while i < len( toimport ) : + if toimport[ i ] == 'killall': + clt.showNS() + killAllPorts() + sys.exit(0) + else: + scrname = toimport[ i ] + if len(scrname) > 2 and (len(scrname) - string.rfind(scrname, ".py") == 3): + print 'executing',scrname + sys.path.insert( 0, os.path.dirname(scrname)) + execfile(scrname,globals()) + del sys.path[0] + else: + print 'importing',scrname + doimport = 'import ' + scrname + exec doimport + i = i + 1 + + 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 + +# ----------------------------------------------------------------------------- + +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 + +# ----------------------------------------------------------------------------- + +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'] + searchFreePort(args, save_config) + #setenv.main() + setenv.set_env(args, modules_list, modules_root_dir) + clt = useSalome(args, modules_list, modules_root_dir) + return clt,args + +# ----------------------------------------------------------------------------- + +if __name__ == "__main__": + import user + clt,args = main()