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