Salome HOME
16dbf097d9211d0054162e34bb5df161169a8c49
[modules/kernel.git] / bin / runSalome.py
1 #!/usr/bin/env python
2
3 # Copyright (C) 2005  OPEN CASCADE, CEA, EDF R&D, LEG
4 #           PRINCIPIA R&D, EADS CCR, Lip6, BV, CEDRAT
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either 
8 # version 2.1 of the License.
9
10 # This library is distributed in the hope that it will be useful 
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of 
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
13 # Lesser General Public License for more details.
14
15 # You should have received a copy of the GNU Lesser General Public  
16 # License along with this library; if not, write to the Free Software 
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20
21
22 import sys, os, string, glob, time, pickle
23 import orbmodule
24 from launchConfigureParser import verbose
25
26 process_id = {}
27
28 # salome_subdir variable is used for composing paths like $KERNEL_ROOT_DIR/share/salome/resources/kernel, etc.
29 # before moving to SUIT-based gui, instead of salome_subdir there was args['appname'] used.
30 # but after - 'appname'  = "SalomeApp", so using it in making the subdirectory is an error.
31 salome_subdir = "salome"
32
33 # -----------------------------------------------------------------------------
34
35 def add_path(directory, variable_name):
36     """Function helper to add environment variables"""
37     if not os.environ.has_key(variable_name):
38         os.environ[variable_name] = ""
39         pass
40     if os.path.exists(directory):
41         newpath=[]
42         for _dir in os.environ[variable_name].split(":"):
43             if os.path.exists(_dir):
44                 if not os.path.samefile(_dir, directory):
45                   newpath.append(_dir)
46             else:
47                 if os.path.abspath(_dir) != os.path.abspath(directory):
48                   newpath.append(_dir)
49             pass
50         import string
51         newpath[:0] = [ directory ]
52         newpath = string.join(newpath,":")
53         os.environ[variable_name] = newpath
54         if variable_name == "PYTHONPATH":
55             sys.path[:0] = [directory]
56
57 # -----------------------------------------------------------------------------
58
59 __lib__dir__ = None
60 def get_lib_dir():
61     global __lib__dir__
62     if __lib__dir__: return __lib__dir__
63     import platform
64     if platform.architecture()[0] == "64bit":
65         __lib__dir__ = "lib64"
66     else:
67         __lib__dir__ = "lib"
68     return get_lib_dir()
69
70 # -----------------------------------------------------------------------------
71
72 def get_config():
73     """
74     Get list of modules, paths.
75     
76     Read args from launch configure xml file and command line options.
77     Check variables <module>_ROOT_DIR and set list of used modules.
78     Return args, modules_list, modules_root_dir    
79     """
80     
81     # read args from launch configure xml file and command line options
82     
83     import launchConfigureParser
84     args = launchConfigureParser.get_env()
85     
86     # Check variables <module>_ROOT_DIR
87     # and set list of used modules (without KERNEL)
88
89     modules_list = []
90     if args.has_key("modules"):
91         modules_list += args["modules"]
92     # KERNEL must be last in the list to locate it at the first place in PATH
93     if args["gui"] :
94         modules_list[:0] = ["GUI"]
95     modules_list[:0] = ["KERNEL"]
96     modules_list.reverse()
97
98     modules_root_dir = {}
99
100     to_remove_list=[]
101     for module in modules_list :
102         module_variable=module+"_ROOT_DIR"
103         if not os.environ.has_key(module_variable):
104             print "*******************************************************"
105             print "*"
106             print "* Environment variable",module_variable,"must be set"
107             print "* Module", module, "will be not available"
108             print "*"
109             print "********************************************************"
110             to_remove_list.append(module)
111             continue
112             pass
113         module_root_dir = os.environ[module_variable]
114         modules_root_dir[module]=module_root_dir
115
116     for to_remove in to_remove_list:
117         modules_list.remove(to_remove)
118
119     while "KERNEL" in modules_list:
120         modules_list.remove("KERNEL")
121         pass
122
123     while "GUI" in modules_list:
124         modules_list.remove("GUI")
125         pass
126
127     if "SUPERV" in modules_list and not 'superv' in args['standalone']:
128         args['standalone'].append("superv")
129         pass
130    
131     return args, modules_list, modules_root_dir
132
133 # -----------------------------------------------------------------------------
134
135 def set_env(args, modules_list, modules_root_dir):
136     """Add to the PATH-variables modules specific paths"""
137     
138     python_version="python%d.%d" % sys.version_info[0:2]
139     modules_root_dir_list = []
140     if args["gui"] :
141         modules_list = modules_list[:] + ["GUI"] 
142     modules_list = modules_list[:] + ["KERNEL"] 
143     for module in modules_list :
144         if modules_root_dir.has_key(module):
145             module_root_dir = modules_root_dir[module]
146             modules_root_dir_list[:0] = [module_root_dir]
147             add_path(os.path.join(module_root_dir,get_lib_dir(),salome_subdir),
148                      "LD_LIBRARY_PATH")
149             add_path(os.path.join(module_root_dir,"bin",salome_subdir),
150                      "PATH")
151             if os.path.exists(module_root_dir + "/examples") :
152                 add_path(os.path.join(module_root_dir,"examples"),
153                          "PYTHONPATH")
154                 pass
155             add_path(os.path.join(module_root_dir,"bin",salome_subdir),
156                      "PYTHONPATH")
157             add_path(os.path.join(module_root_dir,get_lib_dir(),
158                                   python_version,"site-packages",
159                                   salome_subdir),
160                      "PYTHONPATH")
161             add_path(os.path.join(module_root_dir,get_lib_dir(),salome_subdir),
162                      "PYTHONPATH")
163             add_path(os.path.join(module_root_dir,get_lib_dir(),
164                                   python_version,"site-packages",
165                                   salome_subdir,
166                                   "shared_modules"),
167                      "PYTHONPATH")
168             pass
169         pass
170
171
172     os.environ["SALOMEPATH"]=":".join(modules_root_dir_list)
173     
174     # set trace environment variable
175     
176     if not os.environ.has_key("SALOME_trace"):
177         os.environ["SALOME_trace"]="local"
178     if args['file']:
179         os.environ["SALOME_trace"]="file:"+args['file'][0]
180     if args['logger']:
181         os.environ["SALOME_trace"]="with_logger"
182
183     # set environment for SMESH plugins
184
185     if "SMESH" in modules_list:
186         os.environ["SMESH_MeshersList"]="StdMeshers"
187         if not os.environ.has_key("SALOME_StdMeshersResources"):
188             os.environ["SALOME_StdMeshersResources"] \
189             = modules_root_dir["SMESH"]+"/share/"+args["appname"]+"/resources/smesh"
190             pass
191         if args.has_key("SMESH_plugins"):
192             for plugin in args["SMESH_plugins"]:
193                 plugin_root = ""
194                 if os.environ.has_key(plugin+"_ROOT_DIR"):
195                     plugin_root = os.environ[plugin+"_ROOT_DIR"]
196                 else:
197                     # workaround to avoid modifications of existing environment
198                     if os.environ.has_key(plugin.upper()+"_ROOT_DIR"):
199                         plugin_root = os.environ[plugin.upper()+"_ROOT_DIR"]
200                         pass
201                     pass
202                 if plugin_root != "":
203                     os.environ["SMESH_MeshersList"] \
204                     = os.environ["SMESH_MeshersList"]+":"+plugin
205                     if not os.environ.has_key("SALOME_"+plugin+"Resources"):
206                         os.environ["SALOME_"+plugin+"Resources"] \
207                         = plugin_root+"/share/"+args["appname"]+"/resources/"+plugin.lower()
208                     add_path(os.path.join(plugin_root,get_lib_dir(),python_version,
209                                           "site-packages",salome_subdir),
210                              "PYTHONPATH")
211                     add_path(os.path.join(plugin_root,get_lib_dir(),salome_subdir),
212                              "PYTHONPATH")
213                     add_path(os.path.join(plugin_root,get_lib_dir(),salome_subdir),
214                              "LD_LIBRARY_PATH")
215                     add_path(os.path.join(plugin_root,"bin",salome_subdir),
216                              "PYTHONPATH")
217                     add_path(os.path.join(plugin_root,"bin",salome_subdir),
218                              "PATH")
219             pass
220         pass
221
222     # set environment for SUPERV module
223     os.environ["ENABLE_MACRO_NODE"]="1"
224     # set resources variables if not yet set
225     # Done now by launchConfigureParser.py
226     #if os.getenv("GUI_ROOT_DIR"):
227         #if not os.getenv("SalomeAppConfig"): os.environ["SalomeAppConfig"] =  os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui"
228
229     # set CSF_PluginDefaults variable only if it is not customized
230     # by the user
231     if not os.getenv("CSF_PluginDefaults"):
232         os.environ["CSF_PluginDefaults"] \
233         = os.path.join(modules_root_dir["KERNEL"],"share",
234                        salome_subdir,"resources","kernel")
235     os.environ["CSF_SALOMEDS_ResourcesDefaults"] \
236     = os.path.join(modules_root_dir["KERNEL"],"share",
237                    salome_subdir,"resources","kernel")
238
239     if "GEOM" in modules_list:
240         if verbose(): print "GEOM OCAF Resources"
241         os.environ["CSF_GEOMDS_ResourcesDefaults"] \
242         = os.path.join(modules_root_dir["GEOM"],"share",
243                        salome_subdir,"resources","geom")
244         if verbose(): print "GEOM Shape Healing Resources"
245         os.environ["CSF_ShHealingDefaults"] \
246         = os.path.join(modules_root_dir["GEOM"],"share",
247                        salome_subdir,"resources","geom")
248
249 # -----------------------------------------------------------------------------
250
251 from killSalome import killAllPorts
252
253 def killLocalPort():
254     """
255     kill servers from a previous SALOME exection, if needed,
256     on the CORBA port given in args of runSalome
257     """
258     
259     from killSalomeWithPort import killMyPort
260     my_port=str(args['port'])
261     try:
262         killMyPort(my_port)
263     except:
264         print "problem in killLocalPort()"
265         pass
266     pass
267     
268 def givenPortKill(port):
269     """
270     kill servers from a previous SALOME exection, if needed,
271     on the same CORBA port
272     """
273     
274     from killSalomeWithPort import killMyPort
275     my_port=port
276     try:
277         killMyPort(my_port)
278     except:
279         print "problem in LocalPortKill(), killMyPort("<<port<<")"
280         pass
281     pass
282
283 def kill_salome(args):
284     """
285     Kill servers from previous SALOME executions, if needed;
286     depending on args 'killall' or 'portkill', kill all executions,
287     or only execution on the same CORBA port
288     """
289
290     if args['killall']:
291         killAllPorts()
292     elif args['portkill']:
293         givenPortKill(str(args['port']))
294         
295 # -----------------------------------------------------------------------------
296 #
297 # Definition des classes d'objets pour le lancement des Server CORBA
298 #
299
300 class Server:
301     """Generic class for CORBA server launch"""
302
303     def initArgs(self):
304         self.PID=None
305         self.CMD=[]
306         self.ARGS=[]    
307         if self.args['xterm']:
308             self.ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-hold']
309
310     def __init__(self,args):
311         self.args=args
312         self.initArgs()
313
314
315     def run(self):
316         global process_id
317         myargs=self.ARGS
318         if self.args['xterm']:
319             # (Debian) send LD_LIBRARY_PATH to children shells (xterm)
320             env_ld_library_path=['env', 'LD_LIBRARY_PATH='
321                                  + os.getenv("LD_LIBRARY_PATH")]
322             myargs = myargs +['-T']+self.CMD[:1]+['-e'] + env_ld_library_path
323         command = myargs + self.CMD
324         if verbose(): print "command = ", command
325         pid = os.spawnvp(os.P_NOWAIT, command[0], command)
326         process_id[pid]=self.CMD
327         self.PID = pid
328
329
330 class InterpServer(Server):
331     def __init__(self,args):
332         self.args=args
333         env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
334         self.CMD=['xterm', '-e']+ env_ld_library_path + ['python']
335         #self.CMD=['xterm', '-e', 'python']
336        
337     def run(self):
338         global process_id
339         command = self.CMD
340         #print "command = ", command
341         pid = os.spawnvp(os.P_NOWAIT, command[0], command)
342         process_id[pid]=self.CMD
343         self.PID = pid
344
345 # ---
346
347 class CatalogServer(Server):
348     def __init__(self,args):
349         self.args=args
350         self.initArgs()
351         self.SCMD1=['SALOME_ModuleCatalog_Server','-common']
352         self.SCMD2=[]
353         home_dir=os.getenv('HOME')
354         if home_dir is not None:
355             self.SCMD2=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')] 
356
357     def setpath(self,modules_list,modules_root_dir):
358         cata_path=[]
359         list_modules = modules_list[:]
360         list_modules.reverse()
361         if self.args["gui"] :
362             list_modules = ["KERNEL", "GUI"] + list_modules
363         else :
364             list_modules = ["KERNEL"] + list_modules
365         for module in list_modules:
366             if modules_root_dir.has_key(module):
367                 module_root_dir=modules_root_dir[module]
368                 module_cata=module+"Catalog.xml"
369                 #print "   ", module_cata
370                 if os.path.exists(os.path.join(module_root_dir,
371                                                "share",salome_subdir,
372                                                "resources",module.lower(),
373                                                module_cata)):
374                     cata_path.extend(
375                         glob.glob(os.path.join(module_root_dir,
376                                                "share",salome_subdir,
377                                                "resources",module.lower(),
378                                                module_cata)))
379                 else:
380                     cata_path.extend(
381                         glob.glob(os.path.join(module_root_dir,
382                                                "share",salome_subdir,
383                                                "resources",
384                                                module_cata)))
385                 pass
386             pass
387         self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
388
389 # ---
390
391 class SalomeDSServer(Server):
392     def __init__(self,args):
393         self.args=args
394         self.initArgs()
395         self.CMD=['SALOMEDS_Server']
396
397 # ---
398
399 class RegistryServer(Server):
400     def __init__(self,args):
401         self.args=args
402         self.initArgs()
403         self.CMD=['SALOME_Registry_Server', '--salome_session','theSession']
404
405 # ---
406
407 class ContainerCPPServer(Server):
408     def __init__(self,args):
409         self.args=args
410         self.initArgs()
411         self.CMD=['SALOME_Container','FactoryServer']
412
413 # ---
414
415 class ContainerPYServer(Server):
416     def __init__(self,args):
417         self.args=args
418         self.initArgs()
419         self.CMD=['SALOME_ContainerPy.py','FactoryServerPy']
420
421 # ---
422
423 class ContainerSUPERVServer(Server):
424     def __init__(self,args):
425         self.args=args
426         self.initArgs()
427         self.CMD=['SALOME_Container','SuperVisionContainer']
428
429 # ---
430
431 class LoggerServer(Server):
432     def __init__(self,args):
433         self.args=args
434         self.initArgs()
435         self.CMD=['SALOME_Logger_Server', 'logger.log']
436
437 # ---
438
439 class SessionServer(Server):
440     def __init__(self,args):
441         self.args = args.copy()
442         # Bug 11512 (Problems with runSalome --xterm on Mandrake and Debian Sarge)
443         self.args['xterm']=0
444         #
445         self.initArgs()
446         self.SCMD1=['SALOME_Session_Server']
447         self.SCMD2=[]
448         if 'registry' in self.args['embedded']:
449             self.SCMD1+=['--with','Registry',
450                          '(','--salome_session','theSession',')']
451         if 'moduleCatalog' in self.args['embedded']:
452             self.SCMD1+=['--with','ModuleCatalog','(','-common']
453             home_dir=os.getenv('HOME')
454             if home_dir is not None:
455                 self.SCMD2+=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')] 
456             self.SCMD2+=[')']
457         if 'study' in self.args['embedded']:
458             self.SCMD2+=['--with','SALOMEDS','(',')']
459         if 'cppContainer' in self.args['embedded']:
460             self.SCMD2+=['--with','Container','(','FactoryServer',')']
461         if 'SalomeAppEngine' in self.args['embedded']:
462             self.SCMD2+=['--with','SalomeAppEngine','(',')']
463             
464         if 'cppContainer' in self.args['standalone'] or 'cppContainer' in self.args['embedded']:
465             self.SCMD2+=['CPP']
466         if 'pyContainer' in self.args['standalone'] or 'pyContainer' in self.args['embedded']:
467             self.SCMD2+=['PY']
468         if 'supervContainer' in self.args['containers'] or 'supervContainer' in self.args['standalone']:
469             self.SCMD2+=['SUPERV']
470         if self.args['gui']:
471             try:
472                 session_gui = self.args['session_gui']
473             except KeyError:
474                 session_gui = 1
475                 pass
476             if session_gui:
477                 self.SCMD2+=['GUI']
478                 pass
479             pass
480         if self.args['splash'] and self.args['gui']:
481             self.SCMD2+=['SPLASH']
482         if self.args['noexcepthandler']:
483             self.SCMD2+=['noexcepthandler']
484         if self.args.has_key('modules'):
485             self.SCMD2+=['--modules (%s)'%":".join(self.args['modules'])]
486         if self.args.has_key('test') and len(args['test']) > 0:
487             self.SCMD2+=['--test=%s'%(",".join(args['test']))]
488
489     def setpath(self,modules_list,modules_root_dir):
490         cata_path=[]
491         list_modules = modules_list[:]
492         list_modules.reverse()
493         if self.args["gui"] :
494             list_modules = ["KERNEL", "GUI"] + list_modules
495         else :
496             list_modules = ["KERNEL"] + list_modules
497         for module in list_modules:
498             module_root_dir=modules_root_dir[module]
499             module_cata=module+"Catalog.xml"
500             #print "   ", module_cata
501             if os.path.exists(os.path.join(module_root_dir,
502                                            "share",salome_subdir,
503                                            "resources",module.lower(),
504                                            module_cata)):
505                 cata_path.extend(
506                     glob.glob(os.path.join(module_root_dir,"share",
507                                            salome_subdir,"resources",
508                                            module.lower(),module_cata)))
509             else:
510                 cata_path.extend(
511                     glob.glob(os.path.join(module_root_dir,"share",
512                                            salome_subdir,"resources",
513                                            module_cata)))
514             pass
515         if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
516             self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
517         else:
518             self.CMD=self.SCMD1 + self.SCMD2
519       
520 # ---
521
522 class ContainerManagerServer(Server):
523     def __init__(self,args):
524         self.args=args
525         self.initArgs()
526         self.SCMD1=['SALOME_ContainerManagerServer']
527         self.SCMD2=[]
528         if args["gui"] :
529             if 'registry' in self.args['embedded']:
530                 self.SCMD1+=['--with','Registry',
531                              '(','--salome_session','theSession',')']
532             if 'moduleCatalog' in self.args['embedded']:
533                 self.SCMD1+=['--with','ModuleCatalog','(','-common']
534                 self.SCMD2+=['-personal',
535                              '${HOME}/Salome/resources/CatalogModulePersonnel.xml',')']
536             if 'study' in self.args['embedded']:
537                 self.SCMD2+=['--with','SALOMEDS','(',')']
538             if 'cppContainer' in self.args['embedded']:
539                 self.SCMD2+=['--with','Container','(','FactoryServer',')']
540         
541     def setpath(self,modules_list,modules_root_dir):
542         cata_path=[]
543         list_modules = modules_list[:]
544         list_modules.reverse()
545         if self.args["gui"] :
546             list_modules = ["GUI"] + list_modules
547         for module in ["KERNEL"] + list_modules:
548             if modules_root_dir.has_key(module):
549                 module_root_dir=modules_root_dir[module]
550                 module_cata=module+"Catalog.xml"
551                 #print "   ", module_cata
552                 if os.path.exists(os.path.join(module_root_dir,
553                                                "share",salome_subdir,
554                                                "resources",module.lower(),
555                                                module_cata)):
556                     cata_path.extend(
557                         glob.glob(os.path.join(module_root_dir,"share",
558                                                self.args['appname'],"resources",
559                                                module.lower(),module_cata)))
560                 else:
561                     cata_path.extend(
562                         glob.glob(os.path.join(module_root_dir,"share",
563                                                self.args['appname'],"resources",
564                                                module_cata)))
565                 pass
566             pass
567         if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
568             self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
569         else:
570             self.CMD=self.SCMD1 + self.SCMD2
571
572 class NotifyServer(Server):
573     def __init__(self,args,modules_root_dir):
574         self.args=args
575         self.initArgs()
576         self.modules_root_dir=modules_root_dir
577         myLogName = os.environ["LOGNAME"]
578         self.CMD=['notifd','-c',
579                   self.modules_root_dir["KERNEL"] +'/share/salome/resources/kernel/channel.cfg',
580                   '-DFactoryIORFileName=/tmp/'+myLogName+'_rdifact.ior',
581                   '-DChannelIORFileName=/tmp/'+myLogName+'_rdichan.ior',
582                   '-DReportLogFile=/tmp/'+myLogName+'_notifd.report',
583                   '-DDebugLogFile=/tmp/'+myLogName+'_notifd.debug',
584                   ]
585
586 #
587 # -----------------------------------------------------------------------------
588
589 def startGUI():
590     """Salome Session Graphic User Interface activation"""
591     import Engines
592     import SALOME
593     import SALOMEDS
594     import SALOME_ModuleCatalog
595     reload(Engines)
596     reload(SALOME)
597     reload(SALOMEDS)
598     import SALOME_Session_idl
599     session=clt.waitNS("/Kernel/Session",SALOME.Session)
600     session.GetInterface()
601   
602 # -----------------------------------------------------------------------------
603
604 def startSalome(args, modules_list, modules_root_dir):
605     """Launch all SALOME servers requested by args"""
606     init_time = os.times()
607
608     if verbose(): print "startSalome ", args
609     
610     #
611     # Initialisation ORB et Naming Service
612     #
613    
614     clt=orbmodule.client()
615
616     # (non obligatoire) Lancement Logger Server
617     # et attente de sa disponibilite dans le naming service
618     #
619
620     if args['logger']:
621         myServer=LoggerServer(args)
622         myServer.run()
623         clt.waitLogger("Logger")
624
625     # Notify Server launch
626     #
627
628     if verbose(): print "Notify Server to launch"
629
630     myServer=NotifyServer(args,modules_root_dir)
631     myServer.run()
632
633     # Lancement Session Server (to show splash ASAP)
634     #
635
636     if args["gui"]:
637         mySessionServ = SessionServer(args)
638         mySessionServ.setpath(modules_list,modules_root_dir)
639         mySessionServ.run()
640
641     #
642     # Lancement Registry Server,
643     # attente de la disponibilite du Registry dans le Naming Service
644     #
645
646     if ('registry' not in args['embedded']) | (args["gui"] == 0) :
647         myServer=RegistryServer(args)
648         myServer.run()
649         clt.waitNSPID("/Registry",myServer.PID)
650
651     #
652     # Lancement Catalog Server,
653     # attente de la disponibilite du Catalog Server dans le Naming Service
654     #
655     
656
657     if ('moduleCatalog' not in args['embedded']) | (args["gui"] == 0):
658         cataServer=CatalogServer(args)
659         cataServer.setpath(modules_list,modules_root_dir)
660         cataServer.run()
661         import SALOME_ModuleCatalog
662         clt.waitNSPID("/Kernel/ModulCatalog",cataServer.PID,SALOME_ModuleCatalog.ModuleCatalog)
663
664     #
665     # Lancement SalomeDS Server,
666     # attente de la disponibilite du SalomeDS dans le Naming Service
667     #
668
669     #print "ARGS = ",args
670     if ('study' not in args['embedded']) | (args["gui"] == 0):
671         print "RunStudy"
672         myServer=SalomeDSServer(args)
673         myServer.run()
674         clt.waitNSPID("/myStudyManager",myServer.PID)
675
676     #
677     # Lancement ContainerManagerServer
678     #
679     
680     myCmServer = ContainerManagerServer(args)
681     myCmServer.setpath(modules_list,modules_root_dir)
682     myCmServer.run()
683
684
685     from Utils_Identity import getShortHostName
686     
687     if os.getenv("HOSTNAME") == None:
688         if os.getenv("HOST") == None:
689             os.environ["HOSTNAME"]=getShortHostName()
690         else:
691             os.environ["HOSTNAME"]=os.getenv("HOST")
692
693     theComputer = getShortHostName()
694     
695     #
696     # Lancement Container C++ local,
697     # attente de la disponibilite du Container C++ local dans le Naming Service
698     #
699
700     if ('cppContainer' in args['standalone']) | (args["gui"] == 0):
701         myServer=ContainerCPPServer(args)
702         myServer.run()
703         clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID)
704
705     #
706     # Lancement Container Python local,
707     # attente de la disponibilite du Container Python local
708     # dans le Naming Service
709     #
710
711     if 'pyContainer' in args['standalone']:
712         myServer=ContainerPYServer(args)
713         myServer.run()
714         clt.waitNSPID("/Containers/" + theComputer + "/FactoryServerPy",myServer.PID)
715
716     #
717     # Lancement Container Supervision local,
718     # attente de la disponibilite du Container Supervision local
719     # dans le Naming Service
720     #
721
722     if 'supervContainer' in args['standalone']:
723         myServer=ContainerSUPERVServer(args)
724         myServer.run()
725         clt.waitNSPID("/Containers/" + theComputer + "/SuperVisionContainer",myServer.PID)
726
727     #
728     # Attente de la disponibilite du Session Server dans le Naming Service
729     #
730     
731     if args["gui"]:
732 ##----------------        
733         import Engines
734         import SALOME
735         import SALOMEDS
736         import SALOME_ModuleCatalog
737         reload(Engines)
738         reload(SALOME)
739         reload(SALOMEDS)
740         import SALOME_Session_idl
741         session=clt.waitNSPID("/Kernel/Session",mySessionServ.PID,SALOME.Session)
742
743     end_time = os.times()
744     if verbose(): print
745     print "Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
746                                                          - init_time[4])
747
748     # ASV start GUI without Loader
749     #if args['gui']:
750     #    session.GetInterface()
751
752     #
753     # additionnal external python interpreters
754     #
755     nbaddi=0
756     
757     try:
758         if 'interp' in args:
759             if args['interp']:
760                 nbaddi = int(args['interp'][0])
761     except:
762         import traceback
763         traceback.print_exc()
764         print "-------------------------------------------------------------"
765         print "-- to get an external python interpreter:runSalome --interp=1"
766         print "-------------------------------------------------------------"
767         
768     print "additional external python interpreters: ", nbaddi
769     if nbaddi:
770         for i in range(nbaddi):
771             print "i=",i
772             anInterp=InterpServer(args)
773             anInterp.run()
774     
775     return clt
776
777 # -----------------------------------------------------------------------------
778
779 def useSalome(args, modules_list, modules_root_dir):
780     """
781     Launch all SALOME servers requested by args,
782     save list of process, give info to user,
783     show registered objects in Naming Service.
784     """
785     
786     clt=None
787     try:
788         clt = startSalome(args, modules_list, modules_root_dir)
789     except:
790         import traceback
791         traceback.print_exc()
792         print
793         print
794         print "--- erreur au lancement Salome ---"
795         
796     #print process_id
797
798     from killSalomeWithPort import getPiDict
799     filedict = getPiDict(args['port'])
800
801     process_ids = []
802     try:
803         fpid=open(filedict, 'r')
804         process_ids=pickle.load(fpid)
805         fpid.close()
806     except:
807         pass
808     
809     fpid=open(filedict, 'w')
810     process_ids.append(process_id)
811     pickle.dump(process_ids,fpid)
812     fpid.close()
813     
814     if verbose(): print """
815     Saving of the dictionary of Salome processes in %s
816     To kill SALOME processes from a console (kill all sessions from all ports):
817       python killSalome.py 
818     To kill SALOME from the present interpreter, if it is not closed :
819       killLocalPort()      --> kill this session
820                                (use CORBA port from args of runSalome)
821       givenPortKill(port)  --> kill a specific session with given CORBA port 
822       killAllPorts()       --> kill all sessions
823     
824     runSalome, with --killall option, starts with killing
825     the processes resulting from the previous execution.
826     """%filedict
827     
828     #
829     #  Impression arborescence Naming Service
830     #
831     
832     if clt != None:
833         if verbose():
834             print
835             print " --- registered objects tree in Naming Service ---"
836             clt.showNS()
837             pass
838         
839         # run python scripts, passed via -t option
840         toimport = args['pyscript']
841         i = 0
842         while i < len( toimport ) :
843             if toimport[ i ] == 'killall':
844                 killAllPorts()
845                 import sys
846                 sys.exit(0)
847             else:
848                 print 'importing',toimport[ i ]
849                 doimport = 'import ' + toimport[ i ]
850                 exec doimport
851             i = i + 1
852
853     return clt
854
855 # -----------------------------------------------------------------------------
856
857 def registerEnv(args, modules_list, modules_root_dir):
858     """
859     Register args, modules_list, modules_root_dir in a file
860     for further use, when SALOME is launched embedded in an other application.
861     """
862     fileEnv = '/tmp/' + os.getenv('USER') + "_" + str(args['port']) \
863             + '_' + args['appname'].upper() + '_env'
864     fenv=open(fileEnv,'w')
865     pickle.dump((args, modules_list, modules_root_dir),fenv)
866     fenv.close()
867     os.environ["SALOME_LAUNCH_CONFIG"] = fileEnv
868
869 # -----------------------------------------------------------------------------
870
871 def searchFreePort(args, save_config=1):
872     print "Searching for a free port for naming service:",
873     NSPORT=2810
874     limit=NSPORT
875     limit=limit+10
876     while 1:
877         import os
878         status = os.system("netstat -ltn | grep -E :%s > /dev/null 2>&1"%(NSPORT))
879         if status:
880             print "%s - OK"%(NSPORT)
881             #
882             from os import getpid
883             tmp_file = '/tmp/hostname_%s'%(getpid())
884             from os import system
885             system('hostname > %s'%(tmp_file))
886             f = open(tmp_file)
887             myhost = f.read()
888             myhost = myhost[:-1]
889             f.close()
890             system('rm -f %s'%(tmp_file))
891             #
892             home = os.environ['HOME']
893             appli=os.environ.get("APPLI")
894             if appli is not None:
895                 home='%s/%s'%(home,appli)
896                 pass
897             #
898             os.environ['OMNIORB_CONFIG'] = '%s/.omniORB_%s_%s.cfg'%(home, myhost, NSPORT)
899             initref = "NameService=corbaname::%s:%s"%(myhost, NSPORT)
900             os.environ['NSPORT'] = "%s"%(NSPORT)
901             os.environ['NSHOST'] = "%s"%(myhost)
902             f = open(os.environ['OMNIORB_CONFIG'], "w")
903             import CORBA
904             if CORBA.ORB_ID == "omniORB4":
905                 f.write("InitRef = %s\n"%(initref))
906             else:
907                 f.write("ORBInitRef %s\n"%(initref))
908                 pass
909             f.close()
910             args['port'] = os.environ['NSPORT']
911             #
912             if save_config:
913                 from os import system
914                 system('ln -sf %s %s/.omniORB_last.cfg'%(os.environ['OMNIORB_CONFIG'], home))
915                 pass
916             #
917             break
918         print "%s"%(NSPORT),
919         if NSPORT == limit:
920             msg  = "\n"
921             msg += "Can't find a free port to launch omniNames\n"
922             msg += "Try to kill the running servers and then launch SALOME again.\n"
923             raise msg
924         NSPORT=NSPORT+1
925         pass
926     return
927     
928 # -----------------------------------------------------------------------------
929
930 def no_main():
931     """Salome Launch, when embedded in other application"""
932     fileEnv = os.environ["SALOME_LAUNCH_CONFIG"]
933     fenv=open(fileEnv,'r')
934     args, modules_list, modules_root_dir = pickle.load(fenv)
935     fenv.close()
936     kill_salome(args)
937     searchFreePort(args, 0)
938     clt = useSalome(args, modules_list, modules_root_dir)
939     return clt
940
941 # -----------------------------------------------------------------------------
942
943 def main():
944     """Salome launch as a main application"""
945     import sys
946     if len(sys.argv) == 2:
947         if sys.argv[1] == "-nothing":
948             searchFreePort({})
949             import os
950             print "port:%s"%(os.environ['NSPORT'])
951             import sys
952             sys.exit(0)
953             pass
954         pass
955     save_config = 1
956     import sys
957     if len(sys.argv) > 1:
958         if sys.argv[1] == "--nosave-config":
959             save_config = 0
960             sys.argv[1:2] = []
961             pass
962         pass
963     #
964     args, modules_list, modules_root_dir = get_config()
965     kill_salome(args)
966     searchFreePort(args, save_config)
967     set_env(args, modules_list, modules_root_dir)
968     clt = useSalome(args, modules_list, modules_root_dir)
969     return clt,args
970
971 # -----------------------------------------------------------------------------
972
973 if __name__ == "__main__":
974    import user
975    clt,args = main()