Salome HOME
PR: On DEBIAN Woody, need to give LD_LIBRARY_PATH in args for xterm
[modules/yacs.git] / 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', '-hold', '-e']
154    else:
155         ARGS=[] 
156
157    def run(self):
158       # (Debian) Transfert variable LD_LIBRARY_PATH aux shells fils (xterm)
159       env_ld_library_path=['env', 'LD_LIBRARY_PATH='+ os.getenv("LD_LIBRARY_PATH")]
160       args = self.ARGS+ env_ld_library_path + self.CMD
161       args = self.ARGS+self.CMD
162       #print "args = ", args
163       pid = os.spawnvp(os.P_NOWAIT, args[0], args)
164       process_id[pid]=self.CMD
165
166 class CatalogServer(Server):
167    SCMD1=['SALOME_ModuleCatalog_Server','-common']
168    SCMD2=['-personal','${HOME}/Salome/resources/CatalogModulePersonnel.xml'] 
169
170    def setpath(self,liste_modules):
171       cata_path=[]
172       for module in liste_modules:
173           module_root_dir=modules_root_dir[module]
174           module_cata=module+"Catalog.xml"
175           print "   ", module_cata
176           cata_path.extend(glob.glob(os.path.join(module_root_dir,"share","salome","resources",module_cata)))
177       self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
178
179 class SalomeDSServer(Server):
180    CMD=['SALOMEDS_Server']
181
182 class RegistryServer(Server):
183    CMD=['SALOME_Registry_Server', '--salome_session','theSession']
184
185 class ContainerCPPServer(Server):
186    CMD=['SALOME_Container','FactoryServer','-ORBInitRef','NameService=corbaname::localhost']
187
188 class ContainerPYServer(Server):
189    CMD=['SALOME_ContainerPy.py','FactoryServerPy','-ORBInitRef','NameService=corbaname::localhost']
190
191 class ContainerSUPERVServer(Server):
192    CMD=['SALOME_Container','SuperVisionContainer','-ORBInitRef','NameService=corbaname::localhost']
193
194 class LoggerServer(Server):
195    CMD=['SALOME_Logger_Server', 'logger.log']
196
197 class SessionLoader(Server):
198    CMD=['SALOME_Session_Loader']
199    if with_container_cpp:
200        CMD=CMD+['CPP']
201    if with_container_python:
202        CMD=CMD+['PY']
203    if with_container_superv:
204        CMD=CMD+['SUPERV']
205    if with_gui:
206        CMD=CMD+['GUI']
207
208 class SessionServer(Server):
209    CMD=['SALOME_Session_Server']
210
211 class NotifyServer(Server):
212    CMD=['notifd','-c','${KERNEL_ROOT_DIR}/share/salome/resources/channel.cfg -DFactoryIORFileName=/tmp/${LOGNAME}_rdifact.ior -DChannelIORFileName=/tmp/${LOGNAME}_rdichan.ior']
213
214 # -----------------------------------------------------------------------------
215 #
216 # Fonction de test
217 #
218
219 def test(clt):
220    # create an LifeCycleCORBA instance
221    import LifeCycleCORBA 
222    lcc = LifeCycleCORBA.LifeCycleCORBA(clt.orb)
223    med = lcc.FindOrLoadComponent("FactoryServer", "MED")
224    #pycalc = lcc.FindOrLoadComponent("FactoryServerPy", "CalculatorPy")
225
226 # -----------------------------------------------------------------------------
227 #
228 # Fonctions helper pour ajouter des variables d'environnement
229 #
230
231 def add_path(directory):
232    os.environ["PATH"]=directory + ":" + os.environ["PATH"]
233
234 def add_ld_library_path(directory):
235    os.environ["LD_LIBRARY_PATH"]=directory + ":" + os.environ["LD_LIBRARY_PATH"]
236
237 def add_python_path(directory):
238    os.environ["PYTHONPATH"]=directory + ":" + os.environ["PYTHONPATH"]
239    sys.path[:0]=[directory]
240
241 # -----------------------------------------------------------------------------
242 #
243 # initialisation des variables d'environnement
244 #
245
246 python_version="python%d.%d" % sys.version_info[0:2]
247
248 #
249 # Ajout du chemin d'acces aux executables de KERNEL dans le PATH
250 #
251
252 add_path(os.path.join(kernel_root_dir,"bin","salome"))
253 #print "PATH=",os.environ["PATH"]
254
255 #
256 # Ajout des modules dans le LD_LIBRARY_PATH
257 #
258 for module in liste_modules:
259     module_root_dir=modules_root_dir[module]
260     add_ld_library_path(os.path.join(module_root_dir,"lib","salome"))
261
262 os.environ["SALOME_trace"]="local"
263 if with_logger:
264    os.environ["SALOME_trace"]="with_logger"
265    locdir=os.environ['PWD']
266    libtracedir=os.path.join(locdir,"libSalomeTrace")
267    libtrace = os.path.join(kernel_root_dir,"lib","salome","libSALOMELoggerClient.so.0.0.0")
268    libtraceln = os.path.join(libtracedir,"libSALOMELocalTrace.so")
269    aCommand = 'rm -rf ' + libtracedir + "; "
270    aCommand += 'mkdir ' + libtracedir + "; "
271    aCommand += 'ln -s ' + libtrace + " " + libtraceln + "; "
272    aCommand += 'ln -s ' + libtrace + " " + libtraceln + ".0; "
273    aCommand += 'ln -s ' + libtrace + " " + libtraceln + ".0.0.0; "
274    os.system(aCommand)
275    add_ld_library_path(libtracedir)
276    
277 #print "LD_LIBRARY_PATH=",os.environ["LD_LIBRARY_PATH"]
278
279 #
280 # Ajout des modules dans le PYTHONPATH (KERNEL prioritaire, donc en dernier)
281 #
282
283 liste_modules_reverse=liste_modules[:]
284 liste_modules_reverse.reverse()
285 #print liste_modules
286 #print liste_modules_reverse
287 for module in liste_modules_reverse:
288     module_root_dir=modules_root_dir[module]
289     add_python_path(os.path.join(module_root_dir,"bin","salome"))
290     add_python_path(os.path.join(module_root_dir,"lib",python_version,"site-packages","salome"))
291     add_python_path(os.path.join(module_root_dir,"lib","salome"))
292     add_python_path(os.path.join(module_root_dir,"lib",python_version,"site-packages","salome","shared_modules"))
293
294 #print "PYTHONPATH=",sys.path
295
296 import orbmodule
297
298 #
299 # -----------------------------------------------------------------------------
300 #
301
302 def startGUI():
303   import SALOME
304   session=clt.waitNS("/Kernel/Session",SALOME.Session)
305
306   #
307   # Activation du GUI de Session Server
308   #
309         
310   session.GetInterface()
311   
312 #
313 # -----------------------------------------------------------------------------
314 #
315
316 def startSalome():
317
318   #
319   # Lancement Session Loader
320   #
321
322   if with_gui:
323      SessionLoader().run()
324
325   #
326   # Initialisation ORB et Naming Service
327   #
328    
329   clt=orbmodule.client()
330
331   # (non obligatoire) Lancement Logger Server et attente de sa disponibilite dans le naming service
332   #
333
334   if with_logger:
335         LoggerServer().run()
336         clt.waitLogger("Logger")
337
338
339   #
340   # Lancement Registry Server
341   #
342
343   RegistryServer().run()
344
345   #
346   # Attente de la disponibilité du Registry dans le Naming Service
347   #
348
349   clt.waitNS("/Registry")
350
351   #
352   # Lancement Catalog Server
353   #
354
355   cataServer=CatalogServer()
356   cataServer.setpath(liste_modules)
357   cataServer.run()
358
359   #
360   # Attente de la disponibilité du Catalog Server dans le Naming Service
361   #
362
363   import SALOME_ModuleCatalog
364   clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
365
366   #
367   # Lancement SalomeDS Server
368   #
369
370   os.environ["CSF_PluginDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
371   os.environ["CSF_SALOMEDS_ResourcesDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
372   SalomeDSServer().run()
373
374   if "GEOM" in liste_modules:
375         print "GEOM OCAF Resources"
376         os.environ["CSF_GEOMDS_ResourcesDefaults"]=os.path.join(modules_root_dir["GEOM"],"share","salome","resources")
377
378
379   #
380   # Attente de la disponibilité du SalomeDS dans le Naming Service
381   #
382
383   clt.waitNS("/myStudyManager")
384
385   #
386   # Lancement Session Server
387   #
388
389   SessionServer().run()
390
391   #
392   # Attente de la disponibilité du Session Server dans le Naming Service
393   #
394
395   import SALOME
396   session=clt.waitNS("/Kernel/Session",SALOME.Session)
397
398   if os.getenv("HOSTNAME") == None:
399      if os.getenv("HOST") == None:
400         os.environ["HOSTNAME"]="localhost"
401      else:
402         os.environ["HOSTNAME"]=os.getenv("HOST")
403   
404   theComputer = os.getenv("HOSTNAME")
405   computerSplitName = theComputer.split('.')
406   theComputer = computerSplitName[0]
407   
408   #
409   # Lancement Container C++ local
410   #
411   if with_container_cpp:
412           ContainerCPPServer().run()
413
414           #
415           # Attente de la disponibilité du Container C++ local dans le Naming Service
416           #
417
418           clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
419
420   #
421   # Lancement Container Python local
422   #
423
424   if with_container_python:
425           ContainerPYServer().run()
426
427           #
428           # Attente de la disponibilité du Container Python local dans le Naming Service
429           #
430         
431           clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy")
432
433   if with_container_superv:
434
435         #
436         # Lancement Container Supervision local
437         #
438
439         ContainerSUPERVServer().run()
440
441         #
442         # Attente de la disponibilité du Container Supervision local dans le Naming Service
443         #
444
445         clt.waitNS("/Containers/" + theComputer + "/SuperVisionContainer")
446
447
448   #
449   # Activation du GUI de Session Server
450   #
451         
452   #session.GetInterface()
453
454   end_time = os.times()
455   print
456   print "Start SALOME, elpased time : %5.1f seconds"% (end_time[4] - init_time[4])
457
458   return clt
459
460 #
461 # -----------------------------------------------------------------------------
462 #
463
464 if __name__ == "__main__":
465    clt=None
466    try:
467       clt = startSalome()
468    except:
469       print
470       print
471       print "--- erreur au lancement Salome ---"
472    
473    #print process_id
474    
475    
476    filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict'
477    #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
478    
479    fpid=open(filedict, 'w')
480    pickle.dump(process_id,fpid)
481    fpid.close()
482    
483    print
484    print "Sauvegarde du dictionnaire des process dans ", filedict
485    print "Pour tuer les process SALOME, executer : python killSalome.py depuis"
486    print "une console, ou bien killSalome() depuis le present interpreteur,"
487    print "s'il n'est pas fermé."
488    print
489    print "runSalome, avec l'option --killall, commence par tuer les process restants d'une execution précédente."
490    print
491    print "Pour lancer uniquement le GUI, executer startGUI() depuis le present interpreteur,"
492    print "s'il n'est pas fermé."
493    
494    #
495    #  Impression arborescence Naming Service
496    #
497    
498    if clt != None:
499      print
500      print " --- registered objects tree in Naming Service ---"
501      clt.showNS()
502