]> SALOME platform Git repositories - modules/kernel.git/blob - bin/appli_gen.py
Salome HOME
Merge from V5_1_main branch 24/11/2010
[modules/kernel.git] / bin / appli_gen.py
1 #! /usr/bin/env python
2 #  -*- coding: iso-8859-1 -*-
3 #  Copyright (C) 2007-2010  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.
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="""usage: %prog [options]
29 Typical use is:
30   python appli_gen.py
31 Typical use with options is:
32   python appli_gen.py --verbose --prefix=<install directory> --config=<configuration file>
33 """
34
35 import os, glob, string, sys, re
36 import shutil
37 import xml.sax
38 import optparse
39 import virtual_salome
40
41 # --- names of tags in XML configuration file
42 appli_tag   = "application"
43 prereq_tag  = "prerequisites"
44 modules_tag = "modules"
45 module_tag  = "module"
46 samples_tag = "samples"
47 resources_tag = "resources"
48
49 # --- names of attributes in XML configuration file
50 nam_att  = "name"
51 path_att = "path"
52 gui_att  = "gui"
53
54 # -----------------------------------------------------------------------------
55
56 # --- xml reader for SALOME application configuration file
57
58 class xml_parser:
59     def __init__(self, fileName ):
60         print "Configure parser: processing %s ..." % fileName
61         self.space = []
62         self.config = {}
63         self.config["modules"] = []
64         self.config["guimodules"] = []
65         parser = xml.sax.make_parser()
66         parser.setContentHandler(self)
67         parser.parse(fileName)
68         pass
69
70     def boolValue( self, str ):
71         if str in ("yes", "y", "1"):
72             return 1
73         elif str in ("no", "n", "0"):
74             return 0
75         else:
76             return str
77         pass
78
79     def startElement(self, name, attrs):
80         self.space.append(name)
81         self.current = None
82         # --- if we are analyzing "prerequisites" element then store its "path" attribute
83         if self.space == [appli_tag, prereq_tag] and path_att in attrs.getNames():
84             self.config["prereq_path"] = attrs.getValue( path_att )
85             pass
86         # --- if we are analyzing "resources" element then store its "path" attribute
87         if self.space == [appli_tag, resources_tag] and path_att in attrs.getNames():
88             self.config["resources_path"] = attrs.getValue( path_att )
89             pass
90         # --- if we are analyzing "samples" element then store its "path" attribute
91         if self.space == [appli_tag, samples_tag] and path_att in attrs.getNames():
92             self.config["samples_path"] = attrs.getValue( path_att )
93             pass
94         # --- if we are analyzing "module" element then store its "name" and "path" attributes
95         elif self.space == [appli_tag,modules_tag,module_tag] and \
96             nam_att in attrs.getNames() and \
97             path_att in attrs.getNames():
98             nam = attrs.getValue( nam_att )
99             path = attrs.getValue( path_att )
100             gui = 1
101             if gui_att in attrs.getNames():
102                 gui = self.boolValue(attrs.getValue( gui_att ))
103                 pass
104             self.config["modules"].append(nam)
105             self.config[nam]=path
106             if gui:
107                 self.config["guimodules"].append(nam)
108                 pass
109             pass
110         pass
111
112     def endElement(self, name):
113         p = self.space.pop()
114         self.current = None
115         pass
116
117     def characters(self, content):
118         pass
119
120     def processingInstruction(self, target, data):
121         pass
122
123     def setDocumentLocator(self, locator):
124         pass
125
126     def startDocument(self):
127         self.read = None
128         pass
129
130     def endDocument(self):
131         self.read = None
132         pass
133
134 # -----------------------------------------------------------------------------
135
136 class params:
137     pass
138
139 # -----------------------------------------------------------------------------
140
141 def makedirs(namedir):
142   if os.path.exists(namedir):
143     dirbak=namedir+".bak"
144     if os.path.exists(dirbak):
145       shutil.rmtree(dirbak)
146     os.rename(namedir,dirbak)
147     os.listdir(dirbak) #sert seulement a mettre a jour le systeme de fichier sur certaines machines
148   os.makedirs(namedir)
149
150 def install(prefix,config_file,verbose=0):
151     home_dir=os.path.abspath(os.path.expanduser(prefix))
152     filename=os.path.abspath(os.path.expanduser(config_file))
153     _config={}
154     try:
155         p = xml_parser(filename)
156         _config = p.config
157     except xml.sax.SAXParseException, inst:
158         print inst.getMessage()
159         print "Configure parser: parse error in configuration file %s" % filename
160         pass
161     except xml.sax.SAXException, inst:
162         print inst.args
163         print "Configure parser: error in configuration file %s" % filename
164         pass
165     except:
166         print "Configure parser: Error : can not read configuration file %s, check existence and rights" % filename
167         pass
168
169     if verbose:
170         for cle in _config.keys():
171             print cle, _config[cle]
172             pass
173
174     for module in _config["modules"]:
175         print "--- add module ", module, _config[module]
176         options = params()
177         options.verbose=verbose
178         options.clear=0
179         options.prefix=home_dir
180         options.module=_config[module]
181         virtual_salome.link_module(options)
182         pass
183
184     appliskel_dir=os.path.join(home_dir,'bin','salome','appliskel')
185
186     for fn in ('envd',
187                'getAppliPath.py',
188                'searchFreePort.sh',
189                'runRemote.sh',
190                'runAppli',
191                'runConsole',
192                'runSession',
193                'runSalomeScript',
194                'runTests',
195                'update_catalogs.py',
196                '.bashrc',
197                ):
198         virtual_salome.symlink("./bin/salome/appliskel/"+fn,os.path.join(home_dir, fn))
199         pass
200
201     if filename != os.path.join(home_dir,"config_appli.xml"):
202         command = "cp -p " + filename + ' ' + os.path.join(home_dir,"config_appli.xml")
203         os.system(command)
204         pass
205
206     virtual_salome.mkdir(os.path.join(home_dir,'env.d'))
207     if os.path.isfile(_config["prereq_path"]):
208         command='cp -p ' + _config["prereq_path"] + ' ' + os.path.join(home_dir,'env.d','envProducts.sh')
209         os.system(command)
210         pass
211     else:
212         print "WARNING: prerequisite file does not exist"
213         pass
214
215
216     f =open(os.path.join(home_dir,'env.d','configSalome.sh'),'w')
217     for module in _config["modules"]:
218         command='export '+ module + '_ROOT_DIR=${HOME}/${APPLI}\n'
219         f.write(command)
220         pass
221     if _config.has_key("samples_path"):
222         command='export DATA_DIR=' + _config["samples_path"] +'\n'
223         f.write(command)
224         pass
225     if _config.has_key("resources_path") and os.path.isfile(_config["resources_path"]):
226         command='export USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
227         f.write(command)
228
229     f.close()
230
231
232     f =open(os.path.join(home_dir,'env.d','configGUI.sh'),'w')
233     command = 'export SalomeAppConfig=${HOME}/${APPLI}\n'
234     f.write(command)
235     command = 'export SUITRoot=${HOME}/${APPLI}/share/salome\n'
236     f.write(command)
237     f.write('export DISABLE_FPE=1\n')
238     f.write('export MMGT_REENTRANT=1\n')
239     f.close()
240
241
242     f =open(os.path.join(home_dir,'SalomeApp.xml'),'w')
243     command="""<document>
244   <section name="launch">
245     <!-- SALOME launching parameters -->
246     <parameter name="gui"        value="yes"/>
247     <parameter name="splash"     value="yes"/>
248     <parameter name="file"       value="no"/>
249     <parameter name="key"        value="no"/>
250     <parameter name="interp"     value="no"/>
251     <parameter name="logger"     value="no"/>
252     <parameter name="xterm"      value="no"/>
253     <parameter name="portkill"   value="no"/>
254     <parameter name="killall"    value="no"/>
255     <parameter name="noexcepthandler"  value="no"/>
256     <parameter name="modules"    value="""
257     f.write(command)
258     f.write('"')
259     for module in _config["guimodules"][:-1]:
260         f.write(module)
261         f.write(',')
262         pass
263     if len(_config["guimodules"]) > 0:
264       f.write(_config["guimodules"][-1])
265     f.write('"/>')
266     command="""
267     <parameter name="pyModules"  value=""/>
268     <parameter name="embedded"   value="SalomeAppEngine,study,cppContainer,registry,moduleCatalog"/>
269     <parameter name="standalone" value="pyContainer"/>
270   </section>
271 </document>
272 """
273     f.write(command)
274     f.close()
275
276     #Add default CatalogResources.xml file
277     f =open(os.path.join(home_dir,'CatalogResources.xml'),'w')
278     command="""<!DOCTYPE ResourcesCatalog>
279 <resources>
280    <machine name="localhost"
281             hostname="localhost" />
282 </resources>
283 """
284     f.write(command)
285     f.close()
286
287     #Add USERS directory with 777 permission to store users configuration files
288     users_dir=os.path.join(home_dir,'USERS')
289     makedirs(users_dir)
290     os.chmod(users_dir, 0777)
291
292 def main():
293     parser = optparse.OptionParser(usage=usage)
294
295     parser.add_option('--prefix', dest="prefix", default='.',
296                       help="Installation directory (default .)")
297
298     parser.add_option('--config', dest="config", default='config_appli.xml',
299                       help="XML configuration file (default config_appli.xml)")
300
301     parser.add_option('-v', '--verbose', action='count', dest='verbose',
302                       default=0, help="Increase verbosity")
303
304     options, args = parser.parse_args()
305     if not os.path.exists(options.config):
306       print "ERROR: config file %s does not exist. It is mandatory." % options.config
307       sys.exit(1)
308
309     install(prefix=options.prefix,config_file=options.config,verbose=options.verbose)
310     pass
311
312 # -----------------------------------------------------------------------------
313
314 if __name__ == '__main__':
315     main()
316     pass