Salome HOME
PAL6948 (Persistence in MED). Add "typedef H5T_order_t hdf_byte_order;"
[modules/kernel.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 pyModules_nam  = "pyModules"
24 embedded_nam   = "embedded"
25 standalone_nam = "standalone"
26 containers_nam = "containers"
27 key_nam        = "key"
28 interp_nam     = "interp"
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 )
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 # -----------------------------------------------------------------------------
58
59 ### xml reader for launch configuration file usage
60
61 section_to_skip = ""
62
63 class xml_parser:
64     def __init__(self, fileName, _opts ):
65         print "Processing ",fileName 
66         self.space = []
67         self.opts = _opts
68         self.section = section_to_skip
69         parser = xml.sax.make_parser()
70         parser.setContentHandler(self)
71         parser.parse(fileName)
72         pass
73
74     def boolValue( self, str ):
75         if str in ("yes", "y", "1"):
76             return 1
77         elif str in ("no", "n", "0"):
78             return 0
79         else:
80             return str
81         pass
82
83     def startElement(self, name, attrs):
84         self.space.append(name)
85         self.current = None
86
87         # if we are analyzing "section" element and its "name" attribute is
88         # either "launch" or module name -- set section_name
89         if self.space == [doc_tag, sec_tag] and nam_att in attrs.getNames():
90             section_name = attrs.getValue( nam_att )
91             if section_name == lanch_nam:
92                 self.section = section_name # launch section
93             elif self.opts.has_key( modules_nam ) and \
94                  section_name in self.opts[ modules_nam ]:
95                 self.section = section_name # <module> section
96             else:
97                 self.section = section_to_skip # any other section
98             pass
99
100         # if we are analyzing "parameter" elements - children of either
101         # "section launch" or "section "<module>"" element, then store them
102         # in self.opts assiciative array (key = [<module>_ + ] value of "name" attribute)
103         elif self.section != section_to_skip           and \
104              self.space == [doc_tag, sec_tag, par_tag] and \
105              nam_att in attrs.getNames()               and \
106              val_att in attrs.getNames():
107             nam = attrs.getValue( nam_att )
108             val = attrs.getValue( val_att )
109             if self.section == lanch_nam: # key for launch section
110                 key = nam
111             else:                         # key for <module> section
112                 key = self.section + "_" + nam
113             if nam in boolKeys:
114                 self.opts[key] = self.boolValue( val )  # assign boolean value: 0 or 1
115             elif nam in listKeys:
116                 self.opts[key] = val.split( ',' )       # assign list value: []
117             else:
118                 self.opts[key] = val;
119             pass
120         pass
121
122     def endElement(self, name):
123         p = self.space.pop()
124         self.current = None
125         if self.section != section_to_skip and name == sec_tag:
126             self.section = section_to_skip
127         pass
128
129     def characters(self, content):
130         pass
131
132     def processingInstruction(self, target, data):
133         pass
134
135     def setDocumentLocator(self, locator):
136         pass
137
138     def startDocument(self):
139         self.read = None
140         pass
141
142     def endDocument(self):
143         self.read = None
144         pass
145
146 # -----------------------------------------------------------------------------
147
148 ### searching for launch configuration files
149 # the rule:
150 # - environment variable {'appname'+'Config'} (SalomeAppConfig) contains list of directories (';' as devider)
151 # - these directories contain 'appname'+'.xml' (SalomeApp.xml) configuration files
152 # - these files are analyzed beginning with the last one (last directory in the list)
153 # - if a key is found in next analyzed cofiguration file - it will be replaced
154 # - the last configuration file to be analyzed - ~/.'appname'+'rc' (~/SalomeApprc) (if it exists)
155 # - but anyway, if user specifies a certain option in a command line - it will replace the values
156 # - specified in configuration file(s)
157 # - once again the order of settings (next setting replaces the previous ones):
158 # -     SalomeApp.xml files in directories specified by SalomeAppConfig env variable
159 # -     .SalomeApprc file in user's catalogue
160 # -     command line
161
162 config_var = appname+'Config'
163 dirs = os.environ[config_var]
164 dirs = dirs.split( ';' )
165 dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
166
167 _opts = {} # assiciative array of options to be filled
168
169 # SalomeApp.xml files in directories specified by SalomeAppConfig env variable
170 for dir in dirs:
171     filename = dir+'/'+appname+'.xml'
172     try:
173         p = xml_parser(filename, _opts)
174         _opts = p.opts
175     except:
176         print 'Can not read launch configuration file ', filename
177         continue
178
179 # SalomeApprc file in user's catalogue
180 filename = os.environ['HOME']+'/.'+appname+'rc.'+version()
181 try:
182     p = xml_parser(filename, _opts)
183     _opts = p.opts
184 except:
185     print 'Can not read launch configuration file ', filename
186
187
188 args = _opts
189
190 # --- setting default values of keys if they were NOT set in config files ---
191 for aKey in listKeys:
192     if not args.has_key( aKey ):
193         args[aKey]=[]
194         
195 for aKey in boolKeys:
196     if not args.has_key( aKey ):
197         args[aKey]=0
198         
199 if args[file_nam]:
200     afile=args[file_nam]
201     args[file_nam]=[afile]
202     
203 args[appname_nam] = appname
204
205 ### searching for my port
206
207 my_port = 2809
208 try:
209   file = open(os.environ["OMNIORB_CONFIG"], "r")
210   s = file.read()
211   while len(s):
212     l = string.split(s, ":")
213     if string.split(l[0], " ")[0] == "ORBInitRef" or string.split(l[0], " ")[0] == "InitRef" :
214       my_port = int(l[len(l)-1])
215       pass
216     s = file.read()
217     pass
218 except:
219   pass
220
221 args[port_nam] = my_port
222
223 # -----------------------------------------------------------------------------
224
225 ### command line options reader
226
227 def options_parser(line):
228   source = line
229   list = []
230   for delimiter in [" ", ",", "="]:
231     for o in source:
232       list += string.split(o, delimiter)
233       pass
234     source = list
235     list = []
236     pass
237
238   #print "source=",source
239   
240   result = {}
241   i = 0
242   while i < len(source):
243     if source[i][0] != '-':
244       key = None
245     elif source[i][1] == '-':
246       key = source[i][2]
247     else:
248       key = source[i][1]
249       pass
250     
251     result[key] = []
252     if key:
253       i += 1
254       pass
255     while i < len(source) and source[i][0] != '-':
256       result[key].append(source[i])
257       i += 1
258       pass
259     pass
260   return result
261
262 # -----------------------------------------------------------------------------
263
264 ### read command-line options : each arg given in command line supersedes arg from xml config file
265 cmd_opts = {}
266 try:
267     cmd_opts = options_parser(sys.argv[1:])
268     #print "opts=",cmd_opts
269     kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
270 except:
271     cmd_opts["h"] = 1
272     pass
273
274 ### check all options are right
275
276 opterror=0
277 for opt in cmd_opts:
278     if not opt in ("h","g","l","f","x","m","e","s","c","p","k","t","i"):
279         print "command line error: -", opt
280         opterror=1
281
282 if opterror == 1:
283     cmd_opts["h"] = 1
284
285 if cmd_opts.has_key("h"):
286     print """USAGE: runSalome.py [options]
287     [command line options] :
288     --help or -h                  : print this help
289     --gui or -g                   : launching with GUI
290     --terminal -t                 : launching without gui (to deny --gui)
291     --logger or -l                : redirect messages in a CORBA collector
292     --file=filename or -f=filename: redirect messages in a log file  
293     --xterm or -x                 : execute servers in xterm console (messages appear in xterm windows)
294     --modules=module1,module2,... : salome module list (modulen is the name of Salome module to load)
295     or -m=module1,module2,...
296     --embedded=registry,study,moduleCatalog,cppContainer
297     or -e=registry,study,moduleCatalog,cppContainer
298                                   : embedded CORBA servers (default: registry,study,moduleCatalog,cppContainer)
299                                   : (logger,pyContainer,supervContainer can't be embedded
300     --standalone=registry,study,moduleCatalog,cppContainer,pyContainer,supervContainer
301     or -s=registry,study,moduleCatalog,cppContainer,pyContainer,supervContainer
302                                   : standalone CORBA servers (default: pyContainer,supervContainer)
303     --containers=cpp,python,superv: (obsolete) launching of containers cpp, python and supervision
304     or -c=cpp,python,superv       : = get default from -e and -s
305     --portkill or -p              : kill the salome with current port
306     --killall or -k               : kill all salome sessions
307     --interp=n or -i=n            : number of additional xterm to open, with session environment
308     -z                            : display splash screen
309     
310     For each Salome module, the environment variable <modulen>_ROOT_DIR must be set.
311     The module name (<modulen>) must be uppercase.
312     KERNEL_ROOT_DIR is mandatory.
313     """
314     sys.exit(1)
315     pass
316
317 ### apply command-line options to the arguments
318 for opt in cmd_opts:
319     if opt == 'g':
320         args[gui_nam] = 1
321     elif opt == 'z':
322         args[splash_nam] = 1
323     elif opt == 'l':
324         args[logger_nam] = 1
325     elif opt == 'f':
326         args[file_nam] = cmd_opts['f']
327     elif opt == 'x':
328         args[xterm_nam] = 1
329     elif opt == 'i':
330         args[interp_nam] = cmd_opts['i']
331     elif opt == 'm':
332         args[modules_nam] = cmd_opts['m']
333     elif opt == 'e':
334         args[embedded_nam] = cmd_opts['e']
335     elif opt == 's':
336         args[standalone_nam] = cmd_opts['s']
337     elif opt == 'c':
338         args[containers_nam] = cmd_opts['c']
339     elif opt == 'p':
340         args[portkill_nam] = 1
341     elif opt == 'k':
342         args[killall_nam] = 1
343         pass
344     pass
345
346 # 'terminal' must be processed in the end: to deny any 'gui' options
347 if 't' in cmd_opts:
348     args[gui_nam] = 0
349     pass
350
351 #print "args=",args