Salome HOME
mergefrom branch BR_V511_PR tag mergeto_trunk_03feb09
[modules/yacs.git] / src / wrappergen / bin / HXX2SALOME_GENERIC_CLASS_NAME_SRC / bin / runSalome.py
1 #!/usr/bin/env python
2 #  Copyright (C) 2006-2008  CEA/DEN, EDF R&D
3 #
4 #  This library is free software; you can redistribute it and/or
5 #  modify it under the terms of the GNU Lesser General Public
6 #  License as published by the Free Software Foundation; either
7 #  version 2.1 of the License.
8 #
9 #  This library is distributed in the hope that it will be useful,
10 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
11 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 #  Lesser General Public License for more details.
13 #
14 #  You should have received a copy of the GNU Lesser General Public
15 #  License along with this library; if not, write to the Free Software
16 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 #
18 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 #
20 usage="""USAGE: runSalome.py [options]
21
22 [command line options] :
23 --help                        : affichage de l'aide
24 --gui                         : lancement du GUI
25 --logger                      : redirection des messages dans un fichier
26 --xterm                       : les serveurs ouvrent une fenêtre xterm et les messages sont affichés dans cette fenêtre
27 --modules=module1,module2,... : où modulen est le nom d'un module Salome à charger dans le catalogue
28 --containers=cpp,python,superv: lancement des containers cpp, python et de supervision
29 --killall                     : arrêt des serveurs de salome
30
31  La variable d'environnement <modulen>_ROOT_DIR doit etre préalablement
32  positionnée (modulen doit etre en majuscule).
33  KERNEL_ROOT_DIR est obligatoire.
34 """
35
36 # -----------------------------------------------------------------------------
37 #
38 # Fonction d'arrêt de salome
39 #
40
41 def killSalome():
42    print "arret des serveurs SALOME"
43    for pid, cmd in process_id.items():
44       print "arret du process %s : %s"% (pid, cmd[0])
45       try:
46         os.kill(pid,signal.SIGKILL)
47       except:
48          print "  ------------------ process %s : %s inexistant"% (pid, cmd[0])
49    print "arret du naming service"
50    os.system("killall -9 omniNames")
51    
52 # -----------------------------------------------------------------------------
53 #
54 # Fonction message
55 #
56
57 def message(code, msg=''):
58     if msg: print msg
59     sys.exit(code)
60
61 import sys,os,string,glob,time,signal,pickle,getopt
62
63 init_time=os.times()
64 opts, args=getopt.getopt(sys.argv[1:], 'hmglxck:', ['help','modules=','gui','logger','xterm','containers=','killall'])
65 modules_root_dir={}
66 process_id={}
67 liste_modules={}
68 liste_containers={}
69 with_gui=0
70 with_logger=0
71 with_xterm=0
72
73 with_container_cpp=0
74 with_container_python=0
75 with_container_superv=0
76
77 try:
78   for o, a in opts:
79     if o in ('-h', '--help'):
80       print usage
81       sys.exit(1)
82     elif o in ('-g', '--gui'):
83       with_gui=1
84     elif o in ('-l', '--logger'):
85       with_logger=1
86     elif o in ('-x', '--xterm'):
87       with_xterm=1
88     elif o in ('-m', '--modules'):
89       liste_modules = [x.upper() for x in a.split(',')]
90     elif o in ('-c', '--containers'):
91       liste_containers = [x.lower() for x in a.split(',')]
92       for r in liste_containers:
93         if r not in ('cpp', 'python', 'superv'):
94            message(1, 'Invalid -c/--containers option: %s' % a)
95       if 'cpp' in liste_containers:
96            with_container_cpp=1
97       else:
98            with_container_cpp=0
99       if 'python' in liste_containers:
100            with_container_python=1
101       else:
102            with_container_python=0
103       if 'superv' in liste_containers:
104            with_container_superv=1
105       else:
106            with_container_superv=0
107     elif o in ('-k', '--killall'):
108       filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict'
109       #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
110       found = 0
111       try:
112          fpid=open(filedict, 'r')
113          found = 1
114       except:
115          print "le fichier %s des process SALOME n'est pas accessible"% filedict
116
117       if found:
118          process_id=pickle.load(fpid)
119          fpid.close()
120          killSalome()
121          process_id={}
122          os.remove(filedict)
123         
124 except getopt.error, msg:
125   print usage
126   sys.exit(1)
127
128 # -----------------------------------------------------------------------------
129 #
130 # Vérification des variables d'environnement
131 #
132 try:
133   kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
134   modules_root_dir["KERNEL"]=kernel_root_dir
135 except:
136   print usage
137   sys.exit(1)
138
139 for module in liste_modules :
140    try:
141       module=module.upper()
142       module_root_dir=os.environ[module +"_ROOT_DIR"]
143       modules_root_dir[module]=module_root_dir
144    except:
145       print usage
146       sys.exit(1)
147
148 # il faut KERNEL en premier dans la liste des modules
149 # - l'ordre des modules dans le catalogue sera identique
150 # - la liste des modules presents dans le catalogue est exploitée pour charger les modules CORBA python,
151 #   il faut charger les modules python du KERNEL en premier
152
153 if "KERNEL" in liste_modules:liste_modules.remove("KERNEL")
154 liste_modules[:0]=["KERNEL"]
155 #print liste_modules
156 #print modules_root_dir
157
158 os.environ["SALOMEPATH"]=":".join(modules_root_dir.values())
159 if "SUPERV" in liste_modules:with_container_superv=1
160
161
162 # -----------------------------------------------------------------------------
163 #
164 # Définition des classes d'objets pour le lancement des Server CORBA
165 #
166
167 class Server:
168    CMD=[]
169    if with_xterm:
170         ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-e']
171    else:
172         ARGS=[] 
173
174    def run(self):
175       args = self.ARGS+self.CMD
176       #print "args = ", args
177       pid = os.spawnvp(os.P_NOWAIT, args[0], args)
178       process_id[pid]=self.CMD
179
180 class CatalogServer(Server):
181    SCMD1=['SALOME_ModuleCatalog_Server','-common']
182    SCMD2=['-personal','${HOME}/Salome/resources/CatalogModulePersonnel.xml'] 
183
184    def setpath(self,liste_modules):
185       cata_path=[]
186       for module in liste_modules:
187           module_root_dir=modules_root_dir[module]
188           module_cata=module+"Catalog.xml"
189           print "   ", module_cata
190           cata_path.extend(glob.glob(os.path.join(module_root_dir,"share","salome","resources",module_cata)))
191       self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
192
193 class SalomeDSServer(Server):
194    CMD=['SALOMEDS_Server']
195
196 class RegistryServer(Server):
197    CMD=['SALOME_Registry_Server', '--salome_session','theSession']
198
199 class ContainerCPPServer(Server):
200    CMD=['SALOME_Container','FactoryServer','-ORBInitRef','NameService=corbaname::localhost']
201
202 class ContainerPYServer(Server):
203    CMD=['SALOME_ContainerPy.py','FactoryServerPy','-ORBInitRef','NameService=corbaname::localhost']
204
205 class ContainerSUPERVServer(Server):
206    CMD=['SALOME_Container','SuperVisionContainer','-ORBInitRef','NameService=corbaname::localhost']
207
208 class LoggerServer(Server):
209    CMD=['SALOME_Logger_Server', 'logger.log']
210
211 class SessionLoader(Server):
212    CMD=['SALOME_Session_Loader']
213    if with_container_cpp:
214        CMD=CMD+['CPP']
215    if with_container_python:
216        CMD=CMD+['PY']
217    if with_container_superv:
218        CMD=CMD+['SUPERV']
219    if with_gui:
220        CMD=CMD+['GUI']
221
222 class SessionServer(Server):
223    CMD=['SALOME_Session_Server']
224
225 class NotifyServer(Server):
226    CMD=['notifd','-c','${KERNEL_ROOT_DIR}/share/salome/resources/channel.cfg -DFactoryIORFileName=/tmp/${LOGNAME}_rdifact.ior -DChannelIORFileName=/tmp/${LOGNAME}_rdichan.ior']
227
228 # -----------------------------------------------------------------------------
229 #
230 # Fonction de test
231 #
232
233 def test(clt):
234    """
235         Test function that creates an instance of HXX2SALOME_GENERIC_CLASS_NAME component
236         usage : hello=test(clt)
237    """
238    # create an LifeCycleCORBA instance
239    import LifeCycleCORBA 
240    lcc = LifeCycleCORBA.LifeCycleCORBA(clt.orb)
241    import HXX2SALOME_GENERIC_CLASS_NAME_ORB
242    hello = lcc.FindOrLoadComponent("FactoryServer", "HXX2SALOME_GENERIC_CLASS_NAME")
243    return hello
244
245 # -----------------------------------------------------------------------------
246 #
247 # Fonctions helper pour ajouter des variables d'environnement
248 #
249
250 def add_path(directory):
251    os.environ["PATH"]=directory + ":" + os.environ["PATH"]
252
253 def add_ld_library_path(directory):
254    os.environ["LD_LIBRARY_PATH"]=directory + ":" + os.environ["LD_LIBRARY_PATH"]
255
256 def add_python_path(directory):
257    os.environ["PYTHONPATH"]=directory + ":" + os.environ["PYTHONPATH"]
258    sys.path[:0]=[directory]
259
260 # -----------------------------------------------------------------------------
261 #
262 # initialisation des variables d'environnement
263 #
264
265 python_version="python%d.%d" % sys.version_info[0:2]
266
267 #
268 # Ajout du chemin d'acces aux executables de KERNEL dans le PATH
269 #
270
271 add_path(os.path.join(kernel_root_dir,"bin","salome"))
272 #print "PATH=",os.environ["PATH"]
273
274 #
275 # Ajout des modules dans le LD_LIBRARY_PATH
276 #
277 for module in liste_modules:
278     module_root_dir=modules_root_dir[module]
279     add_ld_library_path(os.path.join(module_root_dir,"lib","salome"))
280 #print "LD_LIBRARY_PATH=",os.environ["LD_LIBRARY_PATH"]
281
282 #
283 # Ajout des modules dans le PYTHONPATH (KERNEL prioritaire, donc en dernier)
284 #
285
286 liste_modules_reverse=liste_modules[:]
287 liste_modules_reverse.reverse()
288 #print liste_modules
289 #print liste_modules_reverse
290 for module in liste_modules_reverse:
291     module_root_dir=modules_root_dir[module]
292     add_python_path(os.path.join(module_root_dir,"bin","salome"))
293     add_python_path(os.path.join(module_root_dir,"lib",python_version,"site-packages","salome"))
294     add_python_path(os.path.join(module_root_dir,"lib","salome"))
295     add_python_path(os.path.join(module_root_dir,"lib",python_version,"site-packages","salome","shared_modules"))
296
297 #print "PYTHONPATH=",sys.path
298
299 import orbmodule
300
301 #
302 # -----------------------------------------------------------------------------
303 #
304
305 def startGUI():
306   import SALOME
307   session=clt.waitNS("/Kernel/Session",SALOME.Session)
308
309   #
310   # Activation du GUI de Session Server
311   #
312         
313   session.GetInterface()
314   
315 #
316 # -----------------------------------------------------------------------------
317 #
318
319 def startSalome():
320
321   #
322   # Lancement Session Loader
323   #
324   SessionLoader().run()
325
326   #
327   # Initialisation ORB et Naming Service
328   #
329   clt=orbmodule.client()
330
331   # (non obligatoire) Lancement Logger Server et attente de sa 
332   #  disponibilite dans le naming service
333   #
334   if with_logger:
335         LoggerServer().run()
336         clt.waitLogger("Logger")
337
338   #
339   # Lancement Registry Server
340   #
341   RegistryServer().run()
342
343   #
344   # Attente de la disponibilité du Registry dans le Naming Service
345   #
346   clt.waitNS("/Registry")
347
348   #
349   # Lancement Catalog Server
350   #
351   cataServer=CatalogServer()
352   cataServer.setpath(liste_modules)
353   cataServer.run()
354
355   #
356   # Attente de la disponibilité du Catalog Server dans le Naming Service
357   #
358   import SALOME_ModuleCatalog
359   clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
360
361   #
362   # Lancement SalomeDS Server
363   #
364   os.environ["CSF_PluginDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
365   os.environ["CSF_SALOMEDS_ResourcesDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
366   SalomeDSServer().run()
367
368   if "GEOM" in liste_modules:
369         print "GEOM OCAF Resources"
370         os.environ["CSF_GEOMDS_ResourcesDefaults"]=os.path.join(modules_root_dir["GEOM"],"share","salome","resources")
371
372
373   #
374   # Attente de la disponibilité du SalomeDS dans le Naming Service
375   #
376   clt.waitNS("/myStudyManager")
377
378   #
379   # Lancement Session Server
380   #
381   SessionServer().run()
382
383   #
384   # Attente de la disponibilité du Session Server dans le Naming Service
385   #
386   import SALOME
387   session=clt.waitNS("/Kernel/Session",SALOME.Session)
388
389   #
390   # Lancement containers
391   #
392   theComputer = os.getenv("HOSTNAME")
393   theComputer = theComputer.split('.')[0]
394
395   #
396   # Lancement Container C++ local
397   #
398   if with_container_cpp:
399           ContainerCPPServer().run()
400           #
401           # Attente de la disponibilité du Container C++ local 
402           # dans le Naming Service
403           #
404           clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
405   #
406   # Lancement Container Python local
407   #
408   if with_container_python:
409           ContainerPYServer().run()
410           #
411           # Attente de la disponibilité du Container Python local 
412           #  dans le Naming Service
413           #
414           clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy")
415
416   if with_container_superv:
417         #
418         # Lancement Container Supervision local
419         #
420         ContainerSUPERVServer().run()
421         #
422         # Attente de la disponibilité du Container Supervision local 
423         # dans le Naming Service
424         #
425         clt.waitNS("/Containers/" + theComputer + "/SuperVisionContainer")
426   #
427   # Activation du GUI de Session Server
428   #
429   #session.GetInterface()
430
431   end_time = os.times()
432   print
433   print "Start SALOME, elpased time : %5.1f seconds"% (end_time[4] - init_time[4])
434
435   return clt
436
437 #
438 # -----------------------------------------------------------------------------
439 #
440
441 if __name__ == "__main__":
442    clt=None
443    try:
444       clt = startSalome()
445    except:
446       print
447       print
448       print "--- erreur au lancement Salome ---"
449    
450    #print process_id
451    
452    
453    filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict'
454    #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
455    
456    fpid=open(filedict, 'w')
457    pickle.dump(process_id,fpid)
458    fpid.close()
459    
460    print """
461
462 Sauvegarde du dictionnaire des process dans , %s
463 Pour tuer les process SALOME, executer : python killSalome.py depuis
464 une console, ou bien killSalome() depuis le present interpreteur,
465 s'il n'est pas fermé.
466
467 runSalome, avec l'option --killall, commence par tuer les process restants 
468 d'une execution précédente.
469
470 Pour lancer uniquement le GUI, executer startGUI() depuis le present interpreteur,
471 s'il n'est pas fermé.
472
473 """ % filedict
474    
475    #
476    #  Impression arborescence Naming Service
477    #
478    
479    if clt != None:
480      print
481      print " --- registered objects tree in Naming Service ---"
482      clt.showNS()
483      session=clt.waitNS("/Kernel/Session")
484      catalog=clt.waitNS("/Kernel/ModulCatalog")
485      import socket
486      container =  clt.waitNS("/Containers/" + socket.gethostname().split('.')[0] + "/FactoryServerPy")
487    
488    if os.path.isfile("~/.salome/pystartup"):
489       f=open(os.path.expanduser("~/.salome/pystartup"),'w')
490       PYTHONSTARTUP=f.read()
491       f.close()
492    else:
493       PYTHONSTARTUP="""
494 # Add auto-completion and a stored history file of commands to your Python
495 # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
496 # bound to the TAB key by default (you can change it - see readline docs).
497 #
498 # Store the history in ~/.salome/pyhistory, 
499 #
500 import atexit
501 import os
502 import readline
503 import rlcompleter
504 readline.parse_and_bind('tab: complete')
505
506 historyPath = os.path.expanduser("~/.salome/pyhistory")
507
508 def save_history(historyPath=historyPath):
509     import readline
510     readline.write_history_file(historyPath)
511
512 if os.path.exists(historyPath):
513     readline.read_history_file(historyPath)
514
515 atexit.register(save_history)
516 del os, atexit, readline, rlcompleter, save_history, historyPath
517 """
518       f=open(os.path.expanduser("~/.salome/pystartup"),'w')
519       f.write(PYTHONSTARTUP)
520       f.close()
521
522    exec PYTHONSTARTUP in {}
523