Salome HOME
922a8b6615798cb8f374f3ec69b9b605e279b470
[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["modules"]:
185         print "--- add module ", module, _config[module]
186         options = params()
187         options.verbose=verbose
188         options.clear=0
189         options.prefix=home_dir
190         options.module=_config[module]
191         virtual_salome.link_module(options)
192         pass
193
194     appliskel_dir=os.path.join(home_dir,'bin','salome','appliskel')
195
196     for fn in ('envd',
197                'getAppliPath.py',
198                'kill_remote_containers.py',
199                'runAppli',           # OBSOLETE (replaced by salome)
200                'runConsole',         # OBSOLETE (replaced by salome)
201                'runRemote.sh',
202                'runSalomeScript',
203                'runSession',         # OBSOLETE (replaced by salome)
204                'salome',
205                'update_catalogs.py',
206                '.bashrc',
207                ):
208         virtual_salome.symlink( os.path.join( appliskel_dir, fn ), os.path.join( home_dir, fn) )
209         pass
210
211     if filename != os.path.join(home_dir,"config_appli.xml"):
212         command = "cp -p " + filename + ' ' + os.path.join(home_dir,"config_appli.xml")
213         os.system(command)
214         pass
215
216     # Creation of env.d directory
217     virtual_salome.mkdir(os.path.join(home_dir,'env.d'))
218     if os.path.isfile(_config["prereq_path"]):
219         command='cp -p ' + _config["prereq_path"] + ' ' + os.path.join(home_dir,'env.d','envProducts.sh')
220         os.system(command)
221         pass
222     else:
223         print "WARNING: prerequisite file does not exist"
224         pass
225
226     if os.path.isfile(_config["context_path"]):
227         command='cp -p ' + _config["context_path"] + ' ' + os.path.join(home_dir,'env.d','envProducts.cfg')
228         os.system(command)
229         pass
230     else:
231         print "WARNING: context file does not exist"
232         pass
233
234     if _config.has_key("system_conf_path") and os.path.isfile(_config["system_conf_path"]):
235         command='cp -p ' + _config["system_conf_path"] + ' ' + os.path.join(home_dir,'env.d','envConfSystem.sh')
236         os.system(command)
237         pass
238
239
240     # Create environment file: configSalome.sh
241     f =open(os.path.join(home_dir,'env.d','configSalome.sh'),'w')
242     for module in _config["modules"]:
243         command='export '+ module + '_ROOT_DIR=${HOME}/${APPLI}\n'
244         f.write(command)
245         pass
246     if _config.has_key("samples_path"):
247         command='export DATA_DIR=' + _config["samples_path"] +'\n'
248         f.write(command)
249         pass
250     if _config.has_key("resources_path") and os.path.isfile(_config["resources_path"]):
251         command='export USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
252         f.write(command)
253
254     f.close()
255
256     # Create configuration file: configSalome.cfg
257     f =open(os.path.join(home_dir,'env.d','configSalome.cfg'),'w')
258     command = "[SALOME ROOT_DIR (modules) Configuration]\n"
259     f.write(command)
260     for module in _config["modules"]:
261         command=module + '_ROOT_DIR=${HOME}/${APPLI}\n'
262         f.write(command)
263         pass
264     if _config.has_key("samples_path"):
265         command='DATA_DIR=' + _config["samples_path"] +'\n'
266         f.write(command)
267         pass
268     if _config.has_key("resources_path") and os.path.isfile(_config["resources_path"]):
269         command='USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
270         f.write(command)
271
272     f.close()
273
274
275     # Create environment file: configGUI.sh
276     f =open(os.path.join(home_dir,'env.d','configGUI.sh'),'w')
277     command = """export SalomeAppConfig=${HOME}/${APPLI}
278 export SUITRoot=${HOME}/${APPLI}/share/salome
279 export DISABLE_FPE=1
280 export MMGT_REENTRANT=1
281 """
282     f.write(command)
283     f.close()
284
285     # Create configuration file: configGUI.cfg
286     f =open(os.path.join(home_dir,'env.d','configGUI.cfg'),'w')
287     command = """[SALOME GUI Configuration]
288 SalomeAppConfig=${HOME}/${APPLI}
289 SUITRoot=${HOME}/${APPLI}/share/salome
290 DISABLE_FPE=1
291 MMGT_REENTRANT=1
292 """
293     f.write(command)
294     f.close()
295
296     #SalomeApp.xml file
297     f =open(os.path.join(home_dir,'SalomeApp.xml'),'w')
298     command="""<document>
299   <section name="launch">
300     <!-- SALOME launching parameters -->
301     <parameter name="gui"        value="yes"/>
302     <parameter name="splash"     value="yes"/>
303     <parameter name="file"       value="no"/>
304     <parameter name="key"        value="no"/>
305     <parameter name="interp"     value="no"/>
306     <parameter name="logger"     value="no"/>
307     <parameter name="xterm"      value="no"/>
308     <parameter name="portkill"   value="no"/>
309     <parameter name="killall"    value="no"/>
310     <parameter name="noexcepthandler"  value="no"/>
311     <parameter name="modules"    value="%s"/>
312     <parameter name="pyModules"  value=""/>
313     <parameter name="embedded"   value="SalomeAppEngine,study,cppContainer,registry,moduleCatalog"/>
314     <parameter name="standalone" value=""/>
315   </section>
316 </document>
317 """
318     mods=[]
319     #Keep all modules except KERNEL and GUI
320     for m in _config["modules"]:
321       if m in ("KERNEL","GUI"):continue
322       mods.append(m)
323     f.write(command % ",".join(mods))
324     f.close()
325
326     #Add USERS directory with 777 permission to store users configuration files
327     users_dir=os.path.join(home_dir,'USERS')
328     makedirs(users_dir)
329     os.chmod(users_dir, 0777)
330
331 def main():
332     parser = optparse.OptionParser(usage=usage)
333
334     parser.add_option('--prefix', dest="prefix", default='.',
335                       help="Installation directory (default .)")
336
337     parser.add_option('--config', dest="config", default='config_appli.xml',
338                       help="XML configuration file (default config_appli.xml)")
339
340     parser.add_option('-v', '--verbose', action='count', dest='verbose',
341                       default=0, help="Increase verbosity")
342
343     options, args = parser.parse_args()
344     if not os.path.exists(options.config):
345       print "ERROR: config file %s does not exist. It is mandatory." % options.config
346       sys.exit(1)
347
348     install(prefix=options.prefix,config_file=options.config,verbose=options.verbose)
349     pass
350
351 # -----------------------------------------------------------------------------
352
353 if __name__ == '__main__':
354     main()
355     pass