]> SALOME platform Git repositories - modules/kernel.git/blob - bin/launchConfigureParser.py
Salome HOME
ENV: Windows porting.
[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+([\d\.]+)\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     except:
175         print 'Can not read launch configuration file ', filename
176         continue
177     _opts = p.opts
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 except:
184     print 'Can not read launch configuration file ', filename
185
186
187 args = p.opts
188
189 # --- setting default values of keys if they were NOT set in config files ---
190 for aKey in listKeys:
191     if not args.has_key( aKey ):
192         args[aKey]=[]
193         
194 for aKey in boolKeys:
195     if not args.has_key( aKey ):
196         args[aKey]=0
197         
198 if args[file_nam]:
199     afile=args[file_nam]
200     args[file_nam]=[afile]
201     
202 args[appname_nam] = appname
203
204 ### searching for my port
205
206 my_port = 2809
207 try:
208   file = open(os.environ["OMNIORB_CONFIG"], "r")
209   s = file.read()
210   while len(s):
211     l = string.split(s, ":")
212     if string.split(l[0], " ")[0] == "ORBInitRef" or string.split(l[0], " ")[0] == "InitRef" :
213       my_port = int(l[len(l)-1])
214       pass
215     s = file.read()
216     pass
217 except:
218   pass
219
220 args[port_nam] = my_port
221
222 # -----------------------------------------------------------------------------
223
224 ### command line options reader
225
226 def options_parser(line):
227   source = line
228   list = []
229   for delimiter in [" ", ",", "="]:
230     for o in source:
231       list += string.split(o, delimiter)
232       pass
233     source = list
234     list = []
235     pass
236
237   print "source=",source
238   
239   result = {}
240   i = 0
241   while i < len(source):
242     if source[i][0] != '-':
243       key = None
244     elif source[i][1] == '-':
245       key = source[i][2]
246     else:
247       key = source[i][1]
248       pass
249     
250     result[key] = []
251     if key:
252       i += 1
253       pass
254     while i < len(source) and source[i][0] != '-':
255       result[key].append(source[i])
256       i += 1
257       pass
258     pass
259   return result
260
261 # -----------------------------------------------------------------------------
262
263 ### read command-line options : each arg given in command line supersedes arg from xml config file
264
265 try:
266     opts = options_parser(sys.argv[1:])
267     print "opts=",opts
268     kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
269 except:
270     opts["h"] = 1
271     pass
272
273 ### check all options are right
274
275 opterror=0
276 for opt in opts:
277     if not opt in ("h","g","l","f","x","m","e","s","c","p","k","t","i"):
278         print "command line error: -", opt
279         opterror=1
280
281 if opterror == 1:
282     opts["h"] = 1
283
284 if opts.has_key("h"):
285     print """USAGE: runSalome.py [options]
286     [command line options] :
287     --help or -h                  : print this help
288     --gui or -g                   : launching with GUI
289     --terminal -t                 : launching without gui (to deny --gui)
290     --logger or -l                : redirect messages in a CORBA collector
291     --file=filename or -f=filename: redirect messages in a log file  
292     --xterm or -x                 : execute servers in xterm console (messages appear in xterm windows)
293     --modules=module1,module2,... : salome module list (modulen is the name of Salome module to load)
294     or -m=module1,module2,...
295     --embedded=registry,study,moduleCatalog,cppContainer
296     or -e=registry,study,moduleCatalog,cppContainer
297                                   : embedded CORBA servers (default: registry,study,moduleCatalog,cppContainer)
298                                   : (logger,pyContainer,supervContainer can't be embedded
299     --standalone=registry,study,moduleCatalog,cppContainer,pyContainer,supervContainer
300     or -s=registry,study,moduleCatalog,cppContainer,pyContainer,supervContainer
301                                   : standalone CORBA servers (default: pyContainer,supervContainer)
302     --containers=cpp,python,superv: (obsolete) launching of containers cpp, python and supervision
303     or -c=cpp,python,superv       : = get default from -e and -s
304     --portkill or -p              : kill the salome with current port
305     --killall or -k               : kill all salome sessions
306     --interp=n or -i=n            : number of additional xterm to open, with session environment
307     -z                            : display splash screen
308     
309     For each Salome module, the environment variable <modulen>_ROOT_DIR must be set.
310     The module name (<modulen>) must be uppercase.
311     KERNEL_ROOT_DIR is mandatory.
312     """
313     sys.exit(1)
314     pass
315
316 ### apply command-line options to the arguments
317 for opt in opts:
318     if opt == 'g':
319         args[gui_nam] = 1
320     elif opt == 'z':
321         args[splash_nam] = 1
322     elif opt == 'l':
323         args[logger_nam] = 1
324     elif opt == 'f':
325         args[file_nam] = opts['f']
326     elif opt == 'x':
327         args[xterm_nam] = 1
328     elif opt == 'i':
329         args[interp_nam] = opts['i']
330     elif opt == 'm':
331         args[modules_nam] = opts['m']
332     elif opt == 'e':
333         args[embedded_nam] = opts['e']
334     elif opt == 's':
335         args[standalone_nam] = opts['s']
336     elif opt == 'c':
337         args[containers_nam] = opts['c']
338     elif opt == 'p':
339         args[portkill_nam] = 1
340     elif opt == 'k':
341         args[killall_nam] = 1
342         pass
343     pass
344
345 # 'terminal' must be processed in the end: to deny any 'gui' options
346 if 't' in opts:
347     args[gui_nam] = 0
348     pass
349
350 print "args=",args