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