]> SALOME platform Git repositories - modules/kernel.git/blob - bin/launchConfigureParser.py
Salome HOME
b172e06f12c0b805b0682384060618a120db7e80
[modules/kernel.git] / bin / launchConfigureParser.py
1 # Copyright (C) 2005  OPEN CASCADE, CEA, EDF R&D, LEG
2 #           PRINCIPIA R&D, EADS CCR, Lip6, BV, CEDRAT
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either 
6 # version 2.1 of the License.
7
8 # This library is distributed in the hope that it will be useful 
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of 
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
11 # Lesser General Public License for more details.
12
13 # You should have received a copy of the GNU Lesser General Public  
14 # License along with this library; if not, write to the Free Software 
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18
19 import os, glob, string, sys, re
20 import xml.sax
21
22 # names of tags in XML configuration file 
23 doc_tag = "document"
24 sec_tag = "section"
25 par_tag = "parameter"
26
27 # names of attributes in XML configuration file 
28 nam_att = "name"
29 val_att = "value"
30
31 # certain values in XML configuration file ("launch" section)
32 lanch_nam      = "launch"
33 gui_nam        = "gui"
34 splash_nam     = "splash"
35 logger_nam     = "logger"
36 xterm_nam      = "xterm"
37 file_nam       = "file"
38 portkill_nam   = "portkill"
39 killall_nam    = "killall"
40 modules_nam    = "modules"
41 embedded_nam   = "embedded"
42 standalone_nam = "standalone"
43 containers_nam = "containers"
44 key_nam        = "key"
45 interp_nam     = "interp"
46 except_nam     = "noexcepthandler"
47
48 # values in XML configuration file giving specific module parameters (<module_name> section)
49 # which are stored in opts with key <module_name>_<parameter> (eg SMESH_plugins)
50 plugins_nam    = "plugins"
51
52 # values passed as arguments, NOT read from XML config file, but set from within this script
53 appname_nam    = "appname"
54 port_nam       = "port"
55 appname        = "SalomeApp"
56
57 # values of boolean type (must be '0' or '1').
58 # xml_parser.boolValue() is used for correct setting
59 boolKeys = ( gui_nam, splash_nam, logger_nam, file_nam, xterm_nam, portkill_nam, killall_nam, interp_nam, except_nam )
60
61 # values of list type
62 listKeys = ( containers_nam, embedded_nam, key_nam, modules_nam, standalone_nam, plugins_nam )
63
64 # return application version (uses GUI_ROOT_DIR (or KERNEL_ROOT_DIR in batch mode) +/bin/salome/VERSION)
65 def version():
66     root_dir = os.environ.get( 'KERNEL_ROOT_DIR', '' )     # KERNEL_ROOT_DIR or "" if not found
67     root_dir = os.environ.get( 'GUI_ROOT_DIR', root_dir )  # GUI_ROOT_DIR or KERNEL_ROOT_DIR or "" if both not found
68     filename = root_dir+'/bin/salome/VERSION'
69     str = open( filename, "r" ).readline() # str = "THIS IS SALOME - SALOMEGUI VERSION: 3.0.0"
70     match = re.search( r':\s+([a-zA-Z0-9.]+)\s*$', str )
71     if match :
72         return match.group( 1 )
73     return ''
74
75 # calculate and return configuration file id in order to unically identify it
76 # for example: for 3.1.0a1 the id is 301000101
77 def version_id( fname ):
78     vers = fname.split(".")
79     major   = int(vers[0])
80     minor   = int(vers[1])
81     mr = re.search(r'^([0-9]+)([A-Za-z]?)([0-9]*)',vers[2])
82     release = dev = 0
83     if mr:
84         release = int(mr.group(1))
85         dev1 = dev2 = 0
86         if len(mr.group(2)): dev1 = ord(mr.group(2))
87         if len(mr.group(3)): dev2 = int(mr.group(3))
88         dev = dev1 * 100 + dev2
89     else:
90         return None
91     ver = major
92     ver = ver * 100 + minor
93     ver = ver * 100 + release
94     ver = ver * 10000 + dev
95     return ver
96
97 # get user configuration file name
98 def userFile():
99     v = version()
100     if not v:
101         return ""        # not unknown version
102     filename = "%s/.%src.%s" % (os.environ['HOME'], appname, v)
103     if os.path.exists(filename):
104         return filename  # user preferences file for the current version exists
105     # initial id
106     id0 = version_id( v )
107     # get all existing user preferences files
108     files = glob.glob( os.environ['HOME'] + "/." + appname + "rc.*" )
109     f2v = {}
110     for file in files:
111         match = re.search( r'\.%src\.([a-zA-Z0-9.]+)$'%appname, file )
112         if match: f2v[file] = match.group(1)
113     last_file = ""
114     last_version = 0
115     for file in f2v:
116         ver = version_id( f2v[file] )
117         if abs(last_version-id0) > abs(ver-id0):
118             last_version = ver
119             last_file = file
120     return last_file
121         
122 # -----------------------------------------------------------------------------
123
124 ### xml reader for launch configuration file usage
125
126 section_to_skip = ""
127
128 class xml_parser:
129     def __init__(self, fileName, _opts ):
130         print "Configure parser: processing %s ..." % fileName 
131         self.space = []
132         self.opts = _opts
133         self.section = section_to_skip
134         parser = xml.sax.make_parser()
135         parser.setContentHandler(self)
136         parser.parse(fileName)
137         pass
138
139     def boolValue( self, str ):
140         if str in ("yes", "y", "1"):
141             return 1
142         elif str in ("no", "n", "0"):
143             return 0
144         else:
145             return str
146         pass
147
148     def startElement(self, name, attrs):
149         self.space.append(name)
150         self.current = None
151
152         # if we are analyzing "section" element and its "name" attribute is
153         # either "launch" or module name -- set section_name
154         if self.space == [doc_tag, sec_tag] and nam_att in attrs.getNames():
155             section_name = attrs.getValue( nam_att )
156             if section_name == lanch_nam:
157                 self.section = section_name # launch section
158             elif self.opts.has_key( modules_nam ) and \
159                  section_name in self.opts[ modules_nam ]:
160                 self.section = section_name # <module> section
161             else:
162                 self.section = section_to_skip # any other section
163             pass
164
165         # if we are analyzing "parameter" elements - children of either
166         # "section launch" or "section "<module>"" element, then store them
167         # in self.opts assiciative array (key = [<module>_ + ] value of "name" attribute)
168         elif self.section != section_to_skip           and \
169              self.space == [doc_tag, sec_tag, par_tag] and \
170              nam_att in attrs.getNames()               and \
171              val_att in attrs.getNames():
172             nam = attrs.getValue( nam_att )
173             val = attrs.getValue( val_att )
174             if self.section == lanch_nam: # key for launch section
175                 key = nam
176             else:                         # key for <module> section
177                 key = self.section + "_" + nam
178             if nam in boolKeys:
179                 self.opts[key] = self.boolValue( val )  # assign boolean value: 0 or 1
180             elif nam in listKeys:
181                 self.opts[key] = val.split( ',' )       # assign list value: []
182             else:
183                 self.opts[key] = val;
184             pass
185         pass
186
187     def endElement(self, name):
188         p = self.space.pop()
189         self.current = None
190         if self.section != section_to_skip and name == sec_tag:
191             self.section = section_to_skip
192         pass
193
194     def characters(self, content):
195         pass
196
197     def processingInstruction(self, target, data):
198         pass
199
200     def setDocumentLocator(self, locator):
201         pass
202
203     def startDocument(self):
204         self.read = None
205         pass
206
207     def endDocument(self):
208         self.read = None
209         pass
210
211 # -----------------------------------------------------------------------------
212
213 ### searching for launch configuration files
214 # the rule:
215 # - environment variable {'appname'+'Config'} (SalomeAppConfig) contains list of directories (';' as devider)
216 # - these directories contain 'appname'+'.xml' (SalomeApp.xml) configuration files
217 # - these files are analyzed beginning with the last one (last directory in the list)
218 # - if a key is found in next analyzed cofiguration file - it will be replaced
219 # - the last configuration file to be analyzed - ~/.'appname'+'rc' (~/SalomeApprc) (if it exists)
220 # - but anyway, if user specifies a certain option in a command line - it will replace the values
221 # - specified in configuration file(s)
222 # - once again the order of settings (next setting replaces the previous ones):
223 # -     SalomeApp.xml files in directories specified by SalomeAppConfig env variable
224 # -     .SalomeApprc file in user's catalogue
225 # -     command line
226
227 config_var = appname+'Config'
228 # set resources variables if not yet set
229 if os.getenv("GUI_ROOT_DIR"):
230     if not os.getenv("SUITRoot"):
231         os.environ["SUITRoot"] = os.getenv("GUI_ROOT_DIR") + "/share/salome"
232     if not os.getenv(config_var):
233         os.environ[config_var] = os.getenv("GUI_ROOT_DIR") + "/share/salome/resources"
234     pass
235 else :
236     if not os.getenv("SUITRoot"):
237         os.environ["SUITRoot"] = ""
238     if not os.getenv(config_var):
239         os.environ[config_var] = ""
240
241 dirs = os.environ[config_var]
242 #abd error om win32 path like W:\dir\di1
243 #print 'Search configuration file in dir ', dirs
244 if os.sys.platform == 'win32':
245     dirs = re.split('[;]', dirs )
246 else:
247     dirs = re.split('[;|:]', dirs )
248 dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
249
250 _opts = {} # assiciative array of options to be filled
251
252 # SalomeApp.xml files in directories specified by SalomeAppConfig env variable
253 for dir in dirs:
254     filename = dir+'/'+appname+'.xml'
255     if not os.path.exists(filename):
256         print "Configure parser: Warning : could not find configuration file %s" % filename
257     else:
258         try:
259             p = xml_parser(filename, _opts)
260             _opts = p.opts
261         except:
262             print "Configure parser: Error : can not read configuration file %s" % filename
263         pass
264
265 # SalomeApprc file in user's catalogue
266 filename = userFile()
267 if filename and not os.path.exists(filename):
268     print "Configure parser: Warning : could not find user configuration file"
269 else:
270     try:
271         p = xml_parser(filename, _opts)
272         _opts = p.opts
273     except:
274         print 'Configure parser: Error : can not read user configuration file'
275
276 args = _opts
277
278 # --- setting default values of keys if they were NOT set in config files ---
279 for aKey in listKeys:
280     if not args.has_key( aKey ):
281         args[aKey]=[]
282         
283 for aKey in boolKeys:
284     if not args.has_key( aKey ):
285         args[aKey]=0
286         
287 if args[file_nam]:
288     afile=args[file_nam]
289     args[file_nam]=[afile]
290     
291 args[appname_nam] = appname
292
293 ### searching for my port
294
295 my_port = 2809
296 try:
297   file = open(os.environ["OMNIORB_CONFIG"], "r")
298   s = file.read()
299   while len(s):
300     l = string.split(s, ":")
301     if string.split(l[0], " ")[0] == "ORBInitRef" or string.split(l[0], " ")[0] == "InitRef" :
302       my_port = int(l[len(l)-1])
303       pass
304     s = file.read()
305     pass
306 except:
307   pass
308
309 args[port_nam] = my_port
310
311 # -----------------------------------------------------------------------------
312
313 ### command line options reader
314
315 def options_parser(line):
316   source = line
317   list = []
318   for delimiter in [" ", ",", "="]:
319     for o in source:
320       list += string.split(o, delimiter)
321       pass
322     source = list
323     list = []
324     pass
325
326   result = {}
327   i = 0
328   while i < len(source):
329     if source[i][0] != '-':
330       key = None
331     elif source[i][1] == '-':
332       key = source[i][2]
333     else:
334       key = source[i][1]
335       pass
336     
337     result[key] = []
338     if key:
339       i += 1
340       pass
341     while i < len(source) and source[i][0] != '-':
342       result[key].append(source[i])
343       i += 1
344       pass
345     pass
346   return result
347
348 # -----------------------------------------------------------------------------
349
350 ### read command-line options : each arg given in command line supersedes arg from xml config file
351 cmd_opts = {}
352 try:
353     cmd_opts = options_parser(sys.argv[1:])
354     kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
355 except:
356     cmd_opts["h"] = 1
357     pass
358
359 ### check all options are right
360
361 opterror=0
362 for opt in cmd_opts:
363     if not opt in ("h","g","l","f","x","m","e","s","c","p","k","t","i","r"):
364         print "Configure parser: Error : command line error : -%s" % opt
365         opterror=1
366
367 if opterror == 1:
368     cmd_opts["h"] = 1
369
370 if cmd_opts.has_key("h"):
371     print """USAGE: runSalome.py [options]
372     [command line options] :
373     --help or -h                  : print this help
374     --gui or -g                   : launching with GUI
375     --terminal -t                 : launching without gui (to deny --gui)
376     --logger or -l                : redirect messages in a CORBA collector
377     --file=filename or -f=filename: redirect messages in a log file  
378     --xterm or -x                 : execute servers in xterm console (messages appear in xterm windows)
379     --modules=module1,module2,... : salome module list (modulen is the name of Salome module to load)
380     or -m=module1,module2,...
381     --embedded=registry,study,moduleCatalog,cppContainer
382     or -e=registry,study,moduleCatalog,cppContainer
383                                   : embedded CORBA servers (default: registry,study,moduleCatalog,cppContainer)
384                                   : (logger,pyContainer,supervContainer can't be embedded
385     --standalone=registry,study,moduleCatalog,cppContainer,pyContainer,supervContainer
386     or -s=registry,study,moduleCatalog,cppContainer,pyContainer,supervContainer
387                                   : standalone CORBA servers (default: pyContainer,supervContainer)
388     --containers=cpp,python,superv: (obsolete) launching of containers cpp, python and supervision
389     or -c=cpp,python,superv       : = get default from -e and -s
390     --portkill or -p              : kill the salome with current port
391     --killall or -k               : kill all salome sessions
392     --interp=n or -i=n            : number of additional xterm to open, with session environment
393     -z                            : display splash screen
394     -r                            : disable centralized exception handling mechanism
395     
396     For each Salome module, the environment variable <modulen>_ROOT_DIR must be set.
397     The module name (<modulen>) must be uppercase.
398     KERNEL_ROOT_DIR is mandatory.
399     """
400     sys.exit(1)
401     pass
402
403 ### apply command-line options to the arguments
404 for opt in cmd_opts:
405     if opt == 'g':
406         args[gui_nam] = 1
407     elif opt == 'z':
408         args[splash_nam] = 1
409     elif opt == 'r':
410         args[except_nam] = 1
411     elif opt == 'l':
412         args[logger_nam] = 1
413     elif opt == 'f':
414         args[file_nam] = cmd_opts['f']
415     elif opt == 'x':
416         args[xterm_nam] = 1
417     elif opt == 'i':
418         args[interp_nam] = cmd_opts['i']
419     elif opt == 'm':
420         args[modules_nam] = cmd_opts['m']
421     elif opt == 'e':
422         args[embedded_nam] = cmd_opts['e']
423     elif opt == 's':
424         args[standalone_nam] = cmd_opts['s']
425     elif opt == 'c':
426         args[containers_nam] = cmd_opts['c']
427     elif opt == 'p':
428         args[portkill_nam] = 1
429     elif opt == 'k':
430         args[killall_nam] = 1
431         pass
432     pass
433
434 # if --modules (-m) command line option is not given
435 # try SALOME_MODULES environment variable
436 if not cmd_opts.has_key( "m" ) and os.getenv( "SALOME_MODULES" ):
437     args[modules_nam] = re.split( "[:;,]", os.getenv( "SALOME_MODULES" ) )
438     pass
439
440 # 'terminal' must be processed in the end: to deny any 'gui' options
441 if 't' in cmd_opts:
442     args[gui_nam] = 0
443     pass
444
445 # now modify SalomeAppConfig environment variable
446 if os.sys.platform == 'win32':
447     dirs = re.split('[;]', os.environ[config_var] )
448 else:
449     dirs = re.split('[;|:]', os.environ[config_var] )
450 for m in args[modules_nam]:
451     if m not in ["KERNEL", "GUI", ""] and os.getenv("%s_ROOT_DIR"%m):
452         dirs.append( os.getenv("%s_ROOT_DIR"%m) +  "/share/salome/resources" )
453 if os.sys.platform == 'win32':
454   os.environ[config_var] = ";".join(dirs)
455 else:
456   os.environ[config_var] = ":".join(dirs)