]> SALOME platform Git repositories - modules/kernel.git/blob - bin/appli_gen.py
Salome HOME
15648eb9008fcd3b3ae9d0a3f046dccc7bfae1dd
[modules/kernel.git] / bin / appli_gen.py
1 #! /usr/bin/env python3
2 # Copyright (C) 2007-2019  CEA/DEN, EDF R&D, OPEN CASCADE
3 #
4 # Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
5 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 #
7 # This library is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU Lesser General Public
9 # License as published by the Free Software Foundation; either
10 # version 2.1 of the License, or (at your option) any later version.
11 #
12 # This library is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 # Lesser General Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser General Public
18 # License along with this library; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
20 #
21 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 #
23
24 ## \file appli_gen.py
25 #  Create a %SALOME application (virtual Salome installation)
26 #
27 usage = """%(prog)s [options]
28 Typical use is:
29   python %(prog)s
30 Typical use with options is:
31   python %(prog)s --verbose --prefix=<install directory> --config=<configuration file>
32 """
33
34 import os
35 import sys
36 import shutil
37 import virtual_salome
38 import xml.sax
39 import optparse
40 import subprocess
41
42 # --- names of tags in XML configuration file
43 appli_tag   = "application"
44 prereq_tag  = "prerequisites"
45 context_tag = "context"
46 sha1_collect_tag = "sha1_collections"
47 system_conf_tag  = "system_conf"
48 modules_tag = "modules"
49 module_tag  = "module"
50 samples_tag = "samples"
51 extra_tests_tag = "extra_tests"
52 extra_test_tag = "extra_test"
53 resources_tag = "resources"
54 env_modules_tag = "env_modules"
55 env_module_tag = "env_module"
56
57 # --- names of attributes in XML configuration file
58 nam_att  = "name"
59 path_att = "path"
60 gui_att  = "gui"
61
62 # -----------------------------------------------------------------------------
63
64 # --- xml reader for SALOME application configuration file
65
66 class xml_parser:
67     def __init__(self, fileName ):
68         print("Configure parser: processing %s ..." % fileName)
69         self.space = []
70         self.config = {}
71         self.config["modules"] = []
72         self.config["guimodules"] = []
73         self.config["extra_tests"] = []
74         self.config["env_modules"] = []
75         parser = xml.sax.make_parser()
76         parser.setContentHandler(self)
77         parser.parse(fileName)
78         pass
79
80     def boolValue( self, text):
81         if text in ("yes", "y", "1"):
82             return 1
83         elif text in ("no", "n", "0"):
84             return 0
85         else:
86             return text
87         pass
88
89     def startElement(self, name, attrs):
90         self.space.append(name)
91         self.current = None
92         # --- if we are analyzing "prerequisites" element then store its "path" attribute
93         if self.space == [appli_tag, prereq_tag] and path_att in attrs.getNames():
94             self.config["prereq_path"] = attrs.getValue( path_att )
95             pass
96         # --- if we are analyzing "context" element then store its "path" attribute
97         if self.space == [appli_tag, context_tag] and path_att in attrs.getNames():
98             self.config["context_path"] = attrs.getValue( path_att )
99             pass
100         # --- if we are analyzing "sha1_collection" element then store its "path" attribute
101         if self.space == [appli_tag, sha1_collect_tag] and path_att in attrs.getNames():
102             self.config["sha1_collect_path"] = attrs.getValue( path_att )
103             pass
104         # --- if we are analyzing "system_conf" element then store its "path" attribute
105         if self.space == [appli_tag, system_conf_tag] and path_att in attrs.getNames():
106             self.config["system_conf_path"] = attrs.getValue( path_att )
107             pass
108         # --- if we are analyzing "resources" element then store its "path" attribute
109         if self.space == [appli_tag, resources_tag] and path_att in attrs.getNames():
110             self.config["resources_path"] = attrs.getValue( path_att )
111             pass
112         # --- if we are analyzing "samples" element then store its "path" attribute
113         if self.space == [appli_tag, samples_tag] and path_att in attrs.getNames():
114             self.config["samples_path"] = attrs.getValue( path_att )
115             pass
116         # --- if we are analyzing "module" element then store its "name" and "path" attributes
117         elif self.space == [appli_tag,modules_tag,module_tag] and \
118             nam_att in attrs.getNames() and \
119             path_att in attrs.getNames():
120             nam = attrs.getValue( nam_att )
121             path = attrs.getValue( path_att )
122             gui = 1
123             if gui_att in attrs.getNames():
124                 gui = self.boolValue(attrs.getValue( gui_att ))
125                 pass
126             self.config["modules"].append(nam)
127             self.config[nam]=path
128             if gui:
129                 self.config["guimodules"].append(nam)
130                 pass
131             pass
132         # --- if we are analyzing "env_module" element then store its "name" attribute
133         elif self.space == [appli_tag, env_modules_tag, env_module_tag] and \
134                 nam_att in attrs.getNames():
135             nam = attrs.getValue( nam_att )
136             self.config["env_modules"].append(nam)
137             pass
138         # --- if we are analyzing "extra_test" element then store its "name" and "path" attributes
139         elif self.space == [appli_tag,extra_tests_tag,extra_test_tag] and \
140             nam_att in attrs.getNames() and \
141             path_att in attrs.getNames():
142             nam = attrs.getValue( nam_att )
143             path = attrs.getValue( path_att )
144             self.config["extra_tests"].append(nam)
145             self.config[nam]=path
146             pass
147         pass
148
149     def endElement(self, name):
150         self.space.pop()
151         self.current = None
152         pass
153
154     def characters(self, content):
155         pass
156
157     def processingInstruction(self, target, data):
158         pass
159
160     def setDocumentLocator(self, locator):
161         pass
162
163     def startDocument(self):
164         self.read = None
165         pass
166
167     def endDocument(self):
168         self.read = None
169         pass
170
171 # -----------------------------------------------------------------------------
172
173 class params:
174     pass
175
176 # -----------------------------------------------------------------------------
177
178 def makedirs(namedir):
179   if os.path.exists(namedir):
180     dirbak = namedir+".bak"
181     if os.path.exists(dirbak):
182       shutil.rmtree(dirbak)
183     os.rename(namedir, dirbak)
184     os.listdir(dirbak) #sert seulement a mettre a jour le systeme de fichier sur certaines machines
185   os.makedirs(namedir)
186
187 def install(prefix, config_file, verbose=0):
188     home_dir = os.path.abspath(os.path.expanduser(prefix))
189     filename = os.path.abspath(os.path.expanduser(config_file))
190     _config = {}
191     try:
192         parser = xml_parser(filename)
193         _config = parser.config
194     except xml.sax.SAXParseException as inst:
195         print(inst.getMessage())
196         print("Configure parser: parse error in configuration file %s" % filename)
197         pass
198     except xml.sax.SAXException as inst:
199         print(inst.args)
200         print("Configure parser: error in configuration file %s" % filename)
201         pass
202     except:
203         print("Configure parser: Error : can not read configuration file %s, check existence and rights" % filename)
204         pass
205
206     if verbose:
207         for cle,val in _config.items():
208             print(cle, val)
209             pass
210
211     # Remove CTestTestfile.cmake; this file will be filled by successive calls to link_module and link_extra_test
212     try:
213       ctest_file = os.path.join(home_dir, 'bin', 'salome', 'test', "CTestTestfile.cmake")
214       os.remove(ctest_file)
215     except:
216       pass
217
218     for module in _config.get("modules", []):
219         if module in _config:
220             print("--- add module ", module, _config[module])
221             options = params()
222             options.verbose = verbose
223             options.clear = 0
224             options.prefix = home_dir
225             options.module_name = module
226             options.module_path = _config[module]
227             virtual_salome.link_module(options)
228             # To fix GEOM_TestXAO issue https://codev-tuleap.cea.fr/plugins/tracker/?aid=16599
229             if module == "GEOM":
230                 # link <appli_path>/bin/salome/test/<module> to <module_path>/bin/salome/test
231                 test_dir=os.path.join(home_dir,'bin','salome', 'test')
232                 module_dir=os.path.abspath(options.module_path)
233                 xao_link=os.path.join(module_dir,'bin','salome', 'test', "xao")
234                 print("link %s --> %s"%(os.path.join(test_dir, "xao"), xao_link))
235                 virtual_salome.symlink(xao_link, os.path.join(test_dir, "xao"))
236             pass
237         pass
238
239     for extra_test in _config.get("extra_tests", []):
240         if extra_test in _config:
241             print("--- add extra test ", extra_test, _config[extra_test])
242             options = params()
243             options.verbose = verbose
244             options.clear = 0
245             options.prefix = home_dir
246             options.extra_test_name = extra_test
247             options.extra_test_path = _config[extra_test]
248             virtual_salome.link_extra_test(options)
249             pass
250         pass
251
252     # Generate CTestCustom.cmake to handle long output
253     ctest_custom = os.path.join(home_dir, 'bin', 'salome', 'test', "CTestCustom.cmake")
254     with open(ctest_custom, 'w') as f:
255       f.write("SET(CTEST_CUSTOM_MAXIMUM_PASSED_TEST_OUTPUT_SIZE 1048576) # 1MB\n")
256       f.write("SET(CTEST_CUSTOM_MAXIMUM_FAILED_TEST_OUTPUT_SIZE 1048576) # 1MB\n")
257
258     appliskel_dir = os.path.join(home_dir, 'bin', 'salome', 'appliskel')
259
260     for fn in ('envd',
261                'getAppliPath.py',
262                'kill_remote_containers.py',
263                'runRemote.sh',
264                '.salome_run',
265                'update_catalogs.py',
266                '.bashrc',
267                ):
268         virtual_salome.symlink( os.path.join( appliskel_dir, fn ), os.path.join( home_dir, fn) )
269         pass
270
271     if filename != os.path.join(home_dir,"config_appli.xml"):
272         shutil.copyfile(filename, os.path.join(home_dir,"config_appli.xml"))
273         pass
274
275
276     # Copy salome script 
277     salome_script = open(os.path.join(appliskel_dir, "salome")).read()
278     salome_file = os.path.join(home_dir, "salome")
279     try:
280         os.remove(salome_file)
281     except:
282         pass
283     env_modules = _config.get('env_modules', [])
284     with open(salome_file, 'w') as fd:
285         fd.write(salome_script.replace('MODULES = []', 'MODULES = {}'.format(env_modules)))
286     os.chmod(salome_file, 0o755)
287
288
289     # Add .salome-completion.sh file
290     shutil.copyfile(os.path.join(appliskel_dir, ".salome-completion.sh"),
291                     os.path.join(home_dir, ".salome-completion.sh"))
292
293
294     # Creation of env.d directory
295     virtual_salome.mkdir(os.path.join(home_dir,'env.d'))
296
297     if "prereq_path" in _config and os.path.isfile(_config["prereq_path"]):
298         shutil.copyfile(_config["prereq_path"],
299                         os.path.join(home_dir, 'env.d', 'envProducts.sh'))
300         pass
301     else:
302         print("WARNING: prerequisite file does not exist")
303         pass
304
305     if "context_path" in _config and os.path.isfile(_config["context_path"]):
306         shutil.copyfile(_config["context_path"],
307                         os.path.join(home_dir, 'env.d', 'envProducts.cfg'))
308         pass
309     else:
310         print("WARNING: context file does not exist")
311         pass
312
313     if "sha1_collect_path" in _config and os.path.isfile(_config["sha1_collect_path"]):
314         shutil.copyfile(_config["sha1_collect_path"],
315                         os.path.join(home_dir, 'sha1_collections.txt'))
316         pass
317     else:
318         print("WARNING: sha1 collections file does not exist")
319         pass
320
321     if "system_conf_path" in _config and os.path.isfile(_config["system_conf_path"]):
322         shutil.copyfile(_config["system_conf_path"],
323                         os.path.join(home_dir, 'env.d', 'envConfSystem.sh'))
324         pass
325
326     # Create environment file: configSalome.sh
327
328     cmd='source %s && python3 -c "import sys ; sys.stdout.write(\\"{}.{}\\".format(sys.version_info.major,sys.version_info.minor))"' %(_config["prereq_path"])
329     versionPython=subprocess.check_output(['/bin/bash', '-l' ,'-c',cmd]).decode("utf-8")
330
331     with open(os.path.join(home_dir, 'env.d', 'configSalome.sh'),'w') as f:
332         for module in _config.get("modules", []):
333             command = 'export '+ module + '_ROOT_DIR=${HOME}/${APPLI}\n'
334             f.write(command)
335             pass
336         if "samples_path" in _config:
337             command = 'export DATA_DIR=' + _config["samples_path"] +'\n'
338             f.write(command)
339             pass
340         if "resources_path" in _config and os.path.isfile(_config["resources_path"]):
341             command = 'export USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
342             f.write(command)
343         command ="""export PATH=${HOME}/${APPLI}/bin/salome:$PATH
344 export PYTHONPATH=${HOME}/${APPLI}/lib/python%s/site-packages/salome:$PYTHONPATH
345 export PYTHONPATH=${HOME}/${APPLI}/lib/salome:$PYTHONPATH
346 export LD_LIBRARY_PATH=${HOME}/${APPLI}/lib/salome:$LD_LIBRARY_PATH
347 """ %versionPython
348         f.write(command)
349         # Create environment variable for the salome test
350         for module in _config.get("modules", []):
351             command = "export LD_LIBRARY_PATH=  ${HOME}/${APPLI}/bin/salome/test/" + module + "/lib:$LD_LIBRARY_PATH\n"
352             f.write(command)
353             pass
354         # Create environment for plugins GEOM
355         command = "export GEOM_PluginsList=BREPPlugin:STEPPlugin:IGESPlugin:STLPlugin:XAOPlugin:VTKPlugin:AdvancedGEOM\n"
356         f.write(command)
357         # Create environment for Healing
358         command = "export CSF_ShHealingDefaults=${HOME}/${APPLI}/share/salome/resources/geom\n"
359         f.write(command)
360         # Create environment for Meshers
361         command = "export SMESH_MeshersList=StdMeshers:HYBRIDPlugin:HexoticPLUGIN:GMSHPlugin:GHS3DPlugin:NETGENPlugin:HEXABLOCKPlugin:BLSURFPlugin\nexport SALOME_StdMeshersResources=${HOME}/${APPLI}/share/salome/resources/smesh\n"
362         f.write(command)
363
364     # Create configuration file: configSalome.cfg
365     with open(os.path.join(home_dir, 'env.d', 'configSalome.cfg'),'w') as f:
366         command = "[SALOME ROOT_DIR (modules) Configuration]\n"
367         f.write(command)
368         for module in _config.get("modules", []):
369             command = module + '_ROOT_DIR=${HOME}/${APPLI}\n'
370             f.write(command)
371             pass
372         if "samples_path" in _config:
373             command = 'DATA_DIR=' + _config["samples_path"] +'\n'
374             f.write(command)
375             pass
376         if "resources_path" in _config and os.path.isfile(_config["resources_path"]):
377             command = 'USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
378             f.write(command)
379         command ="""ADD_TO_PATH: ${HOME}/${APPLI}/bin/salome
380 ADD_TO_PYTHONPATH: ${HOME}/${APPLI}/lib/python%s/site-packages/salome
381 ADD_TO_PYTHONPATH: ${HOME}/${APPLI}/lib/salome
382 ADD_TO_LD_LIBRARY_PATH: ${HOME}/${APPLI}/lib/salome
383 """%versionPython
384         f.write(command)
385         for module in _config.get("modules", []):
386             command = "ADD_TO_LD_LIBRARY_PATH: ${HOME}/${APPLI}/bin/salome/test/" + module + "/lib\n"
387             f.write(command)
388             pass
389         # Create environment for plugins GEOM
390         command = "GEOM_PluginsList=BREPPlugin:STEPPlugin:IGESPlugin:STLPlugin:XAOPlugin:VTKPlugin:AdvancedGEOM\n"
391         f.write(command)
392         # Create environment for Healing
393         command = "CSF_ShHealingDefaults=${HOME}/${APPLI}/share/salome/resources/geom\n"
394         f.write(command)
395         # Create environment for Meshers
396         command = "SMESH_MeshersList=StdMeshers:HYBRIDPlugin:HexoticPLUGIN:GMSHPlugin:GHS3DPlugin:NETGENPlugin:HEXABLOCKPlugin:BLSURFPlugin\nSALOME_StdMeshersResources=${HOME}/${APPLI}/share/salome/resources/smesh\n"
397         f.write(command)
398
399
400     # Create environment file: configGUI.sh
401     dirs_ress_icon = []
402     salomeappname  = "SalomeApp"
403     with open(os.path.join(home_dir, 'env.d', 'configGUI.sh'),'w') as f:
404         for module in _config.get("modules", []):
405             if module not in ["KERNEL", "GUI", ""]:
406                 d = os.path.join(_config[module],"share","salome","resources",module.lower())
407                 d_appli = os.path.join("${HOME}","${APPLI}","share","salome","resources",module.lower())
408                 if os.path.exists( os.path.join(d,"{0}.xml".format(salomeappname)) ):
409                    dirs_ress_icon.append( d_appli )
410         AppConfig="export SalomeAppConfig=${HOME}/${APPLI}:${HOME}/${APPLI}/share/salome/resources/gui/"
411         for dir_module in dirs_ress_icon:
412              AppConfig=AppConfig+":"+dir_module
413         f.write(AppConfig+"\n")
414         command = """export SUITRoot=${HOME}/${APPLI}/share/salome
415 export DISABLE_FPE=1
416 export MMGT_REENTRANT=1
417 """
418         f.write(command)
419
420     # Create configuration file: configGUI.cfg
421     dirs_ress_icon = []
422     with open(os.path.join(home_dir, 'env.d', 'configGUI.cfg'),'w') as f:
423         command = """[SALOME GUI Configuration]\n"""
424         f.write(command)
425         for module in _config.get("modules", []):
426             if module not in ["KERNEL", "GUI", ""]:
427                 d = os.path.join(_config[module],"share","salome","resources",module.lower())
428                 d_appli = os.path.join("${HOME}","${APPLI}","share","salome","resources",module.lower())
429                 if os.path.exists( os.path.join(d,"{0}.xml".format(salomeappname)) ):
430                    dirs_ress_icon.append( d_appli )
431         AppConfig="SalomeAppConfig=${HOME}/${APPLI}:${HOME}/${APPLI}/share/salome/resources/gui/"
432         for dir_module in dirs_ress_icon:
433              AppConfig=AppConfig+":"+dir_module
434         f.write(AppConfig+"\n")
435         command = """SUITRoot=${HOME}/${APPLI}/share/salome
436 DISABLE_FPE=1
437 MMGT_REENTRANT=1
438 """
439         f.write(command)
440
441     #SalomeApp.xml file
442     with open(os.path.join(home_dir,'SalomeApp.xml'),'w') as f:
443         command = """<document>
444   <section name="launch">
445     <!-- SALOME launching parameters -->
446     <parameter name="gui"        value="yes"/>
447     <parameter name="splash"     value="yes"/>
448     <parameter name="file"       value="no"/>
449     <parameter name="key"        value="no"/>
450     <parameter name="interp"     value="no"/>
451     <parameter name="logger"     value="no"/>
452     <parameter name="xterm"      value="no"/>
453     <parameter name="portkill"   value="no"/>
454     <parameter name="killall"    value="no"/>
455     <parameter name="noexcepthandler"  value="no"/>
456     <parameter name="modules"    value="%s"/>
457     <parameter name="pyModules"  value=""/>
458     <parameter name="embedded"   value="SalomeAppEngine,study,cppContainer,registry,moduleCatalog"/>
459     <parameter name="standalone" value=""/>
460   </section>
461 </document>
462 """
463         mods = []
464         #Keep all modules except KERNEL and GUI
465         for module in _config.get("modules", []):
466             if module in ("KERNEL","GUI"):
467                 continue
468             mods.append(module)
469         f.write(command % ",".join(mods))
470
471     #Add USERS directory with 777 permission to store users configuration files
472     users_dir = os.path.join(home_dir,'USERS')
473     makedirs(users_dir)
474     os.chmod(users_dir, 0o777)
475
476 def main():
477     parser = optparse.OptionParser(usage=usage)
478
479     parser.add_option('--prefix', dest="prefix", default='.',
480                       help="Installation directory (default .)")
481
482     parser.add_option('--config', dest="config", default='config_appli.xml',
483                       help="XML configuration file (default config_appli.xml)")
484
485     parser.add_option('-v', '--verbose', action='count', dest='verbose',
486                       default=0, help="Increase verbosity")
487
488     options, args = parser.parse_args()
489     if not os.path.exists(options.config):
490         print("ERROR: config file %s does not exist. It is mandatory." % options.config)
491         sys.exit(1)
492
493     install(prefix=options.prefix, config_file=options.config, verbose=options.verbose)
494     pass
495
496 # -----------------------------------------------------------------------------
497
498 if __name__ == '__main__':
499     main()
500     pass