]> SALOME platform Git repositories - modules/kernel.git/blob - bin/runSalome.py
Salome HOME
First implementation of the --wake-up-session option
[modules/kernel.git] / bin / runSalome.py
1 #!/usr/bin/env python
2 #  -*- coding: iso-8859-1 -*-
3 #  Copyright (C) 2007-2010  CEA/DEN, EDF R&D, OPEN CASCADE
4 #
5 #  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
6 #  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
7 #
8 #  This library is free software; you can redistribute it and/or
9 #  modify it under the terms of the GNU Lesser General Public
10 #  License as published by the Free Software Foundation; either
11 #  version 2.1 of the License.
12 #
13 #  This library is distributed in the hope that it will be useful,
14 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 #  Lesser General Public License for more details.
17 #
18 #  You should have received a copy of the GNU Lesser General Public
19 #  License along with this library; if not, write to the Free Software
20 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
21 #
22 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 #
24
25 ## @package runSalome
26 # \brief Module that provides services to launch SALOME
27 #
28
29 import sys, os, string, glob, time, pickle, re
30 import orbmodule
31 import setenv
32 from server import *
33 from launchConfigureParser import verbose
34 from server import process_id
35
36 if sys.platform == "win32":
37     SEP = ";"
38 else:
39     SEP = ":"
40
41 # -----------------------------------------------------------------------------
42
43 from killSalome import killAllPorts
44
45 def killLocalPort():
46     """
47     kill servers from a previous SALOME exection, if needed,
48     on the CORBA port given in args of runSalome
49     """
50     
51     from killSalomeWithPort import killMyPort
52     my_port=str(args['port'])
53     try:
54         killMyPort(my_port)
55     except:
56         print "problem in killLocalPort()"
57         pass
58     pass
59     
60 def givenPortKill(port):
61     """
62     kill servers from a previous SALOME exection, if needed,
63     on the same CORBA port
64     """
65     
66     from killSalomeWithPort import killMyPort
67     my_port=port
68     try:
69         killMyPort(my_port)
70     except:
71         print "problem in LocalPortKill(), killMyPort("<<port<<")"
72         pass
73     pass
74
75 def kill_salome(args):
76     """
77     Kill servers from previous SALOME executions, if needed;
78     depending on args 'killall' or 'portkill', kill all executions,
79     or only execution on the same CORBA port
80     """
81
82     if args['killall']:
83         killAllPorts()
84     elif args['portkill']:
85         givenPortKill(str(args['port']))
86
87 # -----------------------------------------------------------------------------
88 #
89 # Class definitions to launch CORBA Servers
90 #
91
92 class InterpServer(Server):
93     def __init__(self,args):
94         self.args=args
95         if sys.platform != "win32":
96           env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
97           self.CMD=['xterm', '-e']+ env_ld_library_path + ['python']
98         else:
99           self.CMD=['cmd', '/c', 'start cmd.exe', '/K', 'python']
100        
101     def run(self):
102         global process_id
103         command = self.CMD
104         print "INTERPSERVER::command = ", command
105         if sys.platform == "win32":
106           import win32pm
107           pid = win32pm.spawnpid( string.join(command, " "),'-nc' )
108         else:
109           pid = os.spawnvp(os.P_NOWAIT, command[0], command)
110         process_id[pid]=self.CMD
111         self.PID = pid
112
113 # ---
114
115 def get_cata_path(list_modules,modules_root_dir):
116     """Build a list of catalog paths (cata_path) to initialize the ModuleCatalog server
117     """
118     modules_cata={}
119     cata_path=[]
120
121     for module in list_modules:
122         if modules_root_dir.has_key(module):
123             module_root_dir=modules_root_dir[module]
124             module_cata=module+"Catalog.xml"
125             cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources",module.lower(), module_cata)
126
127             if os.path.exists(cata_file):
128                 cata_path.append(cata_file)
129                 modules_cata[module]=cata_file
130             else:
131                 cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources", module_cata)
132                 if os.path.exists(cata_file):
133                     cata_path.append(cata_file)
134                     modules_cata[module]=cata_file
135
136     for path in os.getenv("SALOME_CATALOGS_PATH","").split(SEP):
137         if os.path.exists(path):
138             for cata_file in glob.glob(os.path.join(path,"*Catalog.xml")):
139                 module_name= os.path.basename(cata_file)[:-11]
140                 if not modules_cata.has_key(module_name):
141                     cata_path.append(cata_file)
142                     modules_cata[module_name]=cata_file
143
144     return cata_path
145
146
147
148 class CatalogServer(Server):
149     def __init__(self,args):
150         self.args=args
151         self.initArgs()
152         self.SCMD1=['SALOME_ModuleCatalog_Server','-common']
153         self.SCMD2=[]
154         home_dir=os.getenv('HOME')
155         if home_dir is not None:
156             self.SCMD2=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')] 
157
158     def setpath(self,modules_list,modules_root_dir):
159         list_modules = modules_list[:]
160         list_modules.reverse()
161         if self.args["gui"] :
162             list_modules = ["KERNEL", "GUI"] + list_modules
163         else :
164             list_modules = ["KERNEL"] + list_modules
165
166         cata_path=get_cata_path(list_modules,modules_root_dir)
167
168         self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
169
170 # ---
171
172 class SalomeDSServer(Server):
173     def __init__(self,args):
174         self.args=args
175         self.initArgs()
176         self.CMD=['SALOMEDS_Server']
177
178 # ---
179
180 class ConnectionManagerServer(Server):
181     def __init__(self,args):
182         self.args=args
183         self.initArgs()
184         self.CMD=['SALOME_ConnectionManagerServer']
185
186 # ---
187
188 class RegistryServer(Server):
189     def __init__(self,args):
190         self.args=args
191         self.initArgs()
192         self.CMD=['SALOME_Registry_Server', '--salome_session','theSession']
193
194 # ---
195
196 class ContainerCPPServer(Server):
197     def __init__(self,args):
198         self.args=args
199         self.initArgs()
200         self.CMD=['SALOME_Container','FactoryServer']
201
202 # ---
203
204 class ContainerPYServer(Server):
205     def __init__(self,args):
206         self.args=args
207         self.initArgs()
208         if sys.platform == "win32":
209           self.CMD=[os.environ["PYTHONBIN"], '\"'+os.environ["KERNEL_ROOT_DIR"] + '/bin/salome/SALOME_ContainerPy.py'+'\"','FactoryServerPy']
210         else:
211           self.CMD=['SALOME_ContainerPy.py','FactoryServerPy']
212
213 # ---
214
215 class LoggerServer(Server):
216     def __init__(self,args):
217         self.args=args
218         self.initArgs()
219         from salome_utils import generateFileName
220         if sys.platform == "win32": dirpath = os.environ["HOME"]
221         else:                       dirpath = "/tmp"
222         logfile = generateFileName( dirpath,
223                                     prefix="logger",
224                                     extension="log",
225                                     with_username=True,
226                                     with_hostname=True,
227                                     with_port=True)
228         print "==========================================================="
229         print "Logger server: put log to the file:"
230         print logfile
231         print "==========================================================="
232         self.CMD=['SALOME_Logger_Server', logfile]
233         pass
234     pass # end of LoggerServer class
235
236 # ---
237
238 class SessionServer(Server):
239     def __init__(self,args,modules_list,modules_root_dir):
240         self.args = args.copy()
241         # Bug 11512 (Problems with runSalome --xterm on Mandrake and Debian Sarge)
242         #self.args['xterm']=0
243         #
244         self.initArgs()
245         self.SCMD1=['SALOME_Session_Server']
246         self.SCMD2=[]
247         if 'registry' in self.args['embedded']:
248             self.SCMD1+=['--with','Registry',
249                          '(','--salome_session','theSession',')']
250         if 'moduleCatalog' in self.args['embedded']:
251             self.SCMD1+=['--with','ModuleCatalog','(','-common']
252             home_dir=os.getenv('HOME')
253             if home_dir is not None:
254                 self.SCMD2+=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')] 
255             self.SCMD2+=[')']
256         if 'study' in self.args['embedded']:
257             self.SCMD2+=['--with','SALOMEDS','(',')']
258         if 'cppContainer' in self.args['embedded']:
259             self.SCMD2+=['--with','Container','(','FactoryServer',')']
260         if 'SalomeAppEngine' in self.args['embedded']:
261             self.SCMD2+=['--with','SalomeAppEngine','(',')']
262             
263         if 'cppContainer' in self.args['standalone'] or 'cppContainer' in self.args['embedded']:
264             self.SCMD2+=['CPP']
265         if 'pyContainer' in self.args['standalone'] or 'pyContainer' in self.args['embedded']:
266             self.SCMD2+=['PY']
267         if self.args['gui']:
268             session_gui = True
269             if self.args.has_key('session_gui'):
270                 session_gui = self.args['session_gui']
271             if session_gui:
272                 self.SCMD2+=['GUI']
273                 if self.args['splash']:
274                     self.SCMD2+=['SPLASH']
275                     pass
276                 if self.args['study_hdf'] is not None:
277                     self.SCMD2+=['--study-hdf=%s'%self.args['study_hdf']]
278                     pass
279                 pass
280             pass
281         if self.args['noexcepthandler']:
282             self.SCMD2+=['noexcepthandler']
283         if self.args.has_key('user_config'):
284             self.SCMD2+=['--resources=%s'%self.args['user_config']]
285         if self.args.has_key('modules'):
286             list_modules = []
287             #keep only modules with GUI
288             for m in modules_list:
289               fr1 = os.path.join(modules_root_dir[m],"share","salome","resources",m.lower(),"SalomeApp.xml")
290               fr2 = os.path.join(modules_root_dir[m],"share","salome","resources","SalomeApp.xml")
291               if os.path.exists(fr1) or os.path.exists(fr2):
292                 list_modules.insert(0,m)
293             self.SCMD2+=['--modules (%s)' % ":".join(list_modules)]
294
295         if self.args.has_key('pyscript') and len(self.args['pyscript']) > 0:
296             self.SCMD2+=['--pyscript=%s'%(",".join(self.args['pyscript']))]
297
298     def setpath(self,modules_list,modules_root_dir):
299         list_modules = modules_list[:]
300         list_modules.reverse()
301         if self.args["gui"] :
302             list_modules = ["KERNEL", "GUI"] + list_modules
303         else :
304             list_modules = ["KERNEL"] + list_modules
305
306         cata_path=get_cata_path(list_modules,modules_root_dir)
307
308         if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
309             #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
310             self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
311         else:
312             self.CMD=self.SCMD1 + self.SCMD2
313         if self.args.has_key('test'):
314             self.CMD+=['-test'] + self.args['test']
315         elif self.args.has_key('play'):
316             self.CMD+=['-play'] + self.args['play']
317
318         if self.args["gdb_session"] or self.args["ddd_session"]:
319             f = open(".gdbinit4salome", "w")
320             f.write("set args ")
321             args = " ".join(self.CMD[1:])
322             args = args.replace("(", "\(")
323             args = args.replace(")", "\)")
324             f.write(args)
325             f.write("\n")
326             f.close()
327             if self.args["ddd_session"]:
328                 self.CMD = ["ddd", "--command=.gdbinit4salome", self.CMD[0]]
329             elif self.args["gdb_session"]:
330                 self.CMD = ["xterm", "-e", "gdb", "--command=.gdbinit4salome", self.CMD[0]]
331                 pass
332             pass
333         
334         if self.args["valgrind_session"]:
335             l = ["valgrind"]
336             val = os.getenv("VALGRIND_OPTIONS")
337             if val:
338                 l += val.split()
339                 pass
340             self.CMD = l + self.CMD
341             pass
342         
343 # ---
344
345 class LauncherServer(Server):
346     def __init__(self,args):
347         self.args=args
348         self.initArgs()
349         self.SCMD1=['SALOME_LauncherServer']
350         self.SCMD2=[]
351         if args["gui"] :
352             if 'registry' in self.args['embedded']:
353                 self.SCMD1+=['--with','Registry',
354                              '(','--salome_session','theSession',')']
355             if 'moduleCatalog' in self.args['embedded']:
356                 self.SCMD1+=['--with','ModuleCatalog','(','-common']
357                 self.SCMD2+=['-personal',
358                              '${HOME}/Salome/resources/CatalogModulePersonnel.xml',')']
359             if 'study' in self.args['embedded']:
360                 self.SCMD2+=['--with','SALOMEDS','(',')']
361             if 'cppContainer' in self.args['embedded']:
362                 self.SCMD2+=['--with','Container','(','FactoryServer',')']
363
364     def setpath(self,modules_list,modules_root_dir):
365         list_modules = modules_list[:]
366         list_modules.reverse()
367         if self.args["gui"] :
368             list_modules = ["KERNEL", "GUI"] + list_modules
369         else :
370             list_modules = ["KERNEL"] + list_modules
371
372         cata_path=get_cata_path(list_modules,modules_root_dir)
373
374         if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
375             #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
376             self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
377         else:
378             self.CMD=self.SCMD1 + self.SCMD2
379
380 class NotifyServer(Server):
381     def __init__(self,args,modules_root_dir):
382         self.args=args
383         self.initArgs()
384         self.modules_root_dir=modules_root_dir
385         myLogName = os.environ["LOGNAME"]
386         self.CMD=['notifd','-c',
387                   self.modules_root_dir["KERNEL"] +'/share/salome/resources/kernel/channel.cfg',
388                   '-DFactoryIORFileName=/tmp/'+myLogName+'_rdifact.ior',
389                   '-DChannelIORFileName=/tmp/'+myLogName+'_rdichan.ior',
390                   '-DReportLogFile=/tmp/'+myLogName+'_notifd.report',
391                   '-DDebugLogFile=/tmp/'+myLogName+'_notifd.debug',
392                   ]
393
394 #
395 # -----------------------------------------------------------------------------
396
397 def startGUI(clt):
398     """Salome Session Graphic User Interface activation"""
399     import Engines
400     import SALOME
401     import SALOMEDS
402     import SALOME_ModuleCatalog
403     import SALOME_Session_idl
404     session=clt.waitNS("/Kernel/Session",SALOME.Session)
405     session.GetInterface()
406   
407 # -----------------------------------------------------------------------------
408
409 def startSalome(args, modules_list, modules_root_dir):
410     """Launch all SALOME servers requested by args"""
411     init_time = os.times()
412
413     if verbose(): print "startSalome ", args
414     
415     #
416     # Wake up session option
417     #
418     if args['wake_up_session']:
419         if "OMNIORB_CONFIG" not in os.environ:
420             from salome_utils import generateFileName
421             home  = os.getenv("HOME")
422             appli = os.getenv("APPLI")
423             kwargs={}
424             if appli is not None: 
425                 home = os.path.join(home, appli,"USERS")
426                 kwargs["with_username"] = True
427                 pass
428             last_running_config = generateFileName(home, prefix="omniORB",
429                                                    suffix="last",
430                                                    extension="cfg",
431                                                    hidden=True,
432                                                    **kwargs)
433             os.environ['OMNIORB_CONFIG'] = last_running_config
434             pass
435         pass
436     
437     #
438     # Initialisation ORB and Naming Service
439     #
440    
441     clt=orbmodule.client(args)
442
443     #
444     # Wake up session option
445     #
446     if args['wake_up_session']:
447         import Engines
448         import SALOME
449         import SALOMEDS
450         import SALOME_ModuleCatalog
451         import SALOME_Session_idl
452         session = clt.waitNS("/Kernel/Session",SALOME.Session)
453         status = session.GetStatSession()
454         if status.activeGUI:
455             msg = "Session GUI is already active"
456             raise Exception(msg)
457         session.GetInterface()
458         return clt
459     
460     # Save Naming service port name into
461     # the file args["ns_port_log_file"]
462     if args.has_key('ns_port_log_file'):
463       home = os.environ['HOME']
464       appli= os.environ.get("APPLI")
465       if appli is not None:
466         home='%s/%s'%(home,appli)
467         pass
468       file_name= '%s/%s'%(home, args["ns_port_log_file"])
469       f = open(file_name, "w")
470       f.write(os.environ['NSPORT'])
471       f.close()
472
473     # Launch Logger Server (optional)
474     # and wait until it is registered in naming service
475     #
476
477     if args['logger']:
478         myServer=LoggerServer(args)
479         myServer.run()
480         clt.waitLogger("Logger")
481
482     # Notify Server launch
483     #
484
485     if sys.platform != "win32":
486       if verbose(): print "Notify Server to launch"
487     
488       myServer=NotifyServer(args,modules_root_dir)
489       myServer.run()
490
491     # Launch  Session Server (to show splash ASAP)
492     #
493
494     if args["gui"]:
495         mySessionServ = SessionServer(args,modules_list,modules_root_dir)
496         mySessionServ.setpath(modules_list,modules_root_dir)
497         mySessionServ.run()
498
499     #
500     # Launch Registry Server,
501     # and wait until it is registered in naming service
502     #
503
504     if ('registry' not in args['embedded']) | (args["gui"] == 0) :
505         myServer=RegistryServer(args)
506         myServer.run()
507         if sys.platform == "win32":
508           clt.waitNS("/Registry")
509         else:
510           clt.waitNSPID("/Registry",myServer.PID)
511
512     #
513     # Launch Catalog Server,
514     # and wait until it is registered in naming service
515     #
516
517     if ('moduleCatalog' not in args['embedded']) | (args["gui"] == 0):
518         cataServer=CatalogServer(args)
519         cataServer.setpath(modules_list,modules_root_dir)
520         cataServer.run()
521         import SALOME_ModuleCatalog
522         if sys.platform == "win32":
523           clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
524         else:
525           clt.waitNSPID("/Kernel/ModulCatalog",cataServer.PID,SALOME_ModuleCatalog.ModuleCatalog)
526
527     #
528     # Launch SalomeDS Server,
529     # and wait until it is registered in naming service
530     #
531
532     #print "ARGS = ",args
533     if ('study' not in args['embedded']) | (args["gui"] == 0):
534         print "RunStudy"
535         myServer=SalomeDSServer(args)
536         myServer.run()
537         if sys.platform == "win32":
538           clt.waitNS("/myStudyManager")
539         else:
540           clt.waitNSPID("/myStudyManager",myServer.PID)
541
542     #
543     # Launch LauncherServer
544     #
545     
546     myCmServer = LauncherServer(args)
547     myCmServer.setpath(modules_list,modules_root_dir)
548     myCmServer.run()
549
550     #
551     # Launch ConnectionManagerServer
552     #
553
554     myConnectionServer = ConnectionManagerServer(args)
555     myConnectionServer.run()
556
557
558     from Utils_Identity import getShortHostName
559     
560     if os.getenv("HOSTNAME") == None:
561         if os.getenv("HOST") == None:
562             os.environ["HOSTNAME"]=getShortHostName()
563         else:
564             os.environ["HOSTNAME"]=os.getenv("HOST")
565
566     theComputer = getShortHostName()
567     
568     #
569     # Launch local C++ Container (FactoryServer),
570     # and wait until it is registered in naming service
571     #
572
573     if ('cppContainer' in args['standalone']) | (args["gui"] == 0) : 
574         myServer=ContainerCPPServer(args)
575         myServer.run()
576         if sys.platform == "win32":
577           clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
578         else:
579           clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID)
580
581     #
582     # Launch local Python Container (FactoryServerPy),
583     # and wait until it is registered in naming service
584     #
585
586     if 'pyContainer' in args['standalone']:
587         myServer=ContainerPYServer(args)
588         myServer.run()
589         if sys.platform == "win32":
590           clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy")
591         else:
592           clt.waitNSPID("/Containers/" + theComputer + "/FactoryServerPy",myServer.PID)
593
594     #
595     # Wait until Session Server is registered in naming service
596     #
597     
598     if args["gui"]:
599 ##----------------        
600         import Engines
601         import SALOME
602         import SALOMEDS
603         import SALOME_ModuleCatalog
604         import SALOME_Session_idl
605         if sys.platform == "win32":
606           session=clt.waitNS("/Kernel/Session",SALOME.Session)
607         else:
608           session=clt.waitNSPID("/Kernel/Session",mySessionServ.PID,SALOME.Session)
609     end_time = os.times()
610     if verbose(): print
611     print "Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
612                                                          - init_time[4])
613
614     # ASV start GUI without Loader
615     #if args['gui']:
616     #    session.GetInterface()
617
618     #
619     # additionnal external python interpreters
620     #
621     nbaddi=0
622     
623     try:
624         if 'interp' in args:
625             nbaddi = args['interp']
626     except:
627         import traceback
628         traceback.print_exc()
629         print "-------------------------------------------------------------"
630         print "-- to get an external python interpreter:runSalome --interp=1"
631         print "-------------------------------------------------------------"
632         
633     print "additional external python interpreters: ", nbaddi
634     if nbaddi:
635         for i in range(nbaddi):
636             print "i=",i
637             anInterp=InterpServer(args)
638             anInterp.run()
639
640     # set PYTHONINSPECT variable (python interpreter in interactive mode)
641     if args['pinter']:
642         os.environ["PYTHONINSPECT"]="1"
643         try:
644             import readline
645         except ImportError:
646             pass
647         
648     return clt
649
650 # -----------------------------------------------------------------------------
651
652 def useSalome(args, modules_list, modules_root_dir):
653     """
654     Launch all SALOME servers requested by args,
655     save list of process, give info to user,
656     show registered objects in Naming Service.
657     """
658     global process_id
659     
660     clt=None
661     try:
662         clt = startSalome(args, modules_list, modules_root_dir)
663     except:
664         import traceback
665         traceback.print_exc()
666         print
667         print
668         print "--- Error during Salome launch ---"
669         
670     #print process_id
671
672     from addToKillList import addToKillList
673     from killSalomeWithPort import getPiDict
674
675     filedict = getPiDict(args['port'])
676     for pid, cmd in process_id.items():
677         addToKillList(pid, cmd, args['port'])
678         pass
679
680     if verbose(): print """
681     Saving of the dictionary of Salome processes in %s
682     To kill SALOME processes from a console (kill all sessions from all ports):
683       python killSalome.py 
684     To kill SALOME from the present interpreter, if it is not closed :
685       killLocalPort()      --> kill this session
686                                (use CORBA port from args of runSalome)
687       givenPortKill(port)  --> kill a specific session with given CORBA port 
688       killAllPorts()       --> kill all sessions
689     
690     runSalome, with --killall option, starts with killing
691     the processes resulting from the previous execution.
692     """%filedict
693     
694     #
695     #  Print Naming Service directory list
696     #
697     
698     if clt != None:
699         if verbose():
700             print
701             print " --- registered objects tree in Naming Service ---"
702             clt.showNS()
703             pass
704         
705         if not args['gui'] or not args['session_gui']:
706             if args['shutdown_servers']:
707                 class __utils__(object):
708                     def __init__(self, port):
709                         self.port = port
710                         import killSalomeWithPort
711                         self.killSalomeWithPort = killSalomeWithPort
712                         return
713                     def __del__(self):
714                         self.killSalomeWithPort.killMyPort(self.port)
715                         return
716                     pass
717                 args['shutdown_servers'] = __utils__(args['port'])
718                 pass
719             pass
720         
721         # run python scripts, passed via --execute option
722         toimport = []
723         if args.has_key('pyscript'):
724             if args.has_key('gui') and args.has_key('session_gui'):
725                 if not args['gui'] or not args['session_gui']:
726                     toimport = args['pyscript']
727
728         for srcname in toimport :
729             if srcname == 'killall':
730                 clt.showNS()
731                 killAllPorts()
732                 sys.exit(0)
733             else:
734                 if os.path.isabs(srcname):
735                     if os.path.exists(srcname):
736                         execScript(srcname)
737                     elif os.path.exists(srcname+".py"):
738                         execScript(srcname+".py")
739                     else:
740                         print "Can't execute file %s" % srcname
741                     pass
742                 else:
743                     found = False
744                     for path in [os.getcwd()] + sys.path:
745                         if os.path.exists(os.path.join(path,srcname)):
746                             execScript(os.path.join(path,srcname))
747                             found = True
748                             break
749                         elif os.path.exists(os.path.join(path,srcname+".py")):
750                             execScript(os.path.join(path,srcname+".py"))
751                             found = True
752                             break
753                         pass
754                     if not found:
755                         print "Can't execute file %s" % srcname
756                         pass
757                     pass
758                 pass
759             pass
760         pass
761     return clt
762     
763 def execScript(script_path):
764     print 'executing', script_path
765     sys.path.insert(0, os.path.dirname(script_path))
766     execfile(script_path,globals())
767     del sys.path[0]
768
769 # -----------------------------------------------------------------------------
770
771 def registerEnv(args, modules_list, modules_root_dir):
772     """
773     Register args, modules_list, modules_root_dir in a file
774     for further use, when SALOME is launched embedded in an other application.
775     """
776     if sys.platform == "win32":
777       fileEnv = os.getenv('TEMP')
778     else:
779       fileEnv = '/tmp/'
780
781     fileEnv += os.getenv('USER') + "_" + str(args['port']) \
782             + '_' + args['appname'].upper() + '_env'
783     fenv=open(fileEnv,'w')
784     pickle.dump((args, modules_list, modules_root_dir),fenv)
785     fenv.close()
786     os.environ["SALOME_LAUNCH_CONFIG"] = fileEnv
787
788 # -----------------------------------------------------------------------------
789
790 def searchFreePort(args, save_config=1):
791     print "Searching for a free port for naming service:",
792     #
793     if sys.platform == "win32":
794         tmp_file = os.getenv('TEMP');
795     else:
796         tmp_file = '/tmp'
797     tmp_file = os.path.join(tmp_file, '.netstat_%s'%os.getpid())
798     #
799     ###status = os.system("netstat -ltn | grep -E :%s > /dev/null 2>&1"%(NSPORT))
800     os.system( "netstat -a -n > %s" % tmp_file );
801     f = open( tmp_file, 'r' );
802     ports = f.readlines();
803     f.close();
804     os.remove( tmp_file );
805     #
806     def portIsUsed(port, data):
807         regObj = re.compile( ".*tcp.*:([0-9]+).*:.*listen", re.IGNORECASE );
808         for item in data:
809             try:
810                 p = int(regObj.match(item).group(1))
811                 if p == port: return True
812                 pass
813             except:
814                 pass
815             pass
816         return False
817     #
818     NSPORT=2810
819     limit=NSPORT+100
820     #
821     while 1:
822         if not portIsUsed(NSPORT, ports):
823             print "%s - OK"%(NSPORT)
824             #
825             from salome_utils import generateFileName, getHostName
826             hostname = getHostName()
827             #
828             home  = os.getenv("HOME")
829             appli = os.getenv("APPLI")
830             kwargs={}
831             if appli is not None: 
832               home = os.path.join(home, appli,"USERS")
833               kwargs["with_username"]=True
834             #
835             omniorb_config = generateFileName(home, prefix="omniORB",
836                                               extension="cfg",
837                                               hidden=True,
838                                               with_hostname=True,
839                                               with_port=NSPORT,
840                                               **kwargs)
841             orbdata = []
842             initref = "NameService=corbaname::%s:%s"%(hostname, NSPORT)
843             from omniORB import CORBA
844             if CORBA.ORB_ID == "omniORB4":
845                 orbdata.append("InitRef = %s"%(initref))
846                 orbdata.append("giopMaxMsgSize = 2097152000  # 2 GBytes")
847                 orbdata.append("traceLevel = 0 # critical errors only")
848             else:
849                 orbdata.append("ORBInitRef %s"%(initref))
850                 orbdata.append("ORBgiopMaxMsgSize = 2097152000  # 2 GBytes")
851                 orbdata.append("ORBtraceLevel = 0 # critical errors only")
852                 pass
853             orbdata.append("")
854             f = open(omniorb_config, "w")
855             f.write("\n".join(orbdata))
856             f.close()
857             #
858             os.environ['OMNIORB_CONFIG'] = omniorb_config
859             os.environ['NSPORT'] = "%s"%(NSPORT)
860             os.environ['NSHOST'] = "%s"%(hostname)
861             args['port'] = os.environ['NSPORT']
862             #
863             if save_config:
864                 last_running_config = generateFileName(home, prefix="omniORB",
865                                                        suffix="last",
866                                                        extension="cfg",
867                                                        hidden=True,
868                                                        **kwargs)
869                 try:
870                     if sys.platform == "win32":
871                         import shutil       
872                         shutil.copyfile(omniorb_config, last_running_config)
873                     else:
874                         try:
875                             os.remove(last_running_config)
876                         except OSError:
877                             pass
878                         os.symlink(omniorb_config, last_running_config)
879                         pass
880                     pass
881                 except:
882                     pass
883             break
884         print "%s"%(NSPORT),
885         if NSPORT == limit:
886             msg  = "\n"
887             msg += "Can't find a free port to launch omniNames\n"
888             msg += "Try to kill the running servers and then launch SALOME again.\n"
889             raise RuntimeError, msg
890         NSPORT=NSPORT+1
891         pass
892     return
893     
894 # -----------------------------------------------------------------------------
895
896 def no_main():
897     """Salome Launch, when embedded in other application"""
898     fileEnv = os.environ["SALOME_LAUNCH_CONFIG"]
899     fenv=open(fileEnv,'r')
900     args, modules_list, modules_root_dir = pickle.load(fenv)
901     fenv.close()
902     kill_salome(args)
903     searchFreePort(args, 0)
904     clt = useSalome(args, modules_list, modules_root_dir)
905     return clt
906
907 # -----------------------------------------------------------------------------
908
909 def main():
910     """Salome launch as a main application"""
911     from salome_utils import getHostName
912     print "runSalome running on %s" % getHostName()
913     args, modules_list, modules_root_dir = setenv.get_config()
914     kill_salome(args)
915     save_config = True
916     if args.has_key('save_config'):
917         save_config = args['save_config']
918     # --
919     test = True
920     if args['wake_up_session']:
921         test = False
922         pass
923     if test:
924         searchFreePort(args, save_config)
925         pass
926     # --
927     #setenv.main()
928     setenv.set_env(args, modules_list, modules_root_dir)
929     clt = useSalome(args, modules_list, modules_root_dir)
930     return clt,args
931
932 # -----------------------------------------------------------------------------
933
934 if __name__ == "__main__":
935     import user
936     clt,args = main()
937     pass