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