]> SALOME platform Git repositories - modules/kernel.git/blob - bin/appli_gen.py
Salome HOME
e8b9f9fc24950d42d5f37cfc78f083b36e97331b
[modules/kernel.git] / bin / appli_gen.py
1 #! /usr/bin/env python3
2 # Copyright (C) 2007-2017  CEA/DEN, EDF R&D, OPEN CASCADE
3 #
4 # Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
5 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 #
7 # This library is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU Lesser General Public
9 # License as published by the Free Software Foundation; either
10 # version 2.1 of the License, or (at your option) any later version.
11 #
12 # This library is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 # Lesser General Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser General Public
18 # License along with this library; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
20 #
21 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 #
23
24 ## \file appli_gen.py
25 #  Create a %SALOME application (virtual Salome installation)
26 #
27 usage = """%(prog)s [options]
28 Typical use is:
29   python %(prog)s
30 Typical use with options is:
31   python %(prog)s --verbose --prefix=<install directory> --config=<configuration file>
32 """
33
34 import os
35 import sys
36 import shutil
37 import virtual_salome
38 import xml.sax
39 import optparse
40
41 # --- names of tags in XML configuration file
42 appli_tag   = "application"
43 prereq_tag  = "prerequisites"
44 context_tag = "context"
45 sha1_collect_tag = "sha1_collections"
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 "sha1_collection" element then store its "path" attribute
97         if self.space == [appli_tag, sha1_collect_tag] and path_att in attrs.getNames():
98             self.config["sha1_collect_path"] = attrs.getValue( path_att )
99             pass
100         # --- if we are analyzing "system_conf" element then store its "path" attribute
101         if self.space == [appli_tag, system_conf_tag] and path_att in attrs.getNames():
102             self.config["system_conf_path"] = attrs.getValue( path_att )
103             pass
104         # --- if we are analyzing "resources" element then store its "path" attribute
105         if self.space == [appli_tag, resources_tag] and path_att in attrs.getNames():
106             self.config["resources_path"] = attrs.getValue( path_att )
107             pass
108         # --- if we are analyzing "samples" element then store its "path" attribute
109         if self.space == [appli_tag, samples_tag] and path_att in attrs.getNames():
110             self.config["samples_path"] = attrs.getValue( path_att )
111             pass
112         # --- if we are analyzing "module" element then store its "name" and "path" attributes
113         elif self.space == [appli_tag,modules_tag,module_tag] and \
114             nam_att in attrs.getNames() and \
115             path_att in attrs.getNames():
116             nam = attrs.getValue( nam_att )
117             path = attrs.getValue( path_att )
118             gui = 1
119             if gui_att in attrs.getNames():
120                 gui = self.boolValue(attrs.getValue( gui_att ))
121                 pass
122             self.config["modules"].append(nam)
123             self.config[nam]=path
124             if gui:
125                 self.config["guimodules"].append(nam)
126                 pass
127             pass
128         # --- if we are analyzing "extra_test" element then store its "name" and "path" attributes
129         elif self.space == [appli_tag,extra_tests_tag,extra_test_tag] and \
130             nam_att in attrs.getNames() and \
131             path_att in attrs.getNames():
132             nam = attrs.getValue( nam_att )
133             path = attrs.getValue( path_att )
134             self.config["extra_tests"].append(nam)
135             self.config[nam]=path
136             pass
137         pass
138
139     def endElement(self, name):
140         self.space.pop()
141         self.current = None
142         pass
143
144     def characters(self, content):
145         pass
146
147     def processingInstruction(self, target, data):
148         pass
149
150     def setDocumentLocator(self, locator):
151         pass
152
153     def startDocument(self):
154         self.read = None
155         pass
156
157     def endDocument(self):
158         self.read = None
159         pass
160
161 # -----------------------------------------------------------------------------
162
163 class params:
164     pass
165
166 # -----------------------------------------------------------------------------
167
168 def makedirs(namedir):
169   if os.path.exists(namedir):
170     dirbak = namedir+".bak"
171     if os.path.exists(dirbak):
172       shutil.rmtree(dirbak)
173     os.rename(namedir, dirbak)
174     os.listdir(dirbak) #sert seulement a mettre a jour le systeme de fichier sur certaines machines
175   os.makedirs(namedir)
176
177 def install(prefix, config_file, verbose=0):
178     home_dir = os.path.abspath(os.path.expanduser(prefix))
179     filename = os.path.abspath(os.path.expanduser(config_file))
180     _config = {}
181     try:
182         parser = xml_parser(filename)
183         _config = parser.config
184     except xml.sax.SAXParseException as inst:
185         print(inst.getMessage())
186         print("Configure parser: parse error in configuration file %s" % filename)
187         pass
188     except xml.sax.SAXException as inst:
189         print(inst.args)
190         print("Configure parser: error in configuration file %s" % filename)
191         pass
192     except:
193         print("Configure parser: Error : can not read configuration file %s, check existence and rights" % filename)
194         pass
195
196     if verbose:
197         for cle,val in list(_config.items()):
198             print(cle, val)
199             pass
200
201     # Remove CTestTestfile.cmake; this file will be filled by successive calls to link_module and link_extra_test
202     try:
203       ctest_file = os.path.join(home_dir, 'bin', 'salome', 'test', "CTestTestfile.cmake")
204       os.remove(ctest_file)
205     except:
206       pass
207
208     for module in _config.get("modules", []):
209         if module in _config:
210             print("--- add module ", module, _config[module])
211             options = params()
212             options.verbose = verbose
213             options.clear = 0
214             options.prefix = home_dir
215             options.module_name = module
216             options.module_path = _config[module]
217             virtual_salome.link_module(options)
218             pass
219         pass
220
221     for extra_test in _config.get("extra_tests", []):
222         if extra_test in _config:
223             print("--- add extra test ", extra_test, _config[extra_test])
224             options = params()
225             options.verbose = verbose
226             options.clear = 0
227             options.prefix = home_dir
228             options.extra_test_name = extra_test
229             options.extra_test_path = _config[extra_test]
230             virtual_salome.link_extra_test(options)
231             pass
232         pass
233
234     # Generate CTestCustom.cmake to handle long output
235     ctest_custom = os.path.join(home_dir, 'bin', 'salome', 'test', "CTestCustom.cmake")
236     with open(ctest_custom, 'w') as f:
237       f.write("SET(CTEST_CUSTOM_MAXIMUM_PASSED_TEST_OUTPUT_SIZE 1048576) # 1MB\n")
238       f.write("SET(CTEST_CUSTOM_MAXIMUM_FAILED_TEST_OUTPUT_SIZE 1048576) # 1MB\n")
239
240     appliskel_dir = os.path.join(home_dir, 'bin', 'salome', 'appliskel')
241
242     for fn in ('envd',
243                'getAppliPath.py',
244                'kill_remote_containers.py',
245                'runRemote.sh',
246                'salome',
247                'update_catalogs.py',
248                '.bashrc',
249                ):
250         virtual_salome.symlink( os.path.join( appliskel_dir, fn ), os.path.join( home_dir, fn) )
251         pass
252
253     if filename != os.path.join(home_dir,"config_appli.xml"):
254         shutil.copyfile(filename, os.path.join(home_dir,"config_appli.xml"))
255         pass
256
257
258     # Add .salome-completion.sh file
259     shutil.copyfile(os.path.join(appliskel_dir, ".salome-completion.sh"),
260                     os.path.join(home_dir, ".salome-completion.sh"))
261
262
263     # Creation of env.d directory
264     virtual_salome.mkdir(os.path.join(home_dir,'env.d'))
265
266     if "prereq_path" in _config and os.path.isfile(_config["prereq_path"]):
267         shutil.copyfile(_config["prereq_path"],
268                         os.path.join(home_dir, 'env.d', 'envProducts.sh'))
269         pass
270     else:
271         print("WARNING: prerequisite file does not exist")
272         pass
273
274     if "context_path" in _config and os.path.isfile(_config["context_path"]):
275         shutil.copyfile(_config["context_path"],
276                         os.path.join(home_dir, 'env.d', 'envProducts.cfg'))
277         pass
278     else:
279         print("WARNING: context file does not exist")
280         pass
281
282     if "sha1_collect_path" in _config and os.path.isfile(_config["sha1_collect_path"]):
283         shutil.copyfile(_config["sha1_collect_path"],
284                         os.path.join(home_dir, 'sha1_collections.txt'))
285         pass
286     else:
287         print("WARNING: sha1 collections file does not exist")
288         pass
289
290     if "system_conf_path" in _config and os.path.isfile(_config["system_conf_path"]):
291         shutil.copyfile(_config["system_conf_path"],
292                         os.path.join(home_dir, 'env.d', 'envConfSystem.sh'))
293         pass
294
295     # Create environment file: configSalome.sh
296     with open(os.path.join(home_dir, 'env.d', 'configSalome.sh'),'w') as f:
297         for module in _config.get("modules", []):
298             command = 'export '+ module + '_ROOT_DIR=${HOME}/${APPLI}\n'
299             f.write(command)
300             pass
301         if "samples_path" in _config:
302             command = 'export DATA_DIR=' + _config["samples_path"] +'\n'
303             f.write(command)
304             pass
305         if "resources_path" in _config and os.path.isfile(_config["resources_path"]):
306             command = 'export USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
307             f.write(command)
308
309     # Create configuration file: configSalome.cfg
310     with open(os.path.join(home_dir, 'env.d', 'configSalome.cfg'),'w') as f:
311         command = "[SALOME ROOT_DIR (modules) Configuration]\n"
312         f.write(command)
313         for module in _config.get("modules", []):
314             command = module + '_ROOT_DIR=${HOME}/${APPLI}\n'
315             f.write(command)
316             pass
317         if "samples_path" in _config:
318             command = 'DATA_DIR=' + _config["samples_path"] +'\n'
319             f.write(command)
320             pass
321         if "resources_path" in _config and os.path.isfile(_config["resources_path"]):
322             command = 'USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
323             f.write(command)
324
325
326     # Create environment file: configGUI.sh
327     with open(os.path.join(home_dir, 'env.d', 'configGUI.sh'),'w') as f:
328         command = """export SalomeAppConfig=${HOME}/${APPLI}
329 export SUITRoot=${HOME}/${APPLI}/share/salome
330 export DISABLE_FPE=1
331 export MMGT_REENTRANT=1
332 """
333         f.write(command)
334
335     # Create configuration file: configGUI.cfg
336     with open(os.path.join(home_dir, 'env.d', 'configGUI.cfg'),'w') as f:
337         command = """[SALOME GUI Configuration]
338 SalomeAppConfig=${HOME}/${APPLI}
339 SUITRoot=${HOME}/${APPLI}/share/salome
340 DISABLE_FPE=1
341 MMGT_REENTRANT=1
342 """
343         f.write(command)
344
345     #SalomeApp.xml file
346     with open(os.path.join(home_dir,'SalomeApp.xml'),'w') as f:
347         command = """<document>
348   <section name="launch">
349     <!-- SALOME launching parameters -->
350     <parameter name="gui"        value="yes"/>
351     <parameter name="splash"     value="yes"/>
352     <parameter name="file"       value="no"/>
353     <parameter name="key"        value="no"/>
354     <parameter name="interp"     value="no"/>
355     <parameter name="logger"     value="no"/>
356     <parameter name="xterm"      value="no"/>
357     <parameter name="portkill"   value="no"/>
358     <parameter name="killall"    value="no"/>
359     <parameter name="noexcepthandler"  value="no"/>
360     <parameter name="modules"    value="%s"/>
361     <parameter name="pyModules"  value=""/>
362     <parameter name="embedded"   value="SalomeAppEngine,study,cppContainer,registry,moduleCatalog"/>
363     <parameter name="standalone" value=""/>
364   </section>
365 </document>
366 """
367         mods = []
368         #Keep all modules except KERNEL and GUI
369         for module in _config.get("modules", []):
370             if module in ("KERNEL","GUI"):
371                 continue
372             mods.append(module)
373         f.write(command % ",".join(mods))
374
375     #Add USERS directory with 777 permission to store users configuration files
376     users_dir = os.path.join(home_dir,'USERS')
377     makedirs(users_dir)
378     os.chmod(users_dir, 0o777)
379
380 def main():
381     parser = optparse.OptionParser(usage=usage)
382
383     parser.add_option('--prefix', dest="prefix", default='.',
384                       help="Installation directory (default .)")
385
386     parser.add_option('--config', dest="config", default='config_appli.xml',
387                       help="XML configuration file (default config_appli.xml)")
388
389     parser.add_option('-v', '--verbose', action='count', dest='verbose',
390                       default=0, help="Increase verbosity")
391
392     options, args = parser.parse_args()
393     if not os.path.exists(options.config):
394         print("ERROR: config file %s does not exist. It is mandatory." % options.config)
395         sys.exit(1)
396
397     install(prefix=options.prefix, config_file=options.config, verbose=options.verbose)
398     pass
399
400 # -----------------------------------------------------------------------------
401
402 if __name__ == '__main__':
403     main()
404     pass