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