Salome HOME
Join modifications from branch BR_DEBUG_3_2_0b1
[modules/yacs.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 ver and 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 dirs = re.split('[;|:]', dirs )
243 dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
244
245 _opts = {} # assiciative array of options to be filled
246
247 # SalomeApp.xml files in directories specified by SalomeAppConfig env variable
248 for dir in dirs:
249     filename = dir+'/'+appname+'.xml'
250     if not os.path.exists(filename):
251         print "Configure parser: Warning : could not find configuration file %s" % filename
252     else:
253         try:
254             p = xml_parser(filename, _opts)
255             _opts = p.opts
256         except:
257             print "Configure parser: Error : can not read configuration file %s" % filename
258         pass
259
260 # SalomeApprc file in user's catalogue
261 filename = userFile()
262 if filename and not os.path.exists(filename):
263     print "Configure parser: Warning : could not find user configuration file"
264 else:
265     try:
266         p = xml_parser(filename, _opts)
267         _opts = p.opts
268     except:
269         print 'Configure parser: Error : can not read user configuration file'
270
271 args = _opts
272
273 # --- setting default values of keys if they were NOT set in config files ---
274 for aKey in listKeys:
275     if not args.has_key( aKey ):
276         args[aKey]=[]
277         
278 for aKey in boolKeys:
279     if not args.has_key( aKey ):
280         args[aKey]=0
281         
282 if args[file_nam]:
283     afile=args[file_nam]
284     args[file_nam]=[afile]
285     
286 args[appname_nam] = appname
287
288 ### searching for my port
289
290 my_port = 2809
291 try:
292   file = open(os.environ["OMNIORB_CONFIG"], "r")
293   s = file.read()
294   while len(s):
295     l = string.split(s, ":")
296     if string.split(l[0], " ")[0] == "ORBInitRef" or string.split(l[0], " ")[0] == "InitRef" :
297       my_port = int(l[len(l)-1])
298       pass
299     s = file.read()
300     pass
301 except:
302   pass
303
304 args[port_nam] = my_port
305
306 # -----------------------------------------------------------------------------
307
308 ### command line options reader
309
310 def options_parser(line):
311   source = line
312   list = []
313   for delimiter in [" ", ",", "="]:
314     for o in source:
315       list += string.split(o, delimiter)
316       pass
317     source = list
318     list = []
319     pass
320
321   result = {}
322   i = 0
323   while i < len(source):
324     if source[i][0] != '-':
325       key = None
326     elif source[i][1] == '-':
327       key = source[i][2]
328     else:
329       key = source[i][1]
330       pass
331     
332     result[key] = []
333     if key:
334       i += 1
335       pass
336     while i < len(source) and source[i][0] != '-':
337       result[key].append(source[i])
338       i += 1
339       pass
340     pass
341   return result
342
343 # -----------------------------------------------------------------------------
344
345 ### read command-line options : each arg given in command line supersedes arg from xml config file
346 cmd_opts = {}
347 try:
348     cmd_opts = options_parser(sys.argv[1:])
349     kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
350 except:
351     cmd_opts["h"] = 1
352     pass
353
354 ### check all options are right
355
356 opterror=0
357 for opt in cmd_opts:
358     if not opt in ("h","g","l","f","x","m","e","s","c","p","k","t","i","r"):
359         print "Configure parser: Error : command line error : -%s" % opt
360         opterror=1
361
362 if opterror == 1:
363     cmd_opts["h"] = 1
364
365 if cmd_opts.has_key("h"):
366     print """USAGE: runSalome.py [options]
367     [command line options] :
368     --help or -h                  : print this help
369     --gui or -g                   : launching with GUI
370     --terminal -t                 : launching without gui (to deny --gui)
371     --logger or -l                : redirect messages in a CORBA collector
372     --file=filename or -f=filename: redirect messages in a log file  
373     --xterm or -x                 : execute servers in xterm console (messages appear in xterm windows)
374     --modules=module1,module2,... : salome module list (modulen is the name of Salome module to load)
375     or -m=module1,module2,...
376     --embedded=registry,study,moduleCatalog,cppContainer
377     or -e=registry,study,moduleCatalog,cppContainer
378                                   : embedded CORBA servers (default: registry,study,moduleCatalog,cppContainer)
379                                   : (logger,pyContainer,supervContainer can't be embedded
380     --standalone=registry,study,moduleCatalog,cppContainer,pyContainer,supervContainer
381     or -s=registry,study,moduleCatalog,cppContainer,pyContainer,supervContainer
382                                   : standalone CORBA servers (default: pyContainer,supervContainer)
383     --containers=cpp,python,superv: (obsolete) launching of containers cpp, python and supervision
384     or -c=cpp,python,superv       : = get default from -e and -s
385     --portkill or -p              : kill the salome with current port
386     --killall or -k               : kill all salome sessions
387     --interp=n or -i=n            : number of additional xterm to open, with session environment
388     -z                            : display splash screen
389     -r                            : disable centralized exception handling mechanism
390     
391     For each Salome module, the environment variable <modulen>_ROOT_DIR must be set.
392     The module name (<modulen>) must be uppercase.
393     KERNEL_ROOT_DIR is mandatory.
394     """
395     sys.exit(1)
396     pass
397
398 ### apply command-line options to the arguments
399 for opt in cmd_opts:
400     if opt == 'g':
401         args[gui_nam] = 1
402     elif opt == 'z':
403         args[splash_nam] = 1
404     elif opt == 'r':
405         args[except_nam] = 1
406     elif opt == 'l':
407         args[logger_nam] = 1
408     elif opt == 'f':
409         args[file_nam] = cmd_opts['f']
410     elif opt == 'x':
411         args[xterm_nam] = 1
412     elif opt == 'i':
413         args[interp_nam] = cmd_opts['i']
414     elif opt == 'm':
415         args[modules_nam] = cmd_opts['m']
416     elif opt == 'e':
417         args[embedded_nam] = cmd_opts['e']
418     elif opt == 's':
419         args[standalone_nam] = cmd_opts['s']
420     elif opt == 'c':
421         args[containers_nam] = cmd_opts['c']
422     elif opt == 'p':
423         args[portkill_nam] = 1
424     elif opt == 'k':
425         args[killall_nam] = 1
426         pass
427     pass
428
429 # if --modules (-m) command line option is not given
430 # try SALOME_MODULES environment variable
431 if not cmd_opts.has_key( "m" ) and os.getenv( "SALOME_MODULES" ):
432     args[modules_nam] = re.split( "[:;,]", os.getenv( "SALOME_MODULES" ) )
433     pass
434
435 # 'terminal' must be processed in the end: to deny any 'gui' options
436 if 't' in cmd_opts:
437     args[gui_nam] = 0
438     pass
439
440 # now modify SalomeAppConfig environment variable
441 dirs = re.split('[;|:]', os.environ[config_var] )
442 for m in args[modules_nam]:
443     if m not in ["KERNEL", "GUI", ""] and os.getenv("%s_ROOT_DIR"%m):
444         dirs.append( os.getenv("%s_ROOT_DIR"%m) +  "/share/salome/resources" )
445 os.environ[config_var] = ":".join(dirs)