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