Salome HOME
d390355841cbc090ebd911c2e1795c87a6a4cd9f
[modules/kernel.git] / bin / runSalome.py
1 #!/usr/bin/env python
2
3 import sys, os, string, glob, time, pickle
4
5 ### read launch configure xml file and command line options
6 import launchConfigureParser
7 args = launchConfigureParser.args
8
9 ### kill servers if it is need
10
11 from killSalome import killAllPorts
12
13 def killLocalPort():
14     from killSalomeWithPort import killMyPort
15     my_port=str(args['port'])
16     try:
17         killMyPort(my_port)
18     except:
19         print "problem in killLocalPort()"
20         pass
21     pass
22     
23 if args['killall']:
24     killAllPorts()
25 elif args['portkill']:
26     killLocalPort()
27         
28 # -----------------------------------------------------------------------------
29 #
30 # Fonctions helper pour ajouter des variables d'environnement
31 #
32
33 def add_path(directory, variable_name):
34     if not os.environ.has_key(variable_name):
35         os.environ[variable_name] = ""
36         pass
37     os.environ[variable_name]=directory + ":" + os.environ[variable_name]
38     if variable_name=="PYTHONPATH":
39         sys.path[:0]=[directory]
40
41
42 init_time = os.times()
43 # -----------------------------------------------------------------------------
44 #
45 # Check variables <module>_ROOT_DIR and set list of used modules (without KERNEL)
46 # Add to the PATH-variables modules' specific paths
47 #
48 modules_list = []
49 if args.has_key("modules"):
50     modules_list += args["modules"]
51 modules_list[:0] = ["KERNEL"] # KERNEL must be last in the list to locate it at the first place in PATH variables
52 modules_list.reverse()
53
54 modules_root_dir = {}
55 modules_root_dir_list = []
56 python_version="python%d.%d" % sys.version_info[0:2]
57
58 to_remove_list=[]
59 for module in modules_list :
60     module_variable=module.upper()+"_ROOT_DIR"
61     if not os.environ.has_key(module_variable):
62         print "*******************************************************************************"
63         print "*"
64         print "* Environment variable",module_variable,"must be set"
65         print "* Module", module, "will be not available"
66         print "*"
67         print "*******************************************************************************"
68         to_remove_list.append(module)
69         continue
70         pass
71     module_root_dir = os.environ[module_variable]
72     modules_root_dir[module]=module_root_dir
73     modules_root_dir_list[:0] = [module_root_dir]
74     add_path(os.path.join(module_root_dir,"lib",args['appname']), "LD_LIBRARY_PATH")
75     add_path(os.path.join(module_root_dir,"bin",args['appname']), "PATH")
76     if os.path.exists(module_root_dir + "/examples") :
77         add_path(os.path.join(module_root_dir,"examples"), "PYTHONPATH")
78
79 for to_remove in to_remove_list:
80     modules_list.remove(to_remove)
81
82 while "KERNEL" in modules_list:
83     modules_list.remove("KERNEL")
84     pass
85
86 # KERNEL must be last in the list to locate it at the first place in PYTHONPATH variable
87 list_modules = modules_list[:] + ["KERNEL"] 
88 for module in list_modules:
89     module_root_dir = modules_root_dir[module]
90     add_path(os.path.join(module_root_dir,"bin",args['appname']), "PYTHONPATH")
91     add_path(os.path.join(module_root_dir,"lib",python_version,"site-packages",args['appname']), "PYTHONPATH")
92     add_path(os.path.join(module_root_dir,"lib",args['appname']), "PYTHONPATH")
93     add_path(os.path.join(module_root_dir,"lib",python_version,"site-packages",args['appname'],"shared_modules"), "PYTHONPATH")
94       
95 #os.environ["SALOMEPATH"]=":".join(modules_root_dir.values())
96 os.environ["SALOMEPATH"]=":".join(modules_root_dir_list)
97 if "SUPERV" in modules_list and not 'superv' in args['standalone']:
98     args['standalone'].append("superv")
99     pass
100
101
102 # -----------------------------------------------------------------------------
103 #
104 # Définition des classes d'objets pour le lancement des Server CORBA
105 #
106
107 class Server:
108    CMD=[]
109    if args['xterm']:
110         ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-hold']
111    else:
112         ARGS=[] 
113
114    def run(self):
115        global process_id
116        myargs=self.ARGS
117        if args['xterm']:
118            # (Debian) Transfert variable LD_LIBRARY_PATH aux shells fils (xterm)
119            env_ld_library_path=['env', 'LD_LIBRARY_PATH='+ os.getenv("LD_LIBRARY_PATH")]
120            myargs = myargs +['-T']+self.CMD[:1]+['-e'] + env_ld_library_path
121        command = myargs + self.CMD
122        #print "command = ", command
123        pid = os.spawnvp(os.P_NOWAIT, command[0], command)
124        process_id[pid]=self.CMD
125
126 class CatalogServer(Server):
127    SCMD1=['SALOME_ModuleCatalog_Server','-common']
128    SCMD2=['-personal','${HOME}/Salome/resources/CatalogModulePersonnel.xml'] 
129
130    def setpath(self,modules_list):
131       cata_path=[]
132       list_modules = modules_list[:]
133       list_modules.reverse()
134       for module in ["KERNEL"] + list_modules:
135           module_root_dir=modules_root_dir[module]
136           module_cata=module+"Catalog.xml"
137           print "   ", module_cata
138           cata_path.extend(glob.glob(os.path.join(module_root_dir,"share",args['appname'],"resources",module_cata)))
139       self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
140
141 class SalomeDSServer(Server):
142    CMD=['SALOMEDS_Server']
143
144 class RegistryServer(Server):
145    CMD=['SALOME_Registry_Server', '--salome_session','theSession']
146
147 class ContainerCPPServer(Server):
148    #CMD=['SALOME_Container','FactoryServer','-ORBInitRef','NameService=corbaname::localhost']
149    CMD=['SALOME_Container','FactoryServer']
150
151 class ContainerPYServer(Server):
152    #CMD=['SALOME_ContainerPy.py','FactoryServerPy','-ORBInitRef','NameService=corbaname::localhost']
153    CMD=['SALOME_ContainerPy.py','FactoryServerPy']
154
155 class ContainerSUPERVServer(Server):
156    #CMD=['SALOME_Container','SuperVisionContainer','-ORBInitRef','NameService=corbaname::localhost']
157    CMD=['SALOME_Container','SuperVisionContainer']
158
159 class LoggerServer(Server):
160    CMD=['SALOME_Logger_Server', 'logger.log']
161
162 class SessionLoader(Server):
163    CMD=['SALOME_Session_Loader']
164    if "cpp" in args['containers']:
165        CMD=CMD+['CPP']
166    if "python" in args['containers']:
167        CMD=CMD+['PY']
168    if "superv" in args['containers']:
169        CMD=CMD+['SUPERV']
170    if args['gui']:
171        CMD=CMD+['GUI']
172
173 class SessionServer(Server):
174    SCMD1=['SALOME_Session_Server']
175    SCMD2=[]
176    if 'registry' in args['embedded']:
177        SCMD1+=['--with','Registry','(','--salome_session','theSession',')']
178    if 'moduleCatalog' in args['embedded']:
179        SCMD1+=['--with','ModuleCatalog','(','-common']
180        SCMD2+=['-personal','${HOME}/Salome/resources/CatalogModulePersonnel.xml',')']
181    if 'study' in args['embedded']:
182        SCMD2+=['--with','SALOMEDS','(',')']
183    if 'cppContainer' in args['embedded']:
184        SCMD2+=['--with','Container','(','FactoryServer',')']
185
186    def setpath(self,modules_list):
187       cata_path=[]
188       list_modules = modules_list[:]
189       list_modules.reverse()
190       for module in ["KERNEL"] + list_modules:
191           module_root_dir=modules_root_dir[module]
192           module_cata=module+"Catalog.xml"
193           print "   ", module_cata
194           cata_path.extend(glob.glob(os.path.join(module_root_dir,"share",args['appname'],"resources",module_cata)))
195       if 'moduleCatalog' in args['embedded']:
196           self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
197       else:
198           self.CMD=self.SCMD1 + self.SCMD2
199
200 class NotifyServer(Server):
201     myLogName = os.environ["LOGNAME"]
202     CMD=['notifd','-c',modules_root_dir["KERNEL"]+'/share/salome/resources/channel.cfg', '-DFactoryIORFileName=/tmp/'+myLogName+'_rdifact.ior', '-DChannelIORFileName=/tmp/'+myLogName+'_rdichan.ior']
203
204 # -----------------------------------------------------------------------------
205 #
206 # initialisation des variables d'environnement
207 #
208
209 os.environ["SALOME_trace"]="local"
210 if args['logger']:
211    os.environ["SALOME_trace"]="with_logger"
212    locdir=os.environ['PWD']
213    libtracedir=os.path.join(locdir,"libSalomeTrace")
214    libtrace = os.path.join(modules_root_dir["KERNEL"],"lib",args['appname'],"libSALOMELoggerClient.so.0.0.0")
215    libtraceln = os.path.join(libtracedir,"libSALOMELocalTrace.so")
216    aCommand = 'rm -rf ' + libtracedir + "; "
217    aCommand += 'mkdir ' + libtracedir + "; "
218    aCommand += 'ln -s ' + libtrace + " " + libtraceln + "; "
219    aCommand += 'ln -s ' + libtrace + " " + libtraceln + ".0; "
220    aCommand += 'ln -s ' + libtrace + " " + libtraceln + ".0.0.0; "
221    os.system(aCommand)
222    add_path(libtracedir, "LD_LIBRARY_PATH")
223
224 # set environment for SMESH plugins
225
226 if "SMESH" in args["modules"]:
227     os.environ["SMESH_MeshersList"]="StdMeshers"
228     if not os.environ.has_key("SALOME_StdMeshersResources"):
229         os.environ["SALOME_StdMeshersResources"] = modules_root_dir["SMESH"]+"/share/"+args["appname"]+"/resources"
230         pass
231     if args.has_key("SMESH_plugins"):
232         for plugin in args["SMESH_plugins"]:
233             if os.environ.has_key(plugin.upper()+"_ROOT_DIR"):
234                 os.environ["SMESH_MeshersList"]=os.environ["SMESH_MeshersList"]+":"+plugin
235                 plugin_root = os.environ[plugin.upper()+"_ROOT_DIR"]
236                 if not os.environ.has_key("SALOME_"+plugin+"Resources"):
237                     os.environ["SALOME_"+plugin+"Resources"] = plugin_root+"/share/"+args["appname"]+"/resources"
238                 add_path(os.path.join(plugin_root,"lib",python_version,"site-packages",args['appname']), "PYTHONPATH")
239                 add_path(os.path.join(plugin_root,"lib",args['appname']), "PYTHONPATH")
240                 add_path(os.path.join(plugin_root,"lib",args['appname']), "LD_LIBRARY_PATH")
241                 add_path(os.path.join(plugin_root,"bin",args['appname']), "PYTHONPATH")
242                 add_path(os.path.join(plugin_root,"bin",args['appname']), "PATH")
243         pass
244     pass
245    
246 import orbmodule
247
248 #
249 # -----------------------------------------------------------------------------
250 #
251
252 def startGUI():
253   import SALOME
254   session=clt.waitNS("/Kernel/Session",SALOME.Session)
255
256   #
257   # Activation du GUI de Session Server
258   #
259         
260   session.GetInterface()
261   
262 #
263 # -----------------------------------------------------------------------------
264 #
265
266 def startSalome():
267
268   #
269   # Lancement Session Loader
270   #
271
272   if args['gui']:
273      SessionLoader().run()
274
275   #
276   # Initialisation ORB et Naming Service
277   #
278    
279   clt=orbmodule.client()
280
281   # (non obligatoire) Lancement Logger Server et attente de sa disponibilite dans le naming service
282   #
283
284   if args['logger']:
285         LoggerServer().run()
286         clt.waitLogger("Logger")
287
288   # Notify Server launch
289   #
290   NotifyServer().run()
291
292   #
293   # Lancement Registry Server, attente de la disponibilité du Registry dans le Naming Service
294   #
295   if 'registry' not in args['embedded']:
296       RegistryServer().run()
297       clt.waitNS("/Registry")
298
299   #
300   # Lancement Catalog Server, attente de la disponibilité du Catalog Server dans le Naming Service
301   #
302
303   if 'moduleCatalog' not in args['embedded']:
304       cataServer=CatalogServer()
305       cataServer.setpath(modules_list)
306       cataServer.run()
307       import SALOME_ModuleCatalog
308       clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
309
310   #
311   # Lancement SalomeDS Server, attente de la disponibilité du SalomeDS dans le Naming Service
312   #
313
314   os.environ["CSF_PluginDefaults"]=os.path.join(modules_root_dir["KERNEL"],"share",args['appname'],"resources")
315   os.environ["CSF_SALOMEDS_ResourcesDefaults"]=os.path.join(modules_root_dir["KERNEL"],"share",args['appname'],"resources")
316
317   if "GEOM" in modules_list:
318         print "GEOM OCAF Resources"
319         os.environ["CSF_GEOMDS_ResourcesDefaults"]=os.path.join(modules_root_dir["GEOM"],"share",args['appname'],"resources")
320
321   if 'study' not in args['embedded']:
322       SalomeDSServer().run()
323       clt.waitNS("/myStudyManager")
324
325   #
326   # Lancement Session Server
327   #
328
329   mySessionServ=SessionServer()
330   mySessionServ.setpath(modules_list)
331   mySessionServ.run()
332
333   #
334   # Attente de la disponibilité du Session Server dans le Naming Service
335   #
336
337   #import SALOME
338   #session=clt.waitNS("/Kernel/Session",SALOME.Session)
339
340   if os.getenv("HOSTNAME") == None:
341      if os.getenv("HOST") == None:
342         os.environ["HOSTNAME"]="localhost"
343      else:
344         os.environ["HOSTNAME"]=os.getenv("HOST")
345
346   theComputer = os.getenv("HOSTNAME")
347   computerSplitName = theComputer.split('.')
348   theComputer = computerSplitName[0]
349   
350   #
351   # Lancement Container C++ local, attente de la disponibilité du Container C++ local dans le Naming Service
352   #
353
354   if 'cppContainer' in args['standalone']:
355           ContainerCPPServer().run()
356           clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
357
358   #
359   # Lancement Container Python local, attente de la disponibilité du Container Python local dans le Naming Service
360   #
361
362   if 'pyContainer' in args['standalone']:
363           ContainerPYServer().run()
364           clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy")
365
366   #
367   # Lancement Container Supervision local, attente de la disponibilité du Container Supervision local dans le Naming Service
368   #
369
370   if 'supervContainer' in args['standalone']:
371       ContainerSUPERVServer().run()
372       clt.waitNS("/Containers/" + theComputer + "/SuperVisionContainer")
373
374   end_time = os.times()
375   print
376   print "Start SALOME, elpased time : %5.1f seconds"% (end_time[4] - init_time[4])
377
378   return clt
379
380 #
381 # -----------------------------------------------------------------------------
382 #
383
384 process_id = {}
385 if __name__ == "__main__":
386     clt=None
387     try:
388         clt = startSalome()
389     except:
390         print
391         print
392         print "--- erreur au lancement Salome ---"
393         
394     #print process_id
395     
396     filedict='/tmp/'+os.getenv('USER')+"_"+str(args['port'])+'_'+args['appname'].upper()+'_pidict'
397     #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
398     
399     
400     process_ids = []
401     try:
402         fpid=open(filedict, 'r')
403         process_ids=pickle.load(fpid)
404         fpid.close()
405     except:
406         pass
407     
408     fpid=open(filedict, 'w')
409     process_ids.append(process_id)
410     pickle.dump(process_ids,fpid)
411     fpid.close()
412     
413     print """
414     Saving of the dictionary of Salome processes in %s
415     To kill SALOME processes from a console (kill all sessions from all ports):
416       python killSalome.py 
417     To kill SALOME from the present interpreter, if it is not closed :
418       killLocalPort()  --> kill this session
419       killAllPorts()   --> kill all sessions
420     
421     runSalome, with --killall option, starts with killing the processes resulting from the previous execution.
422     """%filedict
423     
424     #
425     #  Impression arborescence Naming Service
426     #
427     
428     if clt != None:
429         print
430         print " --- registered objects tree in Naming Service ---"
431         clt.showNS()