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