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