]> SALOME platform Git repositories - modules/kernel.git/blob - bin/launchConfigureParser.py
Salome HOME
Print "Warning! File not found!" message rather then "Error!" if the user configurati...
[modules/kernel.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
95     if dev > 0: ver = ver - 10000 + dev
96     return ver
97
98 # get user configuration file name
99 def userFile():
100     v = version()
101     if not v:
102         return ""        # not unknown version
103     filename = "%s/.%src.%s" % (os.environ['HOME'], appname, v)
104     if os.path.exists(filename):
105         return filename  # user preferences file for the current version exists
106     # initial id
107     id0 = version_id( v )
108     # get all existing user preferences files
109     files = glob.glob( os.environ['HOME'] + "/." + appname + "rc.*" )
110     f2v = {}
111     for file in files:
112         match = re.search( r'\.%src\.([a-zA-Z0-9.]+)$'%appname, file )
113         if match: f2v[file] = match.group(1)
114     last_file = ""
115     last_version = 0
116     for file in f2v:
117         ver = version_id( f2v[file] )
118         if ver and abs(last_version-id0) > abs(ver-id0):
119             last_version = ver
120             last_file = file
121     return last_file
122
123 # -----------------------------------------------------------------------------
124
125 ### xml reader for launch configuration file usage
126
127 section_to_skip = ""
128
129 class xml_parser:
130     def __init__(self, fileName, _opts ):
131         print "Configure parser: processing %s ..." % fileName
132         self.space = []
133         self.opts = _opts
134         self.section = section_to_skip
135         parser = xml.sax.make_parser()
136         parser.setContentHandler(self)
137         parser.parse(fileName)
138         pass
139
140     def boolValue( self, str ):
141         if str in ("yes", "y", "1"):
142             return 1
143         elif str in ("no", "n", "0"):
144             return 0
145         else:
146             return str
147         pass
148
149     def startElement(self, name, attrs):
150         self.space.append(name)
151         self.current = None
152
153         # if we are analyzing "section" element and its "name" attribute is
154         # either "launch" or module name -- set section_name
155         if self.space == [doc_tag, sec_tag] and nam_att in attrs.getNames():
156             section_name = attrs.getValue( nam_att )
157             if section_name == lanch_nam:
158                 self.section = section_name # launch section
159             elif self.opts.has_key( modules_nam ) and \
160                  section_name in self.opts[ modules_nam ]:
161                 self.section = section_name # <module> section
162             else:
163                 self.section = section_to_skip # any other section
164             pass
165
166         # if we are analyzing "parameter" elements - children of either
167         # "section launch" or "section "<module>"" element, then store them
168         # in self.opts assiciative array (key = [<module>_ + ] value of "name" attribute)
169         elif self.section != section_to_skip           and \
170              self.space == [doc_tag, sec_tag, par_tag] and \
171              nam_att in attrs.getNames()               and \
172              val_att in attrs.getNames():
173             nam = attrs.getValue( nam_att )
174             val = attrs.getValue( val_att )
175             if self.section == lanch_nam: # key for launch section
176                 key = nam
177             else:                         # key for <module> section
178                 key = self.section + "_" + nam
179             if nam in boolKeys:
180                 self.opts[key] = self.boolValue( val )  # assign boolean value: 0 or 1
181             elif nam in listKeys:
182                 self.opts[key] = val.split( ',' )       # assign list value: []
183             else:
184                 self.opts[key] = val;
185             pass
186         pass
187
188     def endElement(self, name):
189         p = self.space.pop()
190         self.current = None
191         if self.section != section_to_skip and name == sec_tag:
192             self.section = section_to_skip
193         pass
194
195     def characters(self, content):
196         pass
197
198     def processingInstruction(self, target, data):
199         pass
200
201     def setDocumentLocator(self, locator):
202         pass
203
204     def startDocument(self):
205         self.read = None
206         pass
207
208     def endDocument(self):
209         self.read = None
210         pass
211
212 # -----------------------------------------------------------------------------
213
214 ### searching for launch configuration files
215 # the rule:
216 # - environment variable {'appname'+'Config'} (SalomeAppConfig) contains list of directories (';' as devider)
217 # - these directories contain 'appname'+'.xml' (SalomeApp.xml) configuration files
218 # - these files are analyzed beginning with the last one (last directory in the list)
219 # - if a key is found in next analyzed cofiguration file - it will be replaced
220 # - the last configuration file to be analyzed - ~/.'appname'+'rc' (~/SalomeApprc) (if it exists)
221 # - but anyway, if user specifies a certain option in a command line - it will replace the values
222 # - specified in configuration file(s)
223 # - once again the order of settings (next setting replaces the previous ones):
224 # -     SalomeApp.xml files in directories specified by SalomeAppConfig env variable
225 # -     .SalomeApprc file in user's catalogue
226 # -     command line
227
228 config_var = appname+'Config'
229 # set resources variables if not yet set
230 dirs = []
231 if os.getenv(config_var):
232     dirs += re.split('[;|:]', os.getenv(config_var))
233 if os.getenv("GUI_ROOT_DIR"):
234     dirs += [os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui"]
235 os.environ[config_var] = ":".join(dirs)
236
237 dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
238
239 _opts = {} # assiciative array of options to be filled
240
241 # SalomeApp.xml files in directories specified by SalomeAppConfig env variable
242 for dir in dirs:
243     filename = dir+'/'+appname+'.xml'
244     if not os.path.exists(filename):
245         print "Configure parser: Warning : could not find configuration file %s" % filename
246     else:
247         try:
248             p = xml_parser(filename, _opts)
249             _opts = p.opts
250         except:
251             print "Configure parser: Error : can not read configuration file %s" % filename
252         pass
253
254 # SalomeApprc file in user's catalogue
255 filename = userFile()
256 if not filename or not os.path.exists(filename):
257     print "Configure parser: Warning : could not find user configuration file"
258 else:
259     try:
260         p = xml_parser(filename, _opts)
261         _opts = p.opts
262     except:
263         print 'Configure parser: Error : can not read user configuration file'
264
265 args = _opts
266
267 # --- setting default values of keys if they were NOT set in config files ---
268 for aKey in listKeys:
269     if not args.has_key( aKey ):
270         args[aKey]=[]
271
272 for aKey in boolKeys:
273     if not args.has_key( aKey ):
274         args[aKey]=0
275
276 if args[file_nam]:
277     afile=args[file_nam]
278     args[file_nam]=[afile]
279
280 args[appname_nam] = appname
281
282 ### searching for my port
283
284 my_port = 2809
285 try:
286   file = open(os.environ["OMNIORB_CONFIG"], "r")
287   s = file.read()
288   while len(s):
289     l = string.split(s, ":")
290     if string.split(l[0], " ")[0] == "ORBInitRef" or string.split(l[0], " ")[0] == "InitRef" :
291       my_port = int(l[len(l)-1])
292       pass
293     s = file.read()
294     pass
295 except:
296   pass
297
298 args[port_nam] = my_port
299
300 # -----------------------------------------------------------------------------
301
302 ### command line options reader
303
304 def options_parser(line):
305   source = line
306   list = []
307   for delimiter in [" ", ",", "="]:
308     for o in source:
309       list += string.split(o, delimiter)
310       pass
311     source = list
312     list = []
313     pass
314
315   result = {}
316   i = 0
317   while i < len(source):
318     if source[i][0] != '-':
319       key = None
320     elif source[i][1] == '-':
321       key = source[i][2]
322     else:
323       key = source[i][1]
324       pass
325
326     result[key] = []
327     if key:
328       i += 1
329       pass
330     while i < len(source) and source[i][0] != '-':
331       result[key].append(source[i])
332       i += 1
333       pass
334     pass
335   return result
336
337 # -----------------------------------------------------------------------------
338
339 ### read command-line options : each arg given in command line supersedes arg from xml config file
340 cmd_opts = {}
341 try:
342     cmd_opts = options_parser(sys.argv[1:])
343     kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
344 except:
345     cmd_opts["h"] = 1
346     pass
347
348 ### check all options are right
349
350 opterror=0
351 for opt in cmd_opts:
352     if not opt in ("h","g","l","f","x","m","e","s","c","p","k","t","i","r"):
353         print "Configure parser: Error : command line error : -%s" % opt
354         opterror=1
355
356 if opterror == 1:
357     cmd_opts["h"] = 1
358
359 if cmd_opts.has_key("h"):
360     print """USAGE: runSalome.py [options]
361     [command line options] :
362     --help or -h                  : print this help
363     --gui or -g                   : launching with GUI
364     --terminal -t                 : launching without gui (to deny --gui)
365     --logger or -l                : redirect messages in a CORBA collector
366     --file=filename or -f=filename: redirect messages in a log file
367     --xterm or -x                 : execute servers in xterm console (messages appear in xterm windows)
368     --modules=module1,module2,... : salome module list (modulen is the name of Salome module to load)
369     or -m=module1,module2,...
370     --embedded=registry,study,moduleCatalog,cppContainer
371     or -e=registry,study,moduleCatalog,cppContainer
372                                   : embedded CORBA servers (default: registry,study,moduleCatalog,cppContainer)
373                                   : (logger,pyContainer,supervContainer can't be embedded
374     --standalone=registry,study,moduleCatalog,cppContainer,pyContainer,supervContainer
375     or -s=registry,study,moduleCatalog,cppContainer,pyContainer,supervContainer
376                                   : standalone CORBA servers (default: pyContainer,supervContainer)
377     --containers=cpp,python,superv: (obsolete) launching of containers cpp, python and supervision
378     or -c=cpp,python,superv       : = get default from -e and -s
379     --portkill or -p              : kill the salome with current port
380     --killall or -k               : kill all salome sessions
381     --interp=n or -i=n            : number of additional xterm to open, with session environment
382     -z                            : display splash screen
383     -r                            : disable centralized exception handling mechanism
384
385     For each Salome module, the environment variable <modulen>_ROOT_DIR must be set.
386     The module name (<modulen>) must be uppercase.
387     KERNEL_ROOT_DIR is mandatory.
388     """
389     sys.exit(1)
390     pass
391
392 ### apply command-line options to the arguments
393 for opt in cmd_opts:
394     if opt == 'g':
395         args[gui_nam] = 1
396     elif opt == 'z':
397         args[splash_nam] = 1
398     elif opt == 'r':
399         args[except_nam] = 1
400     elif opt == 'l':
401         args[logger_nam] = 1
402     elif opt == 'f':
403         args[file_nam] = cmd_opts['f']
404     elif opt == 'x':
405         args[xterm_nam] = 1
406     elif opt == 'i':
407         args[interp_nam] = cmd_opts['i']
408     elif opt == 'm':
409         args[modules_nam] = cmd_opts['m']
410     elif opt == 'e':
411         args[embedded_nam] = cmd_opts['e']
412     elif opt == 's':
413         args[standalone_nam] = cmd_opts['s']
414     elif opt == 'c':
415         args[containers_nam] = cmd_opts['c']
416     elif opt == 'p':
417         args[portkill_nam] = 1
418     elif opt == 'k':
419         args[killall_nam] = 1
420         pass
421     pass
422
423 # if --modules (-m) command line option is not given
424 # try SALOME_MODULES environment variable
425 if not cmd_opts.has_key( "m" ) and os.getenv( "SALOME_MODULES" ):
426     args[modules_nam] = re.split( "[:;,]", os.getenv( "SALOME_MODULES" ) )
427     pass
428
429 # 'terminal' must be processed in the end: to deny any 'gui' options
430 if 't' in cmd_opts:
431     args[gui_nam] = 0
432     pass
433
434 # now modify SalomeAppConfig environment variable
435 dirs = re.split('[;|:]', os.environ[config_var] )
436
437 for m in args[modules_nam]:
438     if m not in ["KERNEL", "GUI", ""] and os.getenv("%s_ROOT_DIR"%m):
439         d1 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources/" + m.lower()
440         d2 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources"
441         if os.path.exists( "%s/%s.xml"%(d1, appname) ):
442             dirs.append( d1 )
443         elif os.path.exists( "%s/%s.xml"%(d2, appname) ):
444             dirs.append( d2 )
445 os.environ[config_var] = ":".join(dirs)