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