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