Salome HOME
Minor correction to appli_gen.py: fix to prevent bugs in the future
[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
355     # Create configuration file: configSalome.cfg
356     with open(os.path.join(home_dir, 'env.d', 'configSalome.cfg'),'w') as f:
357         command = "[SALOME ROOT_DIR (modules) Configuration]\n"
358         f.write(command)
359         for module in _config.get("modules", []):
360             command = module + '_ROOT_DIR=${HOME}/${APPLI}\n'
361             f.write(command)
362             pass
363         if "samples_path" in _config:
364             command = 'DATA_DIR=' + _config["samples_path"] +'\n'
365             f.write(command)
366             pass
367         if "resources_path" in _config and os.path.isfile(_config["resources_path"]):
368             command = 'USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
369             f.write(command)
370         command ="""ADD_TO_PATH: ${HOME}/${APPLI}/bin/salome
371 ADD_TO_PYTHONPATH: ${HOME}/${APPLI}/lib/python%s/site-packages/salome
372 ADD_TO_PYTHONPATH: ${HOME}/${APPLI}/lib/salome
373 ADD_TO_LD_LIBRARY_PATH: ${HOME}/${APPLI}/lib/salome
374 """%versionPython
375         f.write(command)
376         for module in _config.get("modules", []):
377             command = "ADD_TO_LD_LIBRARY_PATH: ${HOME}/${APPLI}/bin/salome/test/" + module + "/lib\n"
378             f.write(command)
379             pass
380
381
382     # Create environment file: configGUI.sh
383     dirs_ress_icon = []
384     salomeappname  = "SalomeApp"
385     with open(os.path.join(home_dir, 'env.d', 'configGUI.sh'),'w') as f:
386         for module in _config.get("modules", []):
387             if module not in ["KERNEL", "GUI", ""]:
388                 d = os.path.join(_config[module],"share","salome","resources",module.lower())
389                 d_appli = os.path.join("${HOME}","${APPLI}","share","salome","resources",module.lower())
390                 if os.path.exists( os.path.join(d,"{0}.xml".format(salomeappname)) ):
391                    dirs_ress_icon.append( d_appli )
392         AppConfig="export SalomeAppConfig=${HOME}/${APPLI}:${HOME}/${APPLI}/share/salome/resources/gui/"
393         for dir_module in dirs_ress_icon:
394              AppConfig=AppConfig+":"+dir_module
395         f.write(AppConfig+"\n")
396         command = """export SUITRoot=${HOME}/${APPLI}/share/salome
397 export DISABLE_FPE=1
398 export MMGT_REENTRANT=1
399 """
400         f.write(command)
401
402     # Create configuration file: configGUI.cfg
403     with open(os.path.join(home_dir, 'env.d', 'configGUI.cfg'),'w') as f:
404         command = """[SALOME GUI Configuration]\n"""
405         f.write(command)
406         for module in _config.get("modules", []):
407             if module not in ["KERNEL", "GUI", ""]:
408                 d = os.path.join(_config[module],"share","salome","resources",module.lower())
409                 d_appli = os.path.join("${HOME}","${APPLI}","share","salome","resources",module.lower())
410                 if os.path.exists( os.path.join(d,"{0}.xml".format(salomeappname)) ):
411                    dirs_ress_icon.append( d_appli )
412         AppConfig="SalomeAppConfig=${HOME}/${APPLI}:${HOME}/${APPLI}/share/salome/resources/gui/"
413         for dir_module in dirs_ress_icon:
414              AppConfig=AppConfig+":"+dir_module
415         f.write(AppConfig+"\n")
416         command = """SUITRoot=${HOME}/${APPLI}/share/salome
417 DISABLE_FPE=1
418 MMGT_REENTRANT=1
419 """
420         f.write(command)
421
422     #SalomeApp.xml file
423     with open(os.path.join(home_dir,'SalomeApp.xml'),'w') as f:
424         command = """<document>
425   <section name="launch">
426     <!-- SALOME launching parameters -->
427     <parameter name="gui"        value="yes"/>
428     <parameter name="splash"     value="yes"/>
429     <parameter name="file"       value="no"/>
430     <parameter name="key"        value="no"/>
431     <parameter name="interp"     value="no"/>
432     <parameter name="logger"     value="no"/>
433     <parameter name="xterm"      value="no"/>
434     <parameter name="portkill"   value="no"/>
435     <parameter name="killall"    value="no"/>
436     <parameter name="noexcepthandler"  value="no"/>
437     <parameter name="modules"    value="%s"/>
438     <parameter name="pyModules"  value=""/>
439     <parameter name="embedded"   value="SalomeAppEngine,study,cppContainer,registry,moduleCatalog"/>
440     <parameter name="standalone" value=""/>
441   </section>
442 </document>
443 """
444         mods = []
445         #Keep all modules except KERNEL and GUI
446         for module in _config.get("modules", []):
447             if module in ("KERNEL","GUI"):
448                 continue
449             mods.append(module)
450         f.write(command % ",".join(mods))
451
452     #Add USERS directory with 777 permission to store users configuration files
453     users_dir = os.path.join(home_dir,'USERS')
454     makedirs(users_dir)
455     os.chmod(users_dir, 0o777)
456
457 def main():
458     parser = optparse.OptionParser(usage=usage)
459
460     parser.add_option('--prefix', dest="prefix", default='.',
461                       help="Installation directory (default .)")
462
463     parser.add_option('--config', dest="config", default='config_appli.xml',
464                       help="XML configuration file (default config_appli.xml)")
465
466     parser.add_option('-v', '--verbose', action='count', dest='verbose',
467                       default=0, help="Increase verbosity")
468
469     options, args = parser.parse_args()
470     if not os.path.exists(options.config):
471         print("ERROR: config file %s does not exist. It is mandatory." % options.config)
472         sys.exit(1)
473
474     install(prefix=options.prefix, config_file=options.config, verbose=options.verbose)
475     pass
476
477 # -----------------------------------------------------------------------------
478
479 if __name__ == '__main__':
480     main()
481     pass