Salome HOME
Merge tag 'V8_5_0' into omu/Launcher9
[modules/kernel.git] / bin / appli_gen.py
1 #! /usr/bin/env python
2 #  -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2017  CEA/DEN, EDF R&D, OPEN CASCADE
4 #
5 # Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
6 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
7 #
8 # This library is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU Lesser General Public
10 # License as published by the Free Software Foundation; either
11 # version 2.1 of the License, or (at your option) any later version.
12 #
13 # This library is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 # Lesser General Public License for more details.
17 #
18 # You should have received a copy of the GNU Lesser General Public
19 # License along with this library; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
21 #
22 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 #
24
25 ## \file appli_gen.py
26 #  Create a %SALOME application (virtual Salome installation)
27 #
28 usage = """%(prog)s [options]
29 Typical use is:
30   python %(prog)s
31 Typical use with options is:
32   python %(prog)s --verbose --prefix=<install directory> --config=<configuration file>
33 """
34
35 import os
36 import sys
37 import shutil
38 import virtual_salome
39 import xml.sax
40 import optparse
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, inst:
195         print inst.getMessage()
196         print "Configure parser: parse error in configuration file %s" % filename
197         pass
198     except xml.sax.SAXException, inst:
199         print inst.args
200         print "Configure parser: error in configuration file %s" % filename
201         pass
202     except Exception as e:
203         print "Configure parser: Error : can not read configuration file %s, check existence and rights" % filename
204         print(e)
205         pass
206
207     if verbose:
208         for cle,val in _config.items():
209             print cle, val
210             pass
211
212     # Remove CTestTestfile.cmake; this file will be filled by successive calls to link_module and link_extra_test
213     try:
214       ctest_file = os.path.join(home_dir, 'bin', 'salome', 'test', "CTestTestfile.cmake")
215       os.remove(ctest_file)
216     except:
217       pass
218
219     for module in _config.get("modules", []):
220         if _config.has_key(module):
221             print "--- add module ", module, _config[module]
222             options = params()
223             options.verbose = verbose
224             options.clear = 0
225             options.prefix = home_dir
226             options.module_name = module
227             options.module_path = _config[module]
228             virtual_salome.link_module(options)
229             pass
230         pass
231
232     for extra_test in _config.get("extra_tests", []):
233         if _config.has_key(extra_test):
234             print "--- add extra test ", extra_test, _config[extra_test]
235             options = params()
236             options.verbose = verbose
237             options.clear = 0
238             options.prefix = home_dir
239             options.extra_test_name = extra_test
240             options.extra_test_path = _config[extra_test]
241             virtual_salome.link_extra_test(options)
242             pass
243         pass
244
245     # Generate CTestCustom.cmake to handle long output
246     ctest_custom = os.path.join(home_dir, 'bin', 'salome', 'test', "CTestCustom.cmake")
247     with open(ctest_custom, 'w') as f:
248       f.write("SET(CTEST_CUSTOM_MAXIMUM_PASSED_TEST_OUTPUT_SIZE 1048576) # 1MB\n")
249       f.write("SET(CTEST_CUSTOM_MAXIMUM_FAILED_TEST_OUTPUT_SIZE 1048576) # 1MB\n")
250
251     appliskel_dir = os.path.join(home_dir, 'bin', 'salome', 'appliskel')
252
253     for fn in ('envd',
254                'getAppliPath.py',
255                'kill_remote_containers.py',
256                'runRemote.sh',
257                '.salome_run',
258                'update_catalogs.py',
259                '.bashrc',
260                ):
261         virtual_salome.symlink( os.path.join( appliskel_dir, fn ), os.path.join( home_dir, fn) )
262         pass
263
264     if filename != os.path.join(home_dir,"config_appli.xml"):
265         shutil.copyfile(filename, os.path.join(home_dir,"config_appli.xml"))
266         pass
267
268
269     # Copy salome script 
270     salome_script = open(os.path.join(appliskel_dir, "salome")).read()
271     salome_file = os.path.join(home_dir, "salome")
272     try:
273         os.remove(salome_file)
274     except:
275         pass
276     env_modules = [m.encode('utf8') for m in _config.get('env_modules', [])]
277     with open(salome_file, 'w') as fd:
278         fd.write(salome_script.replace('MODULES = []', 'MODULES = {}'.format(env_modules)))
279     os.chmod(salome_file, 0o755)
280
281
282     # Add .salome-completion.sh file
283     shutil.copyfile(os.path.join(appliskel_dir, ".salome-completion.sh"),
284                     os.path.join(home_dir, ".salome-completion.sh"))
285
286
287     # Creation of env.d directory
288     virtual_salome.mkdir(os.path.join(home_dir,'env.d'))
289
290     if _config.has_key("prereq_path") and os.path.isfile(_config["prereq_path"]):
291         shutil.copyfile(_config["prereq_path"],
292                         os.path.join(home_dir, 'env.d', 'envProducts.sh'))
293         pass
294     else:
295         print "WARNING: prerequisite file does not exist"
296         pass
297
298     if _config.has_key("context_path") and os.path.isfile(_config["context_path"]):
299         shutil.copyfile(_config["context_path"],
300                         os.path.join(home_dir, 'env.d', 'envProducts.cfg'))
301         pass
302     else:
303         print "WARNING: context file does not exist"
304         pass
305
306     if _config.has_key("sha1_collect_path") and os.path.isfile(_config["sha1_collect_path"]):
307         shutil.copyfile(_config["sha1_collect_path"],
308                         os.path.join(home_dir, 'sha1_collections.txt'))
309         pass
310     else:
311         print "WARNING: sha1 collections file does not exist"
312         pass
313
314     if _config.has_key("system_conf_path") and os.path.isfile(_config["system_conf_path"]):
315         shutil.copyfile(_config["system_conf_path"],
316                         os.path.join(home_dir, 'env.d', 'envConfSystem.sh'))
317         pass
318
319     # Create environment file: configSalome.sh
320     with open(os.path.join(home_dir, 'env.d', 'configSalome.sh'),'w') as f:
321         for module in _config.get("modules", []):
322             command = 'export '+ module + '_ROOT_DIR=${HOME}/${APPLI}\n'
323             f.write(command)
324             pass
325         if _config.has_key("samples_path"):
326             command = 'export DATA_DIR=' + _config["samples_path"] +'\n'
327             f.write(command)
328             pass
329         if _config.has_key("resources_path") and os.path.isfile(_config["resources_path"]):
330             command = 'export USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
331             f.write(command)
332
333     # Create configuration file: configSalome.cfg
334     with open(os.path.join(home_dir, 'env.d', 'configSalome.cfg'),'w') as f:
335         command = "[SALOME ROOT_DIR (modules) Configuration]\n"
336         f.write(command)
337         for module in _config.get("modules", []):
338             command = module + '_ROOT_DIR=${HOME}/${APPLI}\n'
339             f.write(command)
340             pass
341         if _config.has_key("samples_path"):
342             command = 'DATA_DIR=' + _config["samples_path"] +'\n'
343             f.write(command)
344             pass
345         if _config.has_key("resources_path") and os.path.isfile(_config["resources_path"]):
346             command = 'USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
347             f.write(command)
348
349
350     # Create environment file: configGUI.sh
351     with open(os.path.join(home_dir, 'env.d', 'configGUI.sh'),'w') as f:
352         command = """export SalomeAppConfig=${HOME}/${APPLI}
353 export SUITRoot=${HOME}/${APPLI}/share/salome
354 export DISABLE_FPE=1
355 export MMGT_REENTRANT=1
356 """
357         f.write(command)
358
359     # Create configuration file: configGUI.cfg
360     with open(os.path.join(home_dir, 'env.d', 'configGUI.cfg'),'w') as f:
361         command = """[SALOME GUI Configuration]
362 SalomeAppConfig=${HOME}/${APPLI}
363 SUITRoot=${HOME}/${APPLI}/share/salome
364 DISABLE_FPE=1
365 MMGT_REENTRANT=1
366 """
367         f.write(command)
368
369     #SalomeApp.xml file
370     with open(os.path.join(home_dir,'SalomeApp.xml'),'w') as f:
371         command = """<document>
372   <section name="launch">
373     <!-- SALOME launching parameters -->
374     <parameter name="gui"        value="yes"/>
375     <parameter name="splash"     value="yes"/>
376     <parameter name="file"       value="no"/>
377     <parameter name="key"        value="no"/>
378     <parameter name="interp"     value="no"/>
379     <parameter name="logger"     value="no"/>
380     <parameter name="xterm"      value="no"/>
381     <parameter name="portkill"   value="no"/>
382     <parameter name="killall"    value="no"/>
383     <parameter name="noexcepthandler"  value="no"/>
384     <parameter name="modules"    value="%s"/>
385     <parameter name="pyModules"  value=""/>
386     <parameter name="embedded"   value="SalomeAppEngine,study,cppContainer,registry,moduleCatalog"/>
387     <parameter name="standalone" value=""/>
388   </section>
389 </document>
390 """
391         mods = []
392         #Keep all modules except KERNEL and GUI
393         for module in _config.get("modules", []):
394             if module in ("KERNEL","GUI"):
395                 continue
396             mods.append(module)
397         f.write(command % ",".join(mods))
398
399     #Add USERS directory with 777 permission to store users configuration files
400     users_dir = os.path.join(home_dir,'USERS')
401     makedirs(users_dir)
402     os.chmod(users_dir, 0777)
403
404 def main():
405     parser = optparse.OptionParser(usage=usage)
406
407     parser.add_option('--prefix', dest="prefix", default='.',
408                       help="Installation directory (default .)")
409
410     parser.add_option('--config', dest="config", default='config_appli.xml',
411                       help="XML configuration file (default config_appli.xml)")
412
413     parser.add_option('-v', '--verbose', action='count', dest='verbose',
414                       default=0, help="Increase verbosity")
415
416     options, args = parser.parse_args()
417     if not os.path.exists(options.config):
418         print "ERROR: config file %s does not exist. It is mandatory." % options.config
419         sys.exit(1)
420
421     install(prefix=options.prefix, config_file=options.config, verbose=options.verbose)
422     pass
423
424 # -----------------------------------------------------------------------------
425
426 if __name__ == '__main__':
427     main()
428     pass