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