Back to index

salome-kernel  6.5.0
runSalome.py
Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 #  -*- coding: iso-8859-1 -*-
00003 # Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
00004 #
00005 # Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
00006 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
00007 #
00008 # This library is free software; you can redistribute it and/or
00009 # modify it under the terms of the GNU Lesser General Public
00010 # License as published by the Free Software Foundation; either
00011 # version 2.1 of the License.
00012 #
00013 # This library is distributed in the hope that it will be useful,
00014 # but WITHOUT ANY WARRANTY; without even the implied warranty of
00015 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00016 # Lesser General Public License for more details.
00017 #
00018 # You should have received a copy of the GNU Lesser General Public
00019 # License along with this library; if not, write to the Free Software
00020 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
00021 #
00022 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
00023 #
00024 
00025 ## @package runSalome
00026 # \brief Module that provides services to launch SALOME
00027 #
00028 
00029 import sys, os, string, glob, time, pickle, re
00030 import orbmodule
00031 import setenv
00032 from launchConfigureParser import verbose
00033 from server import process_id, Server
00034 
00035 if sys.platform == "win32":
00036     SEP = ";"
00037 else:
00038     SEP = ":"
00039 
00040 # -----------------------------------------------------------------------------
00041 
00042 from killSalome import killAllPorts
00043 
00044 def killLocalPort():
00045     """
00046     kill servers from a previous SALOME exection, if needed,
00047     on the CORBA port given in args of runSalome
00048     """
00049     
00050     from killSalomeWithPort import killMyPort
00051     my_port=str(args['port'])
00052     try:
00053         killMyPort(my_port)
00054     except:
00055         print "problem in killLocalPort()"
00056         pass
00057     pass
00058     
00059 def givenPortKill(port):
00060     """
00061     kill servers from a previous SALOME exection, if needed,
00062     on the same CORBA port
00063     """
00064     
00065     from killSalomeWithPort import killMyPort
00066     my_port=port
00067     try:
00068         killMyPort(my_port)
00069     except:
00070         print "problem in LocalPortKill(), killMyPort("<<port<<")"
00071         pass
00072     pass
00073 
00074 def kill_salome(args):
00075     """
00076     Kill servers from previous SALOME executions, if needed;
00077     depending on args 'killall' or 'portkill', kill all executions,
00078     or only execution on the same CORBA port
00079     """
00080 
00081     if args['killall']:
00082         killAllPorts()
00083     elif args['portkill']:
00084         givenPortKill(str(args['port']))
00085 
00086 # -----------------------------------------------------------------------------
00087 #
00088 # Class definitions to launch CORBA Servers
00089 #
00090 
00091 class InterpServer(Server):
00092     def __init__(self,args):
00093         self.args=args
00094         if sys.platform != "win32":
00095           env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
00096           self.CMD=['xterm', '-e']+ env_ld_library_path + ['python']
00097         else:
00098           self.CMD=['cmd', '/c', 'start cmd.exe', '/K', 'python']
00099        
00100     def run(self):
00101         global process_id
00102         command = self.CMD
00103         print "INTERPSERVER::command = ", command
00104         if sys.platform == "win32":
00105           import win32pm
00106           pid = win32pm.spawnpid( string.join(command, " "),'-nc' )
00107         else:
00108           pid = os.spawnvp(os.P_NOWAIT, command[0], command)
00109         process_id[pid]=self.CMD
00110         self.PID = pid
00111 
00112 # ---
00113 
00114 def get_cata_path(list_modules,modules_root_dir):
00115     """Build a list of catalog paths (cata_path) to initialize the ModuleCatalog server
00116     """
00117     modules_cata={}
00118     cata_path=[]
00119 
00120     for module in list_modules:
00121         if modules_root_dir.has_key(module):
00122             module_root_dir=modules_root_dir[module]
00123             module_cata=module+"Catalog.xml"
00124             cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources",module.lower(), module_cata)
00125 
00126             if os.path.exists(cata_file):
00127                 cata_path.append(cata_file)
00128                 modules_cata[module]=cata_file
00129             else:
00130                 cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources", module_cata)
00131                 if os.path.exists(cata_file):
00132                     cata_path.append(cata_file)
00133                     modules_cata[module]=cata_file
00134 
00135     for path in os.getenv("SALOME_CATALOGS_PATH","").split(SEP):
00136         if os.path.exists(path):
00137             for cata_file in glob.glob(os.path.join(path,"*Catalog.xml")):
00138                 module_name= os.path.basename(cata_file)[:-11]
00139                 if not modules_cata.has_key(module_name):
00140                     cata_path.append(cata_file)
00141                     modules_cata[module_name]=cata_file
00142 
00143     return cata_path
00144 
00145 
00146 
00147 class CatalogServer(Server):
00148     def __init__(self,args):
00149         self.args=args
00150         self.initArgs()
00151         self.SCMD1=['SALOME_ModuleCatalog_Server','-common']
00152         self.SCMD2=[]
00153         home_dir=os.getenv('HOME')
00154         if home_dir is not None:
00155             self.SCMD2=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')] 
00156 
00157     def setpath(self,modules_list,modules_root_dir):
00158         list_modules = modules_list[:]
00159         list_modules.reverse()
00160         if self.args["gui"] :
00161             list_modules = ["KERNEL", "GUI"] + list_modules
00162         else :
00163             list_modules = ["KERNEL"] + list_modules
00164 
00165         cata_path=get_cata_path(list_modules,modules_root_dir)
00166 
00167         self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
00168 
00169 # ---
00170 
00171 class SalomeDSServer(Server):
00172     def __init__(self,args):
00173         self.args=args
00174         self.initArgs()
00175         self.CMD=['SALOMEDS_Server']
00176 
00177 # ---
00178 
00179 class ConnectionManagerServer(Server):
00180     def __init__(self,args):
00181         self.args=args
00182         self.initArgs()
00183         self.CMD=['SALOME_ConnectionManagerServer']
00184 
00185 # ---
00186 
00187 class RegistryServer(Server):
00188     def __init__(self,args):
00189         self.args=args
00190         self.initArgs()
00191         self.CMD=['SALOME_Registry_Server', '--salome_session','theSession']
00192 
00193 # ---
00194 
00195 class ContainerCPPServer(Server):
00196     def __init__(self,args):
00197         self.args=args
00198         self.initArgs()
00199         self.CMD=['SALOME_Container','FactoryServer']
00200 
00201 # ---
00202 
00203 class ContainerPYServer(Server):
00204     def __init__(self,args):
00205         self.args=args
00206         self.initArgs()
00207         if sys.platform == "win32":
00208           self.CMD=[os.environ["PYTHONBIN"], '\"'+os.environ["KERNEL_ROOT_DIR"] + '/bin/salome/SALOME_ContainerPy.py'+'\"','FactoryServerPy']
00209         else:
00210           self.CMD=['SALOME_ContainerPy.py','FactoryServerPy']
00211 
00212 # ---
00213 
00214 class LoggerServer(Server):
00215     def __init__(self,args):
00216         self.args=args
00217         self.initArgs()
00218         from salome_utils import generateFileName
00219         if sys.platform == "win32": dirpath = os.environ["HOME"]
00220         else:                       dirpath = "/tmp"
00221         logfile = generateFileName( dirpath,
00222                                     prefix="logger",
00223                                     extension="log",
00224                                     with_username=True,
00225                                     with_hostname=True,
00226                                     with_port=True)
00227         print "==========================================================="
00228         print "Logger server: put log to the file:"
00229         print logfile
00230         print "==========================================================="
00231         self.CMD=['SALOME_Logger_Server', logfile]
00232         pass
00233     pass # end of LoggerServer class
00234 
00235 # ---
00236 
00237 class SessionServer(Server):
00238     def __init__(self,args,modules_list,modules_root_dir):
00239         self.args = args.copy()
00240         # Bug 11512 (Problems with runSalome --xterm on Mandrake and Debian Sarge)
00241         #self.args['xterm']=0
00242         #
00243         self.initArgs()
00244         self.SCMD1=['SALOME_Session_Server']
00245         self.SCMD2=[]
00246         if 'registry' in self.args['embedded']:
00247             self.SCMD1+=['--with','Registry',
00248                          '(','--salome_session','theSession',')']
00249         if 'moduleCatalog' in self.args['embedded']:
00250             self.SCMD1+=['--with','ModuleCatalog','(','-common']
00251             home_dir=os.getenv('HOME')
00252             if home_dir is not None:
00253                 self.SCMD2+=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')] 
00254             self.SCMD2+=[')']
00255         if 'study' in self.args['embedded']:
00256             self.SCMD2+=['--with','SALOMEDS','(',')']
00257         if 'cppContainer' in self.args['embedded']:
00258             self.SCMD2+=['--with','Container','(','FactoryServer',')']
00259         if 'SalomeAppEngine' in self.args['embedded']:
00260             self.SCMD2+=['--with','SalomeAppEngine','(',')']
00261             
00262         if 'cppContainer' in self.args['standalone'] or 'cppContainer' in self.args['embedded']:
00263             self.SCMD2+=['CPP']
00264         if 'pyContainer' in self.args['standalone'] or 'pyContainer' in self.args['embedded']:
00265             self.SCMD2+=['PY']
00266         if self.args['gui']:
00267             session_gui = True
00268             if self.args.has_key('session_gui'):
00269                 session_gui = self.args['session_gui']
00270             if session_gui:
00271                 self.SCMD2+=['GUI']
00272                 if self.args['splash']:
00273                     self.SCMD2+=['SPLASH']
00274                     pass
00275                 if self.args['study_hdf'] is not None:
00276                     self.SCMD2+=['--study-hdf=%s'%self.args['study_hdf']]
00277                     pass
00278                 pass
00279             pass
00280         if self.args['noexcepthandler']:
00281             self.SCMD2+=['noexcepthandler']
00282         if self.args.has_key('user_config'):
00283             self.SCMD2+=['--resources=%s'%self.args['user_config']]
00284         if self.args.has_key('modules'):
00285             list_modules = []
00286             #keep only modules with GUI
00287             for m in modules_list:
00288               if m not in modules_root_dir:
00289                 list_modules.insert(0,m)
00290               else:
00291                 fr1 = os.path.join(modules_root_dir[m],"share","salome","resources",m.lower(),"SalomeApp.xml")
00292                 fr2 = os.path.join(modules_root_dir[m],"share","salome","resources","SalomeApp.xml")
00293                 if os.path.exists(fr1) or os.path.exists(fr2):
00294                   list_modules.insert(0,m)
00295             list_modules.reverse()
00296             self.SCMD2+=['--modules (%s)' % ":".join(list_modules)]
00297 
00298         if self.args.has_key('pyscript') and len(self.args['pyscript']) > 0:
00299             self.SCMD2+=['--pyscript=%s'%(",".join(self.args['pyscript']))]
00300 
00301     def setpath(self,modules_list,modules_root_dir):
00302         list_modules = modules_list[:]
00303         list_modules.reverse()
00304         if self.args["gui"] :
00305             list_modules = ["KERNEL", "GUI"] + list_modules
00306         else :
00307             list_modules = ["KERNEL"] + list_modules
00308 
00309         cata_path=get_cata_path(list_modules,modules_root_dir)
00310 
00311         if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
00312             #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
00313             self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
00314         else:
00315             self.CMD=self.SCMD1 + self.SCMD2
00316         if self.args.has_key('test'):
00317             self.CMD+=['-test'] + self.args['test']
00318         elif self.args.has_key('play'):
00319             self.CMD+=['-play'] + self.args['play']
00320 
00321         if self.args["gdb_session"] or self.args["ddd_session"]:
00322             f = open(".gdbinit4salome", "w")
00323             f.write("set args ")
00324             args = " ".join(self.CMD[1:])
00325             args = args.replace("(", "\(")
00326             args = args.replace(")", "\)")
00327             f.write(args)
00328             f.write("\n")
00329             f.close()
00330             if self.args["ddd_session"]:
00331                 self.CMD = ["ddd", "--command=.gdbinit4salome", self.CMD[0]]
00332             elif self.args["gdb_session"]:
00333                 self.CMD = ["xterm", "-e", "gdb", "--command=.gdbinit4salome", self.CMD[0]]
00334                 pass
00335             pass
00336         
00337         if self.args["valgrind_session"]:
00338             l = ["valgrind"]
00339             val = os.getenv("VALGRIND_OPTIONS")
00340             if val:
00341                 l += val.split()
00342                 pass
00343             self.CMD = l + self.CMD
00344             pass
00345         
00346 # ---
00347 
00348 class LauncherServer(Server):
00349     def __init__(self,args):
00350         self.args=args
00351         self.initArgs()
00352         self.SCMD1=['SALOME_LauncherServer']
00353         self.SCMD2=[]
00354         if args["gui"] :
00355             if 'registry' in self.args['embedded']:
00356                 self.SCMD1+=['--with','Registry',
00357                              '(','--salome_session','theSession',')']
00358             if 'moduleCatalog' in self.args['embedded']:
00359                 self.SCMD1+=['--with','ModuleCatalog','(','-common']
00360                 self.SCMD2+=['-personal',
00361                              '${HOME}/Salome/resources/CatalogModulePersonnel.xml',')']
00362             if 'study' in self.args['embedded']:
00363                 self.SCMD2+=['--with','SALOMEDS','(',')']
00364             if 'cppContainer' in self.args['embedded']:
00365                 self.SCMD2+=['--with','Container','(','FactoryServer',')']
00366 
00367     def setpath(self,modules_list,modules_root_dir):
00368         list_modules = modules_list[:]
00369         list_modules.reverse()
00370         if self.args["gui"] :
00371             list_modules = ["KERNEL", "GUI"] + list_modules
00372         else :
00373             list_modules = ["KERNEL"] + list_modules
00374 
00375         cata_path=get_cata_path(list_modules,modules_root_dir)
00376 
00377         if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
00378             #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
00379             self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
00380         else:
00381             self.CMD=self.SCMD1 + self.SCMD2
00382 
00383 class NotifyServer(Server):
00384     def __init__(self,args,modules_root_dir):
00385         self.args=args
00386         self.initArgs()
00387         self.modules_root_dir=modules_root_dir
00388         myLogName = os.environ["LOGNAME"]
00389         self.CMD=['notifd','-c',
00390                   self.modules_root_dir["KERNEL"] +'/share/salome/resources/kernel/channel.cfg',
00391                   '-DFactoryIORFileName=/tmp/'+myLogName+'_rdifact.ior',
00392                   '-DChannelIORFileName=/tmp/'+myLogName+'_rdichan.ior',
00393                   '-DReportLogFile=/tmp/'+myLogName+'_notifd.report',
00394                   '-DDebugLogFile=/tmp/'+myLogName+'_notifd.debug',
00395                   ]
00396 
00397 #
00398 # -----------------------------------------------------------------------------
00399 
00400 def startGUI(clt):
00401     """Salome Session Graphic User Interface activation"""
00402     import Engines
00403     import SALOME
00404     import SALOMEDS
00405     import SALOME_ModuleCatalog
00406     import SALOME_Session_idl
00407     session=clt.waitNS("/Kernel/Session",SALOME.Session)
00408     session.GetInterface()
00409   
00410 # -----------------------------------------------------------------------------
00411 
00412 def startSalome(args, modules_list, modules_root_dir):
00413     """Launch all SALOME servers requested by args"""
00414     init_time = os.times()
00415 
00416     if verbose(): print "startSalome ", args
00417     
00418     #
00419     # Set server launch command
00420     #
00421     if args.has_key('server_launch_mode'):
00422         Server.set_server_launch_mode(args['server_launch_mode'])
00423     
00424     #
00425     # Wake up session option
00426     #
00427     if args['wake_up_session']:
00428         if "OMNIORB_CONFIG" not in os.environ:
00429             from salome_utils import generateFileName
00430             home  = os.getenv("HOME")
00431             appli = os.getenv("APPLI")
00432             kwargs={}
00433             if appli is not None: 
00434                 home = os.path.join(home, appli,"USERS")
00435                 kwargs["with_username"] = True
00436                 pass
00437             last_running_config = generateFileName(home, prefix="omniORB",
00438                                                    suffix="last",
00439                                                    extension="cfg",
00440                                                    hidden=True,
00441                                                    **kwargs)
00442             os.environ['OMNIORB_CONFIG'] = last_running_config
00443             pass
00444         pass
00445     
00446     #
00447     # Initialisation ORB and Naming Service
00448     #
00449    
00450     clt=orbmodule.client(args)
00451 
00452     #
00453     # Wake up session option
00454     #
00455     if args['wake_up_session']:
00456         import Engines
00457         import SALOME
00458         import SALOMEDS
00459         import SALOME_ModuleCatalog
00460         import SALOME_Session_idl
00461         session = clt.waitNS("/Kernel/Session",SALOME.Session)
00462         status = session.GetStatSession()
00463         if status.activeGUI:
00464             from salome_utils import getPortNumber
00465             port = getPortNumber()
00466             msg  = "Warning :"
00467             msg += "\n"
00468             msg += "Session GUI for port number %s is already active."%(port)
00469             msg += "\n"
00470             msg += "If you which to wake up another session,"
00471             msg += "\n"
00472             msg += "please use variable OMNIORB_CONFIG"
00473             msg += "\n"
00474             msg += "to get the correct session object in naming service."
00475             sys.stdout.write(msg+"\n")
00476             sys.stdout.flush()
00477             return clt
00478         session.GetInterface()
00479         args["session_object"] = session
00480         return clt
00481     
00482     # Save Naming service port name into
00483     # the file args["ns_port_log_file"]
00484     if args.has_key('ns_port_log_file'):
00485       home = os.environ['HOME']
00486       appli= os.environ.get("APPLI")
00487       if appli is not None:
00488         home = os.path.join(home, appli, "USERS")
00489       file_name = os.path.join(home, args["ns_port_log_file"])
00490       f = open(file_name, "w")
00491       f.write(os.environ['NSPORT'])
00492       f.close()
00493 
00494     # Launch Logger Server (optional)
00495     # and wait until it is registered in naming service
00496     #
00497 
00498     if args['logger']:
00499         myServer=LoggerServer(args)
00500         myServer.run()
00501         clt.waitLogger("Logger")
00502 
00503     # Notify Server launch
00504     #
00505 
00506     if sys.platform != "win32":
00507       if verbose(): print "Notify Server to launch"
00508     
00509       myServer=NotifyServer(args,modules_root_dir)
00510       myServer.run()
00511 
00512     # Launch  Session Server (to show splash ASAP)
00513     #
00514 
00515     if args["gui"]:
00516         mySessionServ = SessionServer(args,args['modules'],modules_root_dir)
00517         mySessionServ.setpath(modules_list,modules_root_dir)
00518         mySessionServ.run()
00519 
00520     #
00521     # Launch Registry Server,
00522     # and wait until it is registered in naming service
00523     #
00524 
00525     if ('registry' not in args['embedded']) | (args["gui"] == 0) :
00526         myServer=RegistryServer(args)
00527         myServer.run()
00528         if sys.platform == "win32":
00529           clt.waitNS("/Registry")
00530         else:
00531           clt.waitNSPID("/Registry",myServer.PID)
00532 
00533     #
00534     # Launch Catalog Server,
00535     # and wait until it is registered in naming service
00536     #
00537 
00538     if ('moduleCatalog' not in args['embedded']) | (args["gui"] == 0):
00539         cataServer=CatalogServer(args)
00540         cataServer.setpath(modules_list,modules_root_dir)
00541         cataServer.run()
00542         import SALOME_ModuleCatalog
00543         if sys.platform == "win32":
00544           clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
00545         else:
00546           clt.waitNSPID("/Kernel/ModulCatalog",cataServer.PID,SALOME_ModuleCatalog.ModuleCatalog)
00547 
00548     #
00549     # Launch SalomeDS Server,
00550     # and wait until it is registered in naming service
00551     #
00552 
00553     #print "ARGS = ",args
00554     if ('study' not in args['embedded']) | (args["gui"] == 0):
00555         print "RunStudy"
00556         myServer=SalomeDSServer(args)
00557         myServer.run()
00558         if sys.platform == "win32":
00559           clt.waitNS("/myStudyManager")
00560         else:
00561           clt.waitNSPID("/myStudyManager",myServer.PID)
00562 
00563     #
00564     # Launch LauncherServer
00565     #
00566     
00567     myCmServer = LauncherServer(args)
00568     myCmServer.setpath(modules_list,modules_root_dir)
00569     myCmServer.run()
00570 
00571     #
00572     # Launch ConnectionManagerServer
00573     #
00574 
00575     myConnectionServer = ConnectionManagerServer(args)
00576     myConnectionServer.run()
00577 
00578 
00579     from Utils_Identity import getShortHostName
00580     
00581     if os.getenv("HOSTNAME") == None:
00582         if os.getenv("HOST") == None:
00583             os.environ["HOSTNAME"]=getShortHostName()
00584         else:
00585             os.environ["HOSTNAME"]=os.getenv("HOST")
00586 
00587     theComputer = getShortHostName()
00588     
00589     #
00590     # Launch local C++ Container (FactoryServer),
00591     # and wait until it is registered in naming service
00592     #
00593 
00594     if ('cppContainer' in args['standalone']) | (args["gui"] == 0) : 
00595         myServer=ContainerCPPServer(args)
00596         myServer.run()
00597         if sys.platform == "win32":
00598           clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
00599         else:
00600           clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID)
00601 
00602     #
00603     # Launch local Python Container (FactoryServerPy),
00604     # and wait until it is registered in naming service
00605     #
00606 
00607     if 'pyContainer' in args['standalone']:
00608         myServer=ContainerPYServer(args)
00609         myServer.run()
00610         if sys.platform == "win32":
00611           clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy")
00612         else:
00613           clt.waitNSPID("/Containers/" + theComputer + "/FactoryServerPy",myServer.PID)
00614 
00615     #
00616     # Wait until Session Server is registered in naming service
00617     #
00618     
00619     if args["gui"]:
00620 ##----------------        
00621         import Engines
00622         import SALOME
00623         import SALOMEDS
00624         import SALOME_ModuleCatalog
00625         import SALOME_Session_idl
00626         if sys.platform == "win32":
00627           session=clt.waitNS("/Kernel/Session",SALOME.Session)
00628         else:
00629           session=clt.waitNSPID("/Kernel/Session",mySessionServ.PID,SALOME.Session)
00630         args["session_object"] = session
00631     end_time = os.times()
00632     if verbose(): print
00633     print "Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
00634                                                          - init_time[4])
00635 
00636     # ASV start GUI without Loader
00637     #if args['gui']:
00638     #    session.GetInterface()
00639 
00640     #
00641     # additionnal external python interpreters
00642     #
00643     nbaddi=0
00644     
00645     try:
00646         if 'interp' in args:
00647             nbaddi = args['interp']
00648     except:
00649         import traceback
00650         traceback.print_exc()
00651         print "-------------------------------------------------------------"
00652         print "-- to get an external python interpreter:runSalome --interp=1"
00653         print "-------------------------------------------------------------"
00654         
00655     if verbose(): print "additional external python interpreters: ", nbaddi
00656     if nbaddi:
00657         for i in range(nbaddi):
00658             print "i=",i
00659             anInterp=InterpServer(args)
00660             anInterp.run()
00661 
00662     # set PYTHONINSPECT variable (python interpreter in interactive mode)
00663     if args['pinter']:
00664         os.environ["PYTHONINSPECT"]="1"
00665         try:
00666             import readline
00667         except ImportError:
00668             pass
00669         
00670     return clt
00671 
00672 # -----------------------------------------------------------------------------
00673 
00674 def useSalome(args, modules_list, modules_root_dir):
00675     """
00676     Launch all SALOME servers requested by args,
00677     save list of process, give info to user,
00678     show registered objects in Naming Service.
00679     """
00680     global process_id
00681     
00682     clt=None
00683     try:
00684         clt = startSalome(args, modules_list, modules_root_dir)
00685     except:
00686         import traceback
00687         traceback.print_exc()
00688         print
00689         print
00690         print "--- Error during Salome launch ---"
00691         
00692     #print process_id
00693 
00694     from addToKillList import addToKillList
00695     from killSalomeWithPort import getPiDict
00696 
00697     filedict = getPiDict(args['port'])
00698     for pid, cmd in process_id.items():
00699         addToKillList(pid, cmd, args['port'])
00700         pass
00701 
00702     if verbose(): print """
00703     Saving of the dictionary of Salome processes in %s
00704     To kill SALOME processes from a console (kill all sessions from all ports):
00705       python killSalome.py 
00706     To kill SALOME from the present interpreter, if it is not closed :
00707       killLocalPort()      --> kill this session
00708                                (use CORBA port from args of runSalome)
00709       givenPortKill(port)  --> kill a specific session with given CORBA port 
00710       killAllPorts()       --> kill all sessions
00711     
00712     runSalome, with --killall option, starts with killing
00713     the processes resulting from the previous execution.
00714     """%filedict
00715     
00716     #
00717     #  Print Naming Service directory list
00718     #
00719     
00720     if clt != None:
00721         if verbose():
00722             print
00723             print " --- registered objects tree in Naming Service ---"
00724             clt.showNS()
00725             pass
00726         
00727         if not args['gui'] or not args['session_gui']:
00728             if args['shutdown_servers']:
00729                 class __utils__(object):
00730                     def __init__(self, port):
00731                         self.port = port
00732                         import killSalomeWithPort
00733                         self.killSalomeWithPort = killSalomeWithPort
00734                         return
00735                     def __del__(self):
00736                         self.killSalomeWithPort.killMyPort(self.port)
00737                         return
00738                     pass
00739                 args['shutdown_servers'] = __utils__(args['port'])
00740                 pass
00741             pass
00742         
00743         # run python scripts, passed via --execute option
00744         toimport = []
00745         if args.has_key('pyscript'):
00746             if args.has_key('gui') and args.has_key('session_gui'):
00747                 if not args['gui'] or not args['session_gui']:
00748                     toimport = args['pyscript']
00749 
00750         for srcname in toimport :
00751             if srcname == 'killall':
00752                 clt.showNS()
00753                 killAllPorts()
00754                 sys.exit(0)
00755             else:
00756                 if os.path.isabs(srcname):
00757                     if os.path.exists(srcname):
00758                         execScript(srcname)
00759                     elif os.path.exists(srcname+".py"):
00760                         execScript(srcname+".py")
00761                     else:
00762                         print "Can't execute file %s" % srcname
00763                     pass
00764                 else:
00765                     found = False
00766                     for path in [os.getcwd()] + sys.path:
00767                         if os.path.exists(os.path.join(path,srcname)):
00768                             execScript(os.path.join(path,srcname))
00769                             found = True
00770                             break
00771                         elif os.path.exists(os.path.join(path,srcname+".py")):
00772                             execScript(os.path.join(path,srcname+".py"))
00773                             found = True
00774                             break
00775                         pass
00776                     if not found:
00777                         print "Can't execute file %s" % srcname
00778                         pass
00779                     pass
00780                 pass
00781             pass
00782         pass
00783     return clt
00784     
00785 def execScript(script_path):
00786     print 'executing', script_path
00787     sys.path.insert(0, os.path.dirname(script_path))
00788     execfile(script_path,globals())
00789     del sys.path[0]
00790 
00791 # -----------------------------------------------------------------------------
00792 
00793 def registerEnv(args, modules_list, modules_root_dir):
00794     """
00795     Register args, modules_list, modules_root_dir in a file
00796     for further use, when SALOME is launched embedded in an other application.
00797     """
00798     if sys.platform == "win32":
00799       fileEnv = os.getenv('TEMP')
00800     else:
00801       fileEnv = '/tmp/'
00802 
00803     fileEnv += os.getenv('USER') + "_" + str(args['port']) \
00804             + '_' + args['appname'].upper() + '_env'
00805     fenv=open(fileEnv,'w')
00806     pickle.dump((args, modules_list, modules_root_dir),fenv)
00807     fenv.close()
00808     os.environ["SALOME_LAUNCH_CONFIG"] = fileEnv
00809 
00810 # -----------------------------------------------------------------------------
00811 
00812 def searchFreePort(args, save_config=1):
00813     print "Searching for a free port for naming service:",
00814     #
00815     if sys.platform == "win32":
00816         tmp_file = os.getenv('TEMP');
00817     else:
00818         tmp_file = '/tmp'
00819     tmp_file = os.path.join(tmp_file, '.netstat_%s'%os.getpid())
00820     #
00821     ###status = os.system("netstat -ltn | grep -E :%s > /dev/null 2>&1"%(NSPORT))
00822     os.system( "netstat -a -n > %s" % tmp_file );
00823     f = open( tmp_file, 'r' );
00824     ports = f.readlines();
00825     f.close();
00826     os.remove( tmp_file );
00827     #
00828     def portIsUsed(port, data):
00829         regObj = re.compile( ".*tcp.*:([0-9]+).*:.*listen", re.IGNORECASE );
00830         for item in data:
00831             try:
00832                 p = int(regObj.match(item).group(1))
00833                 if p == port: return True
00834                 pass
00835             except:
00836                 pass
00837             pass
00838         return False
00839     #
00840     NSPORT=2810
00841     limit=NSPORT+100
00842     #
00843     while 1:
00844         if not portIsUsed(NSPORT, ports):
00845             print "%s - OK"%(NSPORT)
00846             #
00847             from salome_utils import generateFileName, getHostName
00848             hostname = getHostName()
00849             #
00850             home  = os.getenv("HOME")
00851             appli = os.getenv("APPLI")
00852             kwargs={}
00853             if appli is not None: 
00854               home = os.path.join(home, appli,"USERS")
00855               kwargs["with_username"]=True
00856             #
00857             omniorb_config = generateFileName(home, prefix="omniORB",
00858                                               extension="cfg",
00859                                               hidden=True,
00860                                               with_hostname=True,
00861                                               with_port=NSPORT,
00862                                               **kwargs)
00863             orbdata = []
00864             initref = "NameService=corbaname::%s:%s"%(hostname, NSPORT)
00865             from omniORB import CORBA
00866             if CORBA.ORB_ID == "omniORB4":
00867                 orbdata.append("InitRef = %s"%(initref))
00868                 orbdata.append("giopMaxMsgSize = 2097152000  # 2 GBytes")
00869                 orbdata.append("traceLevel = 0 # critical errors only")
00870             else:
00871                 orbdata.append("ORBInitRef %s"%(initref))
00872                 orbdata.append("ORBgiopMaxMsgSize = 2097152000  # 2 GBytes")
00873                 orbdata.append("ORBtraceLevel = 0 # critical errors only")
00874                 pass
00875             orbdata.append("")
00876             f = open(omniorb_config, "w")
00877             f.write("\n".join(orbdata))
00878             f.close()
00879             #
00880             os.environ['OMNIORB_CONFIG'] = omniorb_config
00881             os.environ['NSPORT'] = "%s"%(NSPORT)
00882             os.environ['NSHOST'] = "%s"%(hostname)
00883             args['port'] = os.environ['NSPORT']
00884             #
00885             if save_config:
00886                 last_running_config = generateFileName(home, prefix="omniORB",
00887                                                        suffix="last",
00888                                                        extension="cfg",
00889                                                        hidden=True,
00890                                                        **kwargs)
00891                 try:
00892                     if sys.platform == "win32":
00893                         import shutil       
00894                         shutil.copyfile(omniorb_config, last_running_config)
00895                     else:
00896                         try:
00897                             os.remove(last_running_config)
00898                         except OSError:
00899                             pass
00900                         os.symlink(omniorb_config, last_running_config)
00901                         pass
00902                     pass
00903                 except:
00904                     pass
00905             break
00906         print "%s"%(NSPORT),
00907         if NSPORT == limit:
00908             msg  = "\n"
00909             msg += "Can't find a free port to launch omniNames\n"
00910             msg += "Try to kill the running servers and then launch SALOME again.\n"
00911             raise RuntimeError, msg
00912         NSPORT=NSPORT+1
00913         pass
00914     return
00915     
00916 # -----------------------------------------------------------------------------
00917 
00918 def no_main():
00919     """Salome Launch, when embedded in other application"""
00920     fileEnv = os.environ["SALOME_LAUNCH_CONFIG"]
00921     fenv=open(fileEnv,'r')
00922     args, modules_list, modules_root_dir = pickle.load(fenv)
00923     fenv.close()
00924     kill_salome(args)
00925     searchFreePort(args, 0)
00926     clt = useSalome(args, modules_list, modules_root_dir)
00927     return clt
00928 
00929 # -----------------------------------------------------------------------------
00930 
00931 def main():
00932     """Salome launch as a main application"""
00933     from salome_utils import getHostName
00934     print "runSalome running on %s" % getHostName()
00935     args, modules_list, modules_root_dir = setenv.get_config()
00936     kill_salome(args)
00937     save_config = True
00938     if args.has_key('save_config'):
00939         save_config = args['save_config']
00940     # --
00941     test = True
00942     if args['wake_up_session']:
00943         test = False
00944         pass
00945     if test:
00946         searchFreePort(args, save_config)
00947         pass
00948     # --
00949     #setenv.main()
00950     setenv.set_env(args, modules_list, modules_root_dir)
00951     clt = useSalome(args, modules_list, modules_root_dir)
00952     return clt,args
00953 
00954 # -----------------------------------------------------------------------------
00955 
00956 def foreGround(clt, args):
00957     # --
00958     if "session_object" not in args:
00959         return
00960     session = args["session_object"]
00961     # --
00962     # Wait until gui is arrived
00963     # tmax = nbtot * dt
00964     # --
00965     gui_detected = False
00966     dt = 0.1
00967     nbtot = 100
00968     nb = 0
00969     while 1:
00970         try:
00971             status = session.GetStatSession()
00972             gui_detected = status.activeGUI
00973         except:
00974             pass
00975         if gui_detected:
00976             break
00977         from time import sleep
00978         sleep(dt)
00979         nb += 1
00980         if nb == nbtot:
00981             break
00982         pass
00983     # --
00984     if not gui_detected:
00985         return
00986     # --
00987     from salome_utils import getPortNumber
00988     port = getPortNumber()
00989     # --
00990     server = Server({})
00991     if sys.platform == "win32":
00992       server.CMD = [os.getenv("PYTHONBIN"), "-m", "killSalomeWithPort", "--spy", "%s"%(os.getpid()), "%s"%(port)]
00993     else:
00994       server.CMD = ["killSalomeWithPort.py", "--spy", "%s"%(os.getpid()), "%s"%(port)]
00995     server.run()   
00996     # os.system("killSalomeWithPort.py --spy %s %s &"%(os.getpid(), port))
00997     # --
00998     dt = 1.0
00999     try:
01000         while 1:
01001             try:
01002                 status = session.GetStatSession()
01003                 assert status.activeGUI
01004             except:
01005                 break
01006             from time import sleep
01007             sleep(dt)
01008             pass
01009         pass
01010     except KeyboardInterrupt:
01011         from killSalomeWithPort import killMyPort
01012         killMyPort(port)
01013         pass
01014     return
01015 
01016 # -----------------------------------------------------------------------------
01017 
01018 if __name__ == "__main__":
01019     import user
01020     clt,args = main()
01021     # --
01022     test = args['gui'] and args['session_gui']
01023     test = test or args['wake_up_session']
01024     # --
01025     # The next test covers the --pinter option or var PYTHONINSPECT setted
01026     # --
01027     test = test and not os.environ.get('PYTHONINSPECT')
01028     # --
01029     # The next test covers the python -i $KERNEL_ROOT_DIR/bin/salome/runSalome.py case
01030     # --
01031     try:
01032         from ctypes import POINTER, c_int, cast, pythonapi
01033         iflag_ptr = cast(pythonapi.Py_InteractiveFlag, POINTER(c_int))
01034         test = test and not iflag_ptr.contents.value
01035     except:
01036         pass
01037     # --
01038     test = test and os.getenv("SALOME_TEST_MODE", "0") != "1"
01039     test = test and args['foreground']
01040     # --
01041     if test:
01042         foreGround(clt, args)
01043         pass
01044     # --
01045     pass