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