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