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