1 #! /usr/bin/env python3
2 # Copyright (C) 2007-2023 CEA, EDF, OPEN CASCADE
4 # Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
5 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
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.
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.
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
21 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
25 # Create a %SALOME application (virtual Salome installation)
37 usage = """%(prog)s [options]
40 Typical use with options is:
41 python %(prog)s --verbose --prefix=<install directory> --config=<configuration file>
44 # --- names of tags in XML configuration file
45 appli_tag = "application"
46 prereq_tag = "prerequisites"
47 context_tag = "context"
48 venv_directory_tag = "venv_directory"
49 sha1_collect_tag = "sha1_collections"
50 system_conf_tag = "system_conf"
51 modules_tag = "modules"
53 samples_tag = "samples"
54 extra_tests_tag = "extra_tests"
55 extra_test_tag = "extra_test"
56 resources_tag = "resources"
57 env_modules_tag = "env_modules"
58 env_module_tag = "env_module"
61 # --- names of attributes in XML configuration file
65 version_att = "version"
66 # -----------------------------------------------------------------------------
69 # --- xml reader for SALOME application configuration file
72 def __init__(self, fileName):
73 print("Configure parser: processing %s ..." % fileName)
76 self.config["modules"] = []
77 self.config["guimodules"] = []
78 self.config["extra_tests"] = []
79 self.config["env_modules"] = []
80 parser = xml.sax.make_parser()
81 parser.setContentHandler(self)
82 parser.parse(fileName)
85 def boolValue(self, text):
86 if text in ("yes", "y", "1"):
88 elif text in ("no", "n", "0"):
94 def startElement(self, name, attrs):
95 self.space.append(name)
97 # --- if we are analyzing "prerequisites" element then store its "path" attribute
98 if self.space == [appli_tag, prereq_tag] and path_att in attrs.getNames():
99 self.config["prereq_path"] = attrs.getValue( path_att )
101 # --- if we are analyzing "context" element then store its "path" attribute
102 if self.space == [appli_tag, context_tag] and path_att in attrs.getNames():
103 self.config["context_path"] = attrs.getValue( path_att )
105 # --- if we are analyzing "venv_directory" element then store its "path" attribute
106 if self.space == [appli_tag, venv_directory_tag] and path_att in attrs.getNames():
107 self.config["venv_directory_path"] = attrs.getValue( path_att )
109 # --- if we are analyzing "sha1_collection" element then store its "path" attribute
110 if self.space == [appli_tag, sha1_collect_tag] and path_att in attrs.getNames():
111 self.config["sha1_collect_path"] = attrs.getValue( path_att )
113 # --- if we are analyzing "python" element then store its "version" attribute
114 if self.space == [appli_tag, python_tag] and version_att in attrs.getNames():
115 self.config["python_version"] = attrs.getValue( version_att )
117 # --- if we are analyzing "system_conf" element then store its "path" attribute
118 if self.space == [appli_tag, system_conf_tag] and path_att in attrs.getNames():
119 self.config["system_conf_path"] = attrs.getValue( path_att )
121 # --- if we are analyzing "resources" element then store its "path" attribute
122 if self.space == [appli_tag, resources_tag] and path_att in attrs.getNames():
123 self.config["resources_path"] = attrs.getValue( path_att )
125 # --- if we are analyzing "samples" element then store its "path" attribute
126 if self.space == [appli_tag, samples_tag] and path_att in attrs.getNames():
127 self.config["samples_path"] = attrs.getValue( path_att )
129 # --- if we are analyzing "module" element then store its "name" and "path" attributes
130 elif self.space == [appli_tag,modules_tag,module_tag] and \
131 nam_att in attrs.getNames() and \
132 path_att in attrs.getNames():
133 nam = attrs.getValue( nam_att )
134 path = attrs.getValue( path_att )
136 if gui_att in attrs.getNames():
137 gui = self.boolValue(attrs.getValue( gui_att ))
139 self.config["modules"].append(nam)
140 self.config[nam]=path
142 self.config["guimodules"].append(nam)
145 # --- if we are analyzing "env_module" element then store its "name" attribute
146 elif self.space == [appli_tag, env_modules_tag, env_module_tag] and \
147 nam_att in attrs.getNames():
148 nam = attrs.getValue( nam_att )
149 self.config["env_modules"].append(nam)
151 # --- if we are analyzing "extra_test" element then store its "name" and "path" attributes
152 elif self.space == [appli_tag,extra_tests_tag,extra_test_tag] and \
153 nam_att in attrs.getNames() and \
154 path_att in attrs.getNames():
155 nam = attrs.getValue( nam_att )
156 path = attrs.getValue( path_att )
157 self.config["extra_tests"].append(nam)
158 self.config[nam]=path
162 def endElement(self, name):
167 def characters(self, content):
170 def processingInstruction(self, target, data):
173 def setDocumentLocator(self, locator):
176 def startDocument(self):
180 def endDocument(self):
184 # -----------------------------------------------------------------------------
189 # -----------------------------------------------------------------------------
191 def makedirs(namedir):
192 if os.path.exists(namedir):
193 dirbak = namedir+".bak"
194 if os.path.exists(dirbak):
195 shutil.rmtree(dirbak)
196 os.rename(namedir, dirbak)
197 os.listdir(dirbak) #sert seulement a mettre a jour le systeme de fichier sur certaines machines
200 def install(prefix, config_file, verbose=0):
201 home_dir = os.path.abspath(os.path.expanduser(prefix))
202 filename = os.path.abspath(os.path.expanduser(config_file))
205 parser = xml_parser(filename)
206 _config = parser.config
207 except xml.sax.SAXParseException as inst:
208 print(inst.getMessage())
209 print("Configure parser: parse error in configuration file %s" % filename)
211 except xml.sax.SAXException as inst:
213 print("Configure parser: error in configuration file %s" % filename)
216 print("Configure parser: Error : can not read configuration file %s, check existence and rights" % filename)
220 for cle,val in _config.items():
224 # Remove CTestTestfile.cmake; this file will be filled by successive calls to link_module and link_extra_test
226 ctest_file = os.path.join(home_dir, 'bin', 'salome', 'test', "CTestTestfile.cmake")
227 os.remove(ctest_file)
231 for module in _config.get("modules", []):
232 if module in _config:
233 print("--- add module ", module, _config[module])
235 options.verbose = verbose
237 options.prefix = home_dir
238 options.module_name = module
239 options.module_path = _config[module]
240 virtual_salome.link_module(options)
241 # To fix GEOM_TestXAO issue https://codev-tuleap.cea.fr/plugins/tracker/?aid=16599
243 # link <appli_path>/bin/salome/test/<module> to <module_path>/bin/salome/test
244 test_dir=os.path.join(home_dir,'bin','salome', 'test')
245 module_dir=os.path.abspath(options.module_path)
246 xao_link=os.path.join(module_dir,'bin','salome', 'test', "xao")
247 print("link %s --> %s"%(os.path.join(test_dir, "xao"), xao_link))
248 virtual_salome.symlink(xao_link, os.path.join(test_dir, "xao"))
252 for extra_test in _config.get("extra_tests", []):
253 if extra_test in _config:
254 print("--- add extra test ", extra_test, _config[extra_test])
256 options.verbose = verbose
258 options.prefix = home_dir
259 options.extra_test_name = extra_test
260 options.extra_test_path = _config[extra_test]
261 virtual_salome.link_extra_test(options)
265 # Sort test labels by name in generated CTestTestfile.cmake
266 with open(ctest_file) as f:
267 lines = f.readlines()
269 with open(ctest_file, "w") as f:
270 f.write("".join(lines))
272 # Generate CTestCustom.cmake to handle long output
273 ctest_custom = os.path.join(home_dir, 'bin', 'salome', 'test', "CTestCustom.cmake")
274 with open(ctest_custom, 'w') as f:
275 f.write("SET(CTEST_CUSTOM_MAXIMUM_PASSED_TEST_OUTPUT_SIZE 1048576) # 1MB\n")
276 f.write("SET(CTEST_CUSTOM_MAXIMUM_FAILED_TEST_OUTPUT_SIZE 1048576) # 1MB\n")
278 appliskel_dir = os.path.join(prefix, 'bin', 'salome', 'appliskel')
282 'kill_remote_containers.py',
286 'update_catalogs.py',
289 virtual_salome.symlink( os.path.join( appliskel_dir, fn ), os.path.join( home_dir, fn) )
292 if filename != os.path.join(home_dir,"config_appli.xml"):
293 shutil.copyfile(filename, os.path.join(home_dir,"config_appli.xml"))
296 # Creation of env.d directory
297 virtual_salome.mkdir(os.path.join(home_dir,'env.d'))
299 venv_directory_path = _config.get('venv_directory_path')
300 if venv_directory_path and os.path.isdir(venv_directory_path):
301 virtual_salome.symlink(venv_directory_path, os.path.join(home_dir, "venv"))
303 # Get the env modules which will be loaded
304 # In the same way as: module load [MODULE_LIST]
305 env_modules = _config.get('env_modules', [])
307 with open(os.path.join(home_dir, 'env_modules.json'), 'w') as fd:
308 json.dump({"env_modules": env_modules}, fd)
309 with open(os.path.join(home_dir, 'env.d', 'envModules.sh'), 'w') as fd:
310 fd.write('#!/bin/bash\n')
311 fd.write('module load %s\n' % (' '.join(env_modules)))
313 # Copy salome / salome_mesa scripts:
315 for scripts in ('salome', 'salome_mesa', 'salome_common.py'):
316 salome_script = open(os.path.join(appliskel_dir, scripts)).read()
317 salome_file = os.path.join(home_dir, scripts)
319 os.remove(salome_file)
322 with open(salome_file, 'w') as fd:
323 fd.write(salome_script.replace('MODULES = []', 'MODULES = {}'.format(env_modules)))
324 os.chmod(salome_file, 0o755)
326 # Add .salome-completion.sh file
327 shutil.copyfile(os.path.join(appliskel_dir, ".salome-completion.sh"),
328 os.path.join(home_dir, ".salome-completion.sh"))
330 if "prereq_path" in _config and os.path.isfile(_config["prereq_path"]):
331 shutil.copyfile(_config["prereq_path"],
332 os.path.join(home_dir, 'env.d', 'envProducts.sh'))
335 print("WARNING: prerequisite file does not exist")
338 if "context_path" in _config and os.path.isfile(_config["context_path"]):
339 shutil.copyfile(_config["context_path"],
340 os.path.join(home_dir, 'env.d', 'envProducts.cfg'))
343 print("WARNING: context file does not exist")
346 if "sha1_collect_path" in _config and os.path.isfile(_config["sha1_collect_path"]):
347 shutil.copyfile(_config["sha1_collect_path"],
348 os.path.join(home_dir, 'sha1_collections.txt'))
351 print("WARNING: sha1 collections file does not exist")
354 if "system_conf_path" in _config and os.path.isfile(_config["system_conf_path"]):
355 shutil.copyfile(_config["system_conf_path"],
356 os.path.join(home_dir, 'env.d', 'envConfSystem.sh'))
359 # Create environment file: configSalome.sh
361 if "python_version" in _config:
362 versionPython_split = _config["python_version"].split('.')
363 versionPython = versionPython_split[0] + "." + versionPython_split[1]
365 cmd='source %s && python3 -c "import sys ; sys.stdout.write(\\"{}.{}\\".format(sys.version_info.major,sys.version_info.minor))"' %(_config["prereq_path"])
366 versionPython=subprocess.check_output(['/bin/bash', '-l' ,'-c',cmd]).decode("utf-8")
368 venv_directory_path = None
369 if "venv_directory_path" in _config:
370 venv_directory_path = _config["venv_directory_path"]
371 venv_bin_directory_path = os.path.join(venv_directory_path, 'bin')
372 venv_pip_executable = os.path.join(venv_bin_directory_path, 'pip')
373 venv_python_executable = os.path.join(venv_bin_directory_path, 'python')
374 if os.path.isdir(venv_directory_path) and os.path.isfile(venv_pip_executable):
375 requirement_file = os.path.join(home_dir, 'requirements.txt')
376 with open(requirement_file, 'w') as fd:
377 subprocess.call([venv_python_executable, '-m', 'pip', 'freeze'], stdout=fd)
379 venv_directory_path = None
381 with open(os.path.join(home_dir, 'env.d', 'configSalome.sh'),'w') as f:
382 for module in _config.get("modules", []):
383 command = 'export '+ module + '_ROOT_DIR=${HOME}/${APPLI}\n'
386 if "samples_path" in _config:
387 command = 'export DATA_DIR=' + _config["samples_path"] +'\n'
390 if "resources_path" in _config and os.path.isfile(_config["resources_path"]):
391 command = 'export USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
393 # Note: below, PYTHONPATH should not be extended to bin/salome! Python modules must be installed in lib/pythonX.Y, to be fixed (e.g. Kernel SALOME_Container.py)
394 command ="""export PATH=${HOME}/${APPLI}/bin/salome:$PATH
395 export PYTHONPATH=${HOME}/${APPLI}/lib/python%s/site-packages/salome:$PYTHONPATH
396 export PYTHONPATH=${HOME}/${APPLI}/lib/salome:$PYTHONPATH
397 export PYTHONPATH=${HOME}/${APPLI}/bin/salome:$PYTHONPATH
398 export LD_LIBRARY_PATH=${HOME}/${APPLI}/lib/salome:$LD_LIBRARY_PATH
401 # Create environment variable for the salome test
402 for module in _config.get("modules", []):
403 command = "export LD_LIBRARY_PATH=${HOME}/${APPLI}/bin/salome/test/" + module + "/lib:$LD_LIBRARY_PATH\n"
406 # Create environment for plugins GEOM
407 command = "export GEOM_PluginsList=BREPPlugin:STEPPlugin:IGESPlugin:STLPlugin:XAOPlugin:VTKPlugin:AdvancedGEOM\n"
409 # Create environment for Healing
410 command = "export CSF_ShHealingDefaults=${HOME}/${APPLI}/share/salome/resources/geom\n"
412 # Create environment for Meshers
413 command = "export SMESH_MeshersList=StdMeshers:HYBRIDPlugin:HexoticPLUGIN:GMSHPlugin:GHS3DPlugin:NETGENPlugin:HEXABLOCKPlugin:BLSURFPlugin:GHS3DPRLPlugin\nexport SALOME_StdMeshersResources=${HOME}/${APPLI}/share/salome/resources/smesh\n"
415 # Create environment for virtual env
416 if venv_directory_path:
417 command = """# SALOME venv Configuration
418 export SALOME_VENV_DIRECTORY=${HOME}/${APPLI}/venv
419 export PATH=${HOME}/${APPLI}/venv/bin:$PATH
420 export LD_LIBRARY_PATH=${HOME}/${APPLI}/venv/lib:$LD_LIBRARY_PATH
421 export PYTHONPATH=${HOME}/${APPLI}/venv/lib/python%s/site-packages
422 """ % (versionPython)
426 # Create configuration file: configSalome.cfg
427 with open(os.path.join(home_dir, 'env.d', 'configSalome.cfg'),'w') as f:
428 command = "[SALOME ROOT_DIR (modules) Configuration]\n"
430 for module in _config.get("modules", []):
431 command = module + '_ROOT_DIR=${HOME}/${APPLI}\n'
434 if "samples_path" in _config:
435 command = 'DATA_DIR=' + _config["samples_path"] +'\n'
438 if "resources_path" in _config and os.path.isfile(_config["resources_path"]):
439 command = 'USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
441 command ="""ADD_TO_PATH: ${HOME}/${APPLI}/bin/salome
442 ADD_TO_PYTHONPATH: ${HOME}/${APPLI}/lib/python%s/site-packages/salome
443 ADD_TO_PYTHONPATH: ${HOME}/${APPLI}/lib/salome
444 ADD_TO_LD_LIBRARY_PATH: ${HOME}/${APPLI}/lib/salome
447 for module in _config.get("modules", []):
448 command = "ADD_TO_LD_LIBRARY_PATH: ${HOME}/${APPLI}/bin/salome/test/" + module + "/lib\n"
451 # Create environment for plugins GEOM
452 command = "GEOM_PluginsList=BREPPlugin:STEPPlugin:IGESPlugin:STLPlugin:XAOPlugin:VTKPlugin:AdvancedGEOM\n"
454 # Create environment for Healing
455 command = "CSF_ShHealingDefaults=${HOME}/${APPLI}/share/salome/resources/geom\n"
457 # Create environment for Meshers
458 command = "SMESH_MeshersList=StdMeshers:HYBRIDPlugin:HexoticPLUGIN:GMSHPlugin:GHS3DPlugin:NETGENPlugin:HEXABLOCKPlugin:BLSURFPlugin:GHS3DPRLPlugin\nSALOME_StdMeshersResources=${HOME}/${APPLI}/share/salome/resources/smesh\n"
460 # Create environment for virtual env
461 if venv_directory_path:
462 command = """[SALOME venv Configuration]
463 SALOME_VENV_DIRECTORY: ${HOME}/${APPLI}/venv
464 ADD_TO_PATH: ${HOME}/${APPLI}/venv/bin
465 ADD_TO_LD_LIBRARY_PATH: ${HOME}/${APPLI}/venv/lib
466 ADD_TO_PYTHONPATH: ${HOME}/${APPLI}/venv/lib/python%s/site-packages
467 """ % (versionPython)
471 # Create environment file: configGUI.sh
473 salomeappname = "SalomeApp"
474 with open(os.path.join(home_dir, 'env.d', 'configGUI.sh'),'w') as f:
475 for module in _config.get("modules", []):
476 if module not in ["KERNEL", "GUI", ""]:
477 d = os.path.join(_config[module],"share","salome","resources",module.lower())
478 d_appli = os.path.join("${HOME}","${APPLI}","share","salome","resources",module.lower())
479 if os.path.exists( os.path.join(d,"{0}.xml".format(salomeappname)) ):
480 dirs_ress_icon.append( d_appli )
481 AppConfig="export SalomeAppConfig=${HOME}/${APPLI}:${HOME}/${APPLI}/share/salome/resources/gui/"
482 for dir_module in dirs_ress_icon:
483 AppConfig=AppConfig+":"+dir_module
484 f.write(AppConfig+"\n")
485 command = """export SUITRoot=${HOME}/${APPLI}/share/salome
487 export MMGT_REENTRANT=1
491 # Create configuration file: configGUI.cfg
493 with open(os.path.join(home_dir, 'env.d', 'configGUI.cfg'),'w') as f:
494 command = """[SALOME GUI Configuration]\n"""
496 for module in _config.get("modules", []):
497 if module not in ["KERNEL", "GUI", ""]:
498 d = os.path.join(_config[module],"share","salome","resources",module.lower())
499 d_appli = os.path.join("${HOME}","${APPLI}","share","salome","resources",module.lower())
500 if os.path.exists( os.path.join(d,"{0}.xml".format(salomeappname)) ):
501 dirs_ress_icon.append( d_appli )
502 AppConfig="SalomeAppConfig=${HOME}/${APPLI}:${HOME}/${APPLI}/share/salome/resources/gui/"
503 for dir_module in dirs_ress_icon:
504 AppConfig=AppConfig+":"+dir_module
505 f.write(AppConfig+"\n")
506 command = """SUITRoot=${HOME}/${APPLI}/share/salome
513 with open(os.path.join(home_dir,'SalomeApp.xml'),'w') as f:
514 command = """<document>
515 <section name="launch">
516 <!-- SALOME launching parameters -->
517 <parameter name="gui" value="yes"/>
518 <parameter name="splash" value="yes"/>
519 <parameter name="file" value="no"/>
520 <parameter name="key" value="no"/>
521 <parameter name="interp" value="no"/>
522 <parameter name="logger" value="no"/>
523 <parameter name="xterm" value="no"/>
524 <parameter name="portkill" value="no"/>
525 <parameter name="killall" value="no"/>
526 <parameter name="noexcepthandler" value="no"/>
527 <parameter name="modules" value="%s"/>
528 <parameter name="pyModules" value=""/>
529 <parameter name="embedded" value="SalomeAppEngine,study,cppContainer,registry,moduleCatalog"/>
530 <parameter name="standalone" value=""/>
535 #Keep all modules except KERNEL and GUI
536 for module in _config.get("modules", []):
537 if module in ("KERNEL","GUI"):
540 f.write(command % ",".join(mods))
542 #Add USERS directory with 777 permission to store users configuration files
543 users_dir = os.path.join(home_dir,'USERS')
545 os.chmod(users_dir, 0o777)
548 parser = optparse.OptionParser(usage=usage)
550 parser.add_option('--prefix', dest="prefix", default='.',
551 help="Installation directory (default .)")
553 parser.add_option('--config', dest="config", default='config_appli.xml',
554 help="XML configuration file (default config_appli.xml)")
556 parser.add_option('-v', '--verbose', action='count', dest='verbose',
557 default=0, help="Increase verbosity")
559 options, args = parser.parse_args()
560 if not os.path.exists(options.config):
561 print("ERROR: config file %s does not exist. It is mandatory." % options.config)
564 install(prefix=options.prefix, config_file=options.config, verbose=options.verbose)
567 # -----------------------------------------------------------------------------
569 if __name__ == '__main__':