Salome HOME
Correct Python wrappings for SALOMEDS::TMPFile and Engines::TMPFile IDL types
[modules/kernel.git] / bin / appli_gen.py
1 #! /usr/bin/env python3
2 # Copyright (C) 2007-2017  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
41 # --- names of tags in XML configuration file
42 appli_tag   = "application"
43 prereq_tag  = "prerequisites"
44 context_tag = "context"
45 sha1_collect_tag = "sha1_collections"
46 system_conf_tag  = "system_conf"
47 modules_tag = "modules"
48 module_tag  = "module"
49 samples_tag = "samples"
50 extra_tests_tag = "extra_tests"
51 extra_test_tag = "extra_test"
52 resources_tag = "resources"
53 env_modules_tag = "env_modules"
54 env_module_tag = "env_module"
55
56 # --- names of attributes in XML configuration file
57 nam_att  = "name"
58 path_att = "path"
59 gui_att  = "gui"
60
61 # -----------------------------------------------------------------------------
62
63 # --- xml reader for SALOME application configuration file
64
65 class xml_parser:
66     def __init__(self, fileName ):
67         print("Configure parser: processing %s ..." % fileName)
68         self.space = []
69         self.config = {}
70         self.config["modules"] = []
71         self.config["guimodules"] = []
72         self.config["extra_tests"] = []
73         self.config["env_modules"] = []
74         parser = xml.sax.make_parser()
75         parser.setContentHandler(self)
76         parser.parse(fileName)
77         pass
78
79     def boolValue( self, text):
80         if text in ("yes", "y", "1"):
81             return 1
82         elif text in ("no", "n", "0"):
83             return 0
84         else:
85             return text
86         pass
87
88     def startElement(self, name, attrs):
89         self.space.append(name)
90         self.current = None
91         # --- if we are analyzing "prerequisites" element then store its "path" attribute
92         if self.space == [appli_tag, prereq_tag] and path_att in attrs.getNames():
93             self.config["prereq_path"] = attrs.getValue( path_att )
94             pass
95         # --- if we are analyzing "context" element then store its "path" attribute
96         if self.space == [appli_tag, context_tag] and path_att in attrs.getNames():
97             self.config["context_path"] = attrs.getValue( path_att )
98             pass
99         # --- if we are analyzing "sha1_collection" element then store its "path" attribute
100         if self.space == [appli_tag, sha1_collect_tag] and path_att in attrs.getNames():
101             self.config["sha1_collect_path"] = attrs.getValue( path_att )
102             pass
103         # --- if we are analyzing "system_conf" element then store its "path" attribute
104         if self.space == [appli_tag, system_conf_tag] and path_att in attrs.getNames():
105             self.config["system_conf_path"] = attrs.getValue( path_att )
106             pass
107         # --- if we are analyzing "resources" element then store its "path" attribute
108         if self.space == [appli_tag, resources_tag] and path_att in attrs.getNames():
109             self.config["resources_path"] = attrs.getValue( path_att )
110             pass
111         # --- if we are analyzing "samples" element then store its "path" attribute
112         if self.space == [appli_tag, samples_tag] and path_att in attrs.getNames():
113             self.config["samples_path"] = attrs.getValue( path_att )
114             pass
115         # --- if we are analyzing "module" element then store its "name" and "path" attributes
116         elif self.space == [appli_tag,modules_tag,module_tag] and \
117             nam_att in attrs.getNames() and \
118             path_att in attrs.getNames():
119             nam = attrs.getValue( nam_att )
120             path = attrs.getValue( path_att )
121             gui = 1
122             if gui_att in attrs.getNames():
123                 gui = self.boolValue(attrs.getValue( gui_att ))
124                 pass
125             self.config["modules"].append(nam)
126             self.config[nam]=path
127             if gui:
128                 self.config["guimodules"].append(nam)
129                 pass
130             pass
131         # --- if we are analyzing "env_module" element then store its "name" attribute
132         elif self.space == [appli_tag, env_modules_tag, env_module_tag] and \
133                 nam_att in attrs.getNames():
134             nam = attrs.getValue( nam_att )
135             self.config["env_modules"].append(nam)
136             pass
137         # --- if we are analyzing "extra_test" element then store its "name" and "path" attributes
138         elif self.space == [appli_tag,extra_tests_tag,extra_test_tag] and \
139             nam_att in attrs.getNames() and \
140             path_att in attrs.getNames():
141             nam = attrs.getValue( nam_att )
142             path = attrs.getValue( path_att )
143             self.config["extra_tests"].append(nam)
144             self.config[nam]=path
145             pass
146         pass
147
148     def endElement(self, name):
149         self.space.pop()
150         self.current = None
151         pass
152
153     def characters(self, content):
154         pass
155
156     def processingInstruction(self, target, data):
157         pass
158
159     def setDocumentLocator(self, locator):
160         pass
161
162     def startDocument(self):
163         self.read = None
164         pass
165
166     def endDocument(self):
167         self.read = None
168         pass
169
170 # -----------------------------------------------------------------------------
171
172 class params:
173     pass
174
175 # -----------------------------------------------------------------------------
176
177 def makedirs(namedir):
178   if os.path.exists(namedir):
179     dirbak = namedir+".bak"
180     if os.path.exists(dirbak):
181       shutil.rmtree(dirbak)
182     os.rename(namedir, dirbak)
183     os.listdir(dirbak) #sert seulement a mettre a jour le systeme de fichier sur certaines machines
184   os.makedirs(namedir)
185
186 def install(prefix, config_file, verbose=0):
187     home_dir = os.path.abspath(os.path.expanduser(prefix))
188     filename = os.path.abspath(os.path.expanduser(config_file))
189     _config = {}
190     try:
191         parser = xml_parser(filename)
192         _config = parser.config
193     except xml.sax.SAXParseException as inst:
194         print(inst.getMessage())
195         print("Configure parser: parse error in configuration file %s" % filename)
196         pass
197     except xml.sax.SAXException as inst:
198         print(inst.args)
199         print("Configure parser: error in configuration file %s" % filename)
200         pass
201     except:
202         print("Configure parser: Error : can not read configuration file %s, check existence and rights" % filename)
203         pass
204
205     if verbose:
206         for cle,val in _config.items():
207             print(cle, val)
208             pass
209
210     # Remove CTestTestfile.cmake; this file will be filled by successive calls to link_module and link_extra_test
211     try:
212       ctest_file = os.path.join(home_dir, 'bin', 'salome', 'test', "CTestTestfile.cmake")
213       os.remove(ctest_file)
214     except:
215       pass
216
217     for module in _config.get("modules", []):
218         if module in _config:
219             print("--- add module ", module, _config[module])
220             options = params()
221             options.verbose = verbose
222             options.clear = 0
223             options.prefix = home_dir
224             options.module_name = module
225             options.module_path = _config[module]
226             virtual_salome.link_module(options)
227             pass
228         pass
229
230     for extra_test in _config.get("extra_tests", []):
231         if extra_test in _config:
232             print("--- add extra test ", extra_test, _config[extra_test])
233             options = params()
234             options.verbose = verbose
235             options.clear = 0
236             options.prefix = home_dir
237             options.extra_test_name = extra_test
238             options.extra_test_path = _config[extra_test]
239             virtual_salome.link_extra_test(options)
240             pass
241         pass
242
243     # Generate CTestCustom.cmake to handle long output
244     ctest_custom = os.path.join(home_dir, 'bin', 'salome', 'test', "CTestCustom.cmake")
245     with open(ctest_custom, 'w') as f:
246       f.write("SET(CTEST_CUSTOM_MAXIMUM_PASSED_TEST_OUTPUT_SIZE 1048576) # 1MB\n")
247       f.write("SET(CTEST_CUSTOM_MAXIMUM_FAILED_TEST_OUTPUT_SIZE 1048576) # 1MB\n")
248
249     appliskel_dir = os.path.join(home_dir, 'bin', 'salome', 'appliskel')
250
251     for fn in ('envd',
252                'getAppliPath.py',
253                'kill_remote_containers.py',
254                'runRemote.sh',
255                '.salome_run',
256                'update_catalogs.py',
257                '.bashrc',
258                ):
259         virtual_salome.symlink( os.path.join( appliskel_dir, fn ), os.path.join( home_dir, fn) )
260         pass
261
262     if filename != os.path.join(home_dir,"config_appli.xml"):
263         shutil.copyfile(filename, os.path.join(home_dir,"config_appli.xml"))
264         pass
265
266
267     # Copy salome script 
268     salome_script = open(os.path.join(appliskel_dir, "salome")).read()
269     salome_file = os.path.join(home_dir, "salome")
270     try:
271         os.remove(salome_file)
272     except:
273         pass
274     env_modules = _config.get('env_modules', [])
275     with open(salome_file, 'w') as fd:
276         fd.write(salome_script.replace('MODULES = []', 'MODULES = {}'.format(env_modules)))
277     os.chmod(salome_file, 0o755)
278
279
280     # Add .salome-completion.sh file
281     shutil.copyfile(os.path.join(appliskel_dir, ".salome-completion.sh"),
282                     os.path.join(home_dir, ".salome-completion.sh"))
283
284
285     # Creation of env.d directory
286     virtual_salome.mkdir(os.path.join(home_dir,'env.d'))
287
288     if "prereq_path" in _config and os.path.isfile(_config["prereq_path"]):
289         shutil.copyfile(_config["prereq_path"],
290                         os.path.join(home_dir, 'env.d', 'envProducts.sh'))
291         pass
292     else:
293         print("WARNING: prerequisite file does not exist")
294         pass
295
296     if "context_path" in _config and os.path.isfile(_config["context_path"]):
297         shutil.copyfile(_config["context_path"],
298                         os.path.join(home_dir, 'env.d', 'envProducts.cfg'))
299         pass
300     else:
301         print("WARNING: context file does not exist")
302         pass
303
304     if "sha1_collect_path" in _config and os.path.isfile(_config["sha1_collect_path"]):
305         shutil.copyfile(_config["sha1_collect_path"],
306                         os.path.join(home_dir, 'sha1_collections.txt'))
307         pass
308     else:
309         print("WARNING: sha1 collections file does not exist")
310         pass
311
312     if "system_conf_path" in _config and os.path.isfile(_config["system_conf_path"]):
313         shutil.copyfile(_config["system_conf_path"],
314                         os.path.join(home_dir, 'env.d', 'envConfSystem.sh'))
315         pass
316
317     # Create environment file: configSalome.sh
318     with open(os.path.join(home_dir, 'env.d', 'configSalome.sh'),'w') as f:
319         for module in _config.get("modules", []):
320             command = 'export '+ module + '_ROOT_DIR=${HOME}/${APPLI}\n'
321             f.write(command)
322             pass
323         if "samples_path" in _config:
324             command = 'export DATA_DIR=' + _config["samples_path"] +'\n'
325             f.write(command)
326             pass
327         if "resources_path" in _config and os.path.isfile(_config["resources_path"]):
328             command = 'export USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
329             f.write(command)
330
331     # Create configuration file: configSalome.cfg
332     with open(os.path.join(home_dir, 'env.d', 'configSalome.cfg'),'w') as f:
333         command = "[SALOME ROOT_DIR (modules) Configuration]\n"
334         f.write(command)
335         for module in _config.get("modules", []):
336             command = module + '_ROOT_DIR=${HOME}/${APPLI}\n'
337             f.write(command)
338             pass
339         if "samples_path" in _config:
340             command = 'DATA_DIR=' + _config["samples_path"] +'\n'
341             f.write(command)
342             pass
343         if "resources_path" in _config and os.path.isfile(_config["resources_path"]):
344             command = 'USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
345             f.write(command)
346
347
348     # Create environment file: configGUI.sh
349     with open(os.path.join(home_dir, 'env.d', 'configGUI.sh'),'w') as f:
350         command = """export SalomeAppConfig=${HOME}/${APPLI}
351 export SUITRoot=${HOME}/${APPLI}/share/salome
352 export DISABLE_FPE=1
353 export MMGT_REENTRANT=1
354 """
355         f.write(command)
356
357     # Create configuration file: configGUI.cfg
358     with open(os.path.join(home_dir, 'env.d', 'configGUI.cfg'),'w') as f:
359         command = """[SALOME GUI Configuration]
360 SalomeAppConfig=${HOME}/${APPLI}
361 SUITRoot=${HOME}/${APPLI}/share/salome
362 DISABLE_FPE=1
363 MMGT_REENTRANT=1
364 """
365         f.write(command)
366
367     #SalomeApp.xml file
368     with open(os.path.join(home_dir,'SalomeApp.xml'),'w') as f:
369         command = """<document>
370   <section name="launch">
371     <!-- SALOME launching parameters -->
372     <parameter name="gui"        value="yes"/>
373     <parameter name="splash"     value="yes"/>
374     <parameter name="file"       value="no"/>
375     <parameter name="key"        value="no"/>
376     <parameter name="interp"     value="no"/>
377     <parameter name="logger"     value="no"/>
378     <parameter name="xterm"      value="no"/>
379     <parameter name="portkill"   value="no"/>
380     <parameter name="killall"    value="no"/>
381     <parameter name="noexcepthandler"  value="no"/>
382     <parameter name="modules"    value="%s"/>
383     <parameter name="pyModules"  value=""/>
384     <parameter name="embedded"   value="SalomeAppEngine,study,cppContainer,registry,moduleCatalog"/>
385     <parameter name="standalone" value=""/>
386   </section>
387 </document>
388 """
389         mods = []
390         #Keep all modules except KERNEL and GUI
391         for module in _config.get("modules", []):
392             if module in ("KERNEL","GUI"):
393                 continue
394             mods.append(module)
395         f.write(command % ",".join(mods))
396
397     #Add USERS directory with 777 permission to store users configuration files
398     users_dir = os.path.join(home_dir,'USERS')
399     makedirs(users_dir)
400     os.chmod(users_dir, 0o777)
401
402 def main():
403     parser = optparse.OptionParser(usage=usage)
404
405     parser.add_option('--prefix', dest="prefix", default='.',
406                       help="Installation directory (default .)")
407
408     parser.add_option('--config', dest="config", default='config_appli.xml',
409                       help="XML configuration file (default config_appli.xml)")
410
411     parser.add_option('-v', '--verbose', action='count', dest='verbose',
412                       default=0, help="Increase verbosity")
413
414     options, args = parser.parse_args()
415     if not os.path.exists(options.config):
416         print("ERROR: config file %s does not exist. It is mandatory." % options.config)
417         sys.exit(1)
418
419     install(prefix=options.prefix, config_file=options.config, verbose=options.verbose)
420     pass
421
422 # -----------------------------------------------------------------------------
423
424 if __name__ == '__main__':
425     main()
426     pass