Salome HOME
To print user friendly message at Python modules import error.
[tools/install.git] / runInstall
1 #!/usr/bin/env python
2
3 """
4 Installation Wizard launching script.
5
6 This script is the part of the SALOME installation procedure.
7 Author    : Vadim SANDLER, Open CASCADE SAS (vadim.sandler@opencascade.com)
8 Created   : Thu Dec 18 12:01:00 2002
9 Copyright : 2002-2008 CEA
10
11 """
12
13 __version__ = "1.1.5"
14
15 # --- imports --- #
16 import sys
17 try:
18     import xml.sax, xml.dom.minidom
19     import os, re
20     import types
21     import random
22     import warnings
23 except Exception, an_exc:
24     sys.exit("Error: %s! Please check the installed Python package." % str(an_exc))
25     pass
26
27 # --- avoid "deprecation" warnings --- #
28 warnings.filterwarnings("ignore", "", DeprecationWarning)
29
30 # --- global variables --- #
31 opt_parser = None
32 root_path  = None
33
34 # --- actions definition --- #
35 __BINARIES__   = "install_binary"
36 __BUILDSRC__   = "install_source_and_build"
37 __PREINSTALL__ = "try_preinstalled"
38
39 # --- product type definition --- #
40 __CTX__COMPONENT__    = "component"
41 __CTX__PREREQUISITE__ = "prerequisite"
42
43 #------------------------------------------------------------------#
44 #                                                                  #
45 #                 COMMAND LINE ARGUMENTS PARSER                    #
46 #                                                                  #
47 #------------------------------------------------------------------#
48
49 #===================================================================
50 # class OptBaseError : base parse error
51 #===================================================================
52 class OptBaseError(Exception):
53     """
54     Base option parsing exception class
55     """
56     def __init__(self, msg):
57         self.msg = msg
58     def __str__ (self):
59         return self.msg
60
61 #===================================================================
62 # class OptError : bad option error
63 #===================================================================
64 class OptError(OptBaseError):
65     """
66     Bad option exception class
67     """
68     def __init__ (self, msg, option):
69         self.msg = msg
70         self.option = option
71     def __str__ (self):
72         if self.option:
73             opt_prs = "<unknown>"
74             if self.option.short_opt and self.option.long_opt:
75                 opt_prs = "%s/%s"%(self.option.short_opt,self.option.long_opt)
76             elif self.option.short_opt:
77                 opt_prs = "%s"%(self.option.short_opt)
78             elif self.option.long_opt:
79                 opt_prs = "%s"%(self.option.long_opt)
80             return "option %s: %s"%(opt_prs, self.msg)
81         return self.msg
82
83 #===================================================================
84 # class ArgError : bad option argument error
85 #===================================================================
86 class ArgError(OptBaseError):
87     """
88     Bad argument exception class
89     """
90     pass
91
92 #===================================================================
93 # class ValError : bad command line parameter error
94 #===================================================================
95 class ValError(OptBaseError):
96     """
97     Bad parameter exception class
98     """
99     pass
100
101 #===================================================================
102 # class ArgOption : command line option
103 #===================================================================
104 class ArgOption:
105     """
106     Option class
107     """
108     attrs   = ["short_opt", "long_opt", "dest", "action", "type", "default", "metavar", "help"]
109     actions = ["store", "store_true", "store_false"]
110     types   = ["string", "int", "float", "bool"]
111     def __init__(self, *args, **kwargs):
112         # set defaults
113         for attr in self.attrs: setattr(self, attr, None)
114         # parse arguments
115         for i in range(len(args)):
116             if i > len(self.attrs)-1:
117                 msg = "Wrong number of parameters is given (maximum is %d)" % len(self.attrs)
118                 raise OptBaseError(msg)
119             setattr(self, self.attrs[i], args[i])
120         for arg in kwargs:
121             if arg not in self.attrs:
122                 msg = "Invalid argument: %s" % arg
123                 raise OptBaseError(msg)
124             setattr(self, arg, kwargs[arg])
125         # check short option key
126         if self.short_opt and \
127                not re.match("^-[a-zA-Z]$",self.short_opt):
128             msg  = "invalid short option key; "
129             msg += "should be of the form -x (x is letter)"
130             raise OptError(msg, self)
131         # check long option key
132         if self.long_opt and \
133                not re.match("^--[a-zA-Z][a-zA-Z0-9]*(-[a-zA-Z0-9]+)*$",self.long_opt):
134             msg  = "invalid long option key; "
135             msg += "should be of the form --word[[-word]...] "
136             msg += "(word is letters and digits sequence)"
137             raise OptError(msg, self)
138         # check that at least one option key is defined
139         if not self.short_opt and not self.long_opt:
140             msg  = "invalid option; neither short nor long option key is defined"
141             raise OptError(msg, self)
142         # destination
143         if not self.dest and self.long_opt:
144             self.dest = self.long_opt[2:].replace('-','_')
145         if not self.dest and self.short_opt:
146             self.dest = self.short_opt[1:]
147         # action
148         if not self.action:
149             self.action = "store"
150         if self.action not in self.actions:
151             msg  = "invalid action: %s" % self.action
152             raise OptError(msg, self)
153         # type
154         if not self.type:
155             if self.action in ["store_true","store_false"]: self.type = "bool"
156             else: self.type = "string"
157         if self.type not in self.types:
158             msg  = "invalid type: %s" % self.type
159             raise OptError(msg, self)
160         if self.action in ["store_true","store_false"] and self.type != "bool":
161             msg  = "invalid type: %s : should be 'bool' or None" % self.type
162             raise OptError(msg, self)
163         # default
164         if self.default is not None:
165             try:
166                 if self.type == "string": self.default = str(self.default)
167                 if self.type == "int":    self.default = int(self.default)
168                 if self.type == "float":  self.default = float(self.default)
169                 if self.type == "bool":   self.default = boolean(self.default)
170             except :
171                 msg  = "invalid default value type: should be %s" % self.type
172                 raise OptError(msg, self)
173             pass
174         # metavar
175         if not self.metavar:
176             self.metavar = self.dest.upper()
177         # help
178         if not self.help:
179             self.help = ""
180         pass
181
182     def to_string(self):
183         """
184         Returns string representation of the option
185         """
186         opts = []
187         opt = self.short_opt
188         if opt and self.action == "store" and self.metavar: opt += " %s" % self.metavar
189         if opt: opts.append(opt)
190         opt = self.long_opt
191         if opt and self.action == "store" and self.metavar: opt += "=%s" % self.metavar
192         if opt: opts.append(opt)
193         return (", ").join(opts)
194     
195 #===================================================================
196 # class Values : resulting option values
197 #===================================================================
198 class Values:
199     """
200     Values class
201     """
202     def __init__(self):
203         pass
204         
205 #===================================================================
206 # class ArgParser : command line arguments parser
207 #===================================================================
208 class ArgParser:
209     """
210     Arguments parser class
211     """
212     def __init__(self):
213         self.options = []
214         pass
215
216     def add_option(self, *args, **kwargs):
217         """Register an option"""
218         o = ArgOption(*args, **kwargs)
219         self._check_option(o)
220         self.options.append(o)
221         pass
222
223     def parse_args(self, args = None):
224         """Parse an arguments"""
225         if not args: args = sys.argv[1:]
226         values = Values()
227         for o in self.options:
228             if o.default is not None:
229                 setattr(values, o.dest, o.default)
230             elif not hasattr(values,o.dest):
231                 setattr(values, o.dest, None)
232         try:
233             (values, args) = self._process_args(values, args)
234         except (ArgError, ValError), e:
235             self._error(e.msg)
236
237         return (values, args)
238             
239     def print_usage(self):
240         """Print usage"""
241         print "usage: %s [options]" % os.path.basename(sys.argv[0])
242         pass
243
244     def print_help(self):
245         """Print help"""
246         self.print_usage()
247         print ""
248         olen = 0
249         _maxwidth, _indent = 79, 2
250         if len(self.options):
251             for option in self.options:
252                 if olen < len(option.to_string()): olen = len(option.to_string())
253             print "options:"
254             for option in self.options:
255                 strings = []
256                 for hs in option.help.split("\n"):
257                     s = ""
258                     for w in hs.split():
259                         if len("%s %s" % (s,w)) > _maxwidth:
260                             strings.append(s.strip()); s = ""
261                         s = "%s %s" % (s,w)
262                     if s.strip(): strings.append(s.strip())
263                 if not strings: strings[:0] = [""]
264                 print "%s%s%s" % (option.to_string(), " "*(_indent+olen-len(option.to_string())), strings[0])
265                 for i in range(1, len(strings)):
266                     print "%s%s" % (" "*(olen+_indent), strings[i])
267         pass
268     
269     def _check_option(self, option):
270         o = self._get_option(option.short_opt)
271         if not o: o = self._get_option(option.long_opt)
272         if o:
273             msg = "option conflicts with previously defined option(s)"
274             raise OptError(msg, option)
275         pass
276
277     def _get_option(self, opt_key):
278         if opt_key:
279             for o in self.options:
280                 if opt_key in [o.short_opt, o.long_opt]: return o
281         return None
282         
283     def _error(self, msg):
284         self.print_usage()
285         sys.exit("\n%s: error: %s\n" % (os.path.basename(sys.argv[0]), msg))
286         pass
287
288     def _check_value(self, option, value):
289         o = self._get_option(option)
290         try:
291             if o.type == "string": return str(value)
292             if o.type == "int":    return int(value)
293             if o.type == "float":  return float(value)
294             if o.type == "bool":   return boolean(value)
295         except:
296             msg  = "invalid value type for option %s: %s; " % (option, value)
297             msg += "should be %s" % o.type
298             raise ValError(msg)
299         raise OptBaseError("unknown error")
300
301     def _process_args(self, values, args):
302         res_args = []
303         cur_opt = None
304         rargs   = []
305         for index in range(len(args)):
306             a = args[index]
307             if cur_opt and cur_opt[1].action == "store":
308                 setattr(values, cur_opt[1].dest, self._check_value(cur_opt[0], a))
309                 cur_opt = None
310                 continue
311             if a == "-":
312                 rargs = args[index+1:]
313                 break
314             elif re.match("^-[a-zA-Z].*", a):
315                 for i in range(1,len(a)):
316                     if cur_opt and cur_opt[1].action == "store":
317                         setattr(values, cur_opt[1].dest, self._check_value(cur_opt[0], a[i:]))
318                         cur_opt = None
319                         break
320                     o = self._get_option("-%s"%a[i])
321                     if not o:
322                         raise ArgError("no such option: -%s"%a[i])
323                     if o.action == "store_true":
324                         setattr(values, o.dest, True)
325                     elif o.action == "store_false":
326                         setattr(values, o.dest, False)
327                     else:
328                         cur_opt = ("-%s"%a[i], o)
329                 pass
330             elif re.match("^--[a-zA-Z][a-zA-Z0-9]*(-[a-zA-Z0-9]+)*", a):
331                 oname  = ("%s="%a).split("=")[0]
332                 ovalue = ("%s="%a).split("=")[1]
333                 o = self._get_option(oname)
334                 if not o:
335                     raise ArgError("no such option: %s" % oname)
336                 if o.action == "store_true":
337                     if ovalue:
338                         raise ValError("option %s does not take a value" % oname)
339                     setattr(values, o.dest, True)
340                 elif o.action == "store_false":
341                     if ovalue:
342                         raise ValError("option %s does not take a value" % oname)
343                     setattr(values, o.dest, False)
344                 else:
345                     if ovalue:
346                         setattr(values, o.dest, self._check_value(oname, ovalue))
347                     else:
348                         cur_opt = (oname, o)
349                 pass
350             elif a.startswith("-"):
351                 raise ArgError("bad formatted option: %s" % a)
352             else:
353                 rargs = args[index:]
354                 break
355         if cur_opt and cur_opt[1].action == "store":
356             raise ValError("option %s requires value" % cur_opt[0])
357         return (values, rargs)
358
359 #------------------------------------------------------------------#
360 #                                                                  #
361 #                 XML CONFIGURATION FILES PARSER                   #
362 #                                                                  #
363 #------------------------------------------------------------------#
364
365 #===================================================================
366 # class Config : general configuration options : version, target and
367 #                temporary directories, etc...
368 #===================================================================
369 class Config :
370     """
371     General configuration file options:
372     - Install Wizard window caption
373     - SALOME platform version
374     - Copyright and license info
375     - Default target and temporary directories
376     """
377     def __init__(self,
378                  theVersion   = None,
379                  theCaption   = None,
380                  theCopyright = None,
381                  theLicense   = None,
382                  thePlatforms = None,
383                  theTargetdir = None,
384                  theTmpdir    = None):
385         self.version   = strip(theVersion)
386         self.caption   = strip(theCaption)
387         self.copyright = strip(theCopyright)
388         self.license   = strip(theLicense)
389         self.platforms = strip(thePlatforms)
390         self.targetdir = strip(theTargetdir)
391         self.tmpdir    = strip(theTmpdir)
392
393 #==============================================================
394 # class Product : pre-requisite product options
395 #==============================================================
396 class Product :
397     """
398     Product options:
399     - name, version
400     - target Linux OS version
401     - dependencies
402     - required disk space
403     - installation script
404     - etc...
405     """
406     def __init__(self,
407                  theName,
408                  theType               = None,
409                  theOS                 = None,
410                  theVersion            = None,
411                  theDependencies       = None,
412                  theWoGuiInstallation  = None,
413                  theInstalldiskspace   = None,
414                  theScript             = None,
415                  thePickUpEnvironment  = None):
416         self.name               = strip(theName)
417         self.type               = strip(theType)
418         self.os                 = strip(theOS)
419         self.version            = strip(theVersion)
420         self.dependencies       = strip(theDependencies)
421         self.woguiinst          = strip(theWoGuiInstallation)
422         self.installdiskspace   = strip(theInstalldiskspace)
423         self.script             = strip(theScript)
424         self.pickupEnv          = strip(thePickUpEnvironment)
425         self.whattodo           = __BINARIES__
426         
427     def setMode(self, mode):
428         if mode not in [__BINARIES__, __BUILDSRC__, __PREINSTALL__]:
429             return
430         self.whattodo = mode
431         return
432         
433 #===================================================================
434 # class ConfigParser : XML files parser implementation
435 #===================================================================
436 class ConfigParser:
437     """
438     XML configuration files parser
439     """
440     def __init__(self, is_force_src=False, pltname=None):
441         self.docElem = None
442         self.products = []
443         self.full_prods_list = []
444         self.config = None
445         self.is_force_src = is_force_src
446         self.pltname = pltname
447         pass
448         
449     def parse_config(self):
450         # Parse 'config' part of the XML file
451         configElem = self.docElem.getElementsByTagName('config')[0]
452         
453         self.config = Config(configElem.getAttribute('version').strip(),
454                              configElem.getAttribute('caption').strip(),
455                              configElem.getAttribute('copyright').strip(),
456                              configElem.getAttribute('license').strip(),
457                              configElem.getAttribute('platforms').strip(),
458                              configElem.getAttribute('targetdir').strip(),
459                              configElem.getAttribute('tempdir').strip())
460         if not self.pltname and self.config.platforms:
461             self.pltname = self.config.platforms.split(",")[0].strip()
462         pass
463     
464     def parse_dependencies(self):
465         # Parse 'dependencies' part of the XML file
466         depsMap = {}
467         depsElem = self.docElem.getElementsByTagName('dependencies')[0]
468         for prodElem in depsElem.getElementsByTagName('product'):
469             prodName = prodElem.getAttribute('name').strip()
470             if not prodName: continue
471             depsList = []
472             for depElem in prodElem.getElementsByTagName('dep'):
473                 depsList.append(depElem.firstChild.data)
474                 pass
475             depsMap[prodName] = depsList
476             pass
477         return depsMap
478     
479     def parse_product(self):
480         # Parse 'products' part of the XML file
481         depsMap = self.parse_dependencies()
482         prodsElem = self.docElem.getElementsByTagName('products')[0]
483         sal_prods_list = []; req_prods_list = []
484         modules_list = []; prereqs_list = []
485         for prodElem in prodsElem.getElementsByTagName('product'):
486             prodName = prodElem.getAttribute('name').strip()
487             if not prodName: continue
488             instElems = prodElem.getElementsByTagName('installation')
489             instElem = None
490             for node in instElems:
491                 if not self.pltname or self.pltname == node.getAttribute('os').strip():
492                     instElem = node
493                     break
494                 pass
495             if not instElem: continue
496             if check_bool(str(instElem.getAttribute('disable').strip())): continue
497             depsList = []
498             if prodName in depsMap: depsList = depsMap[prodName]
499             aProduct = Product(prodName,
500                                prodElem.getAttribute('type').strip(),
501                                instElem.getAttribute('os').strip(),
502                                instElem.getAttribute('version').strip(),
503                                depsList,
504                                instElem.getAttribute('woguimode').strip(),
505                                instElem.getAttribute('installdiskspace').strip(),
506                                instElem.getAttribute('script').strip(),
507                                instElem.getAttribute('pickupenv').strip())
508             if self.is_force_src:
509                 aProduct.setMode(__BUILDSRC__)
510                 pass
511             if prodElem.getAttribute('type').strip() == "component":
512                 sal_prods_list.append(aProduct)
513                 # fill an ordered modules list -----------
514                 modules_list.append(prodName)
515                 modules_list.append(prodName + "_src")
516                 pass
517             else: #prerequisite
518                 req_prods_list.append(aProduct)
519                 # fill an ordered prerequisites list -----------
520                 prereqs_list.append(prodName)
521                 #AKL: prerequisite sources and temp files are removed, by default.
522                 #     So, there is no need to make sources environment
523                 #if aProduct.whattodo == __BUILDSRC__: prereqs_list.append(prodName + "_src")
524                 pass
525             pass
526         self.products.extend( req_prods_list )
527         self.products.extend( sal_prods_list )
528         if len(self.products) != 0:
529             gcc_product = Product("gcc",
530                                   __CTX__PREREQUISITE__,
531                                   self.products[0].os,
532                                   "",
533                                   [],
534                                   None,
535                                   "0,0,0",
536                                   "gcc-common.sh",
537                                   "")
538             gcc_product.setMode(__PREINSTALL__)
539             self.products.insert(0, gcc_product)
540             prereqs_list.insert(0, gcc_product.name)
541             pass
542         self.full_prods_list.extend( prereqs_list )
543         self.full_prods_list.extend( modules_list )
544         pass
545
546     def parse(self, xml_file):
547         filehandle = open(xml_file)
548         sax_parser = xml.sax.make_parser()
549         doc = xml.dom.minidom.parse(filehandle, sax_parser)
550         filehandle.close()
551
552         self.docElem = doc.documentElement
553         self.parse_config()
554         self.parse_product()
555         pass
556
557     def getProduct(self, prod):
558         for product in self.products:
559             if product.name == prod:
560                 return product
561         return None
562
563
564 #------------------------------------------------------------------#
565 #                                                                  #
566 #                         SERVICE FUNCTIONS                        #
567 #                                                                  #
568 #------------------------------------------------------------------#
569
570 #==============================================================
571 # message: prints diagnostic information
572 #==============================================================
573 def message(msg):
574     """
575     Prints diagnostic information.
576     """
577     if msg.strip():
578         print ">>>", msg
579     pass
580
581 #==============================================================
582 # warning: prints warning
583 #==============================================================
584 def warning(msg):
585     """
586     Prints warning.
587     """
588     if msg.strip():
589         print ""
590         print msg
591         print ""
592     pass
593
594 #==============================================================
595 # error_exit : prints (optionally) error string, then prints
596 #              help information and quits
597 #==============================================================
598 def error_exit(msg = "", print_help = True):
599     """
600     Prints (optionally) error string,
601     then prints help information and quits.
602     """
603     # print error message
604     if len(msg.strip()):
605         print ""
606         print msg
607         print ""
608     # print help information
609     if print_help:
610         global opt_parser
611         if opt_parser:
612             opt_parser.print_help() 
613             print ""
614     # cleaning 
615     clean_all()
616     # quit
617     sys.exit(1);
618     pass
619
620 #==============================================================
621 # boolean : Converts string to boolean value.
622 #==============================================================
623 def boolean(val):
624     """
625     Converts string to boolean value if possible.
626     Raises exception if wrong string is used.
627     """
628     if isinstance(val, types.StringType):
629         if val.strip().lower()   in ["true",  "yes", "ok"]     : return True
630         elif val.strip().lower() in ["false", "no",  "cancel"] : return False
631         else: raise TypeError("invalid boolean value")
632     return bool(val)
633
634 #=================================================================
635 # check_bool : checks boolean value: yes/no, true/false, 1/0
636 #=================================================================
637 def check_bool(val):
638     """
639     Checks boolean value.
640     """
641     try:
642         return boolean(val)
643     except:
644         pass
645     return False
646
647 #==============================================================
648 # clean_all : performs system cleaning before exiting
649 #==============================================================
650 def clean_all():
651     """
652     Performs system cleaning before exiting.
653     """
654     global root_path
655     remove_dir(root_path)
656     pass
657
658 #==============================================================
659 # parse_parameters : parses command line arguments
660 #==============================================================
661 def parse_parameters():
662     """
663     Parses command line arguments.
664     """
665     global opt_parser
666     opt_parser = ArgParser()
667     
668     help_str  = "Runs the Installation Wizard in the GUI mode [default].\n"
669     opt_parser.add_option("-g",
670                           "--gui",
671                           action="store_true",
672                           dest="gui",
673                           default=True,
674                           help=help_str)
675     help_str  = "Runs the Installation Wizard in the TUI mode."
676     opt_parser.add_option("-b",
677                           "--batch",
678                           action="store_false",
679                           dest="gui",
680                           help=help_str)
681     help_str  = "The configuration xml file.\n"
682     help_str += "If this parameter is missing, then the program tries to define the "
683     help_str += "Linux platform and use the corresponding xml file. For example, "
684     help_str += "for Red Hat 8.0 config_RedHat_8.0.xml file is used in this case. "
685     opt_parser.add_option("-f",
686                           "--file",
687                           action="store",
688                           dest="xmlfile",
689                           metavar="FILE",
690                           help=help_str)
691     help_str  = "The platform specification.\n"
692     help_str += "This option can be used in conjunction with --file option in order"
693     help_str += "to specify Linux platform name when XML file contains installation"
694     help_str += "options for several platforms."
695     opt_parser.add_option("-p",
696                           "--platform",
697                           action="store",
698                           dest="platform",
699                           metavar="PLT",
700                           help=help_str)
701     help_str  = "The target directory the products to be installed to.\n"
702     help_str += "When used this parameter overrides the default target directory "
703     help_str += "defined in the configuration xml file."
704     opt_parser.add_option("-d",
705                           "--target",
706                           action="store",
707                           dest="target_dir",
708                           metavar="DIR",
709                           help=help_str)
710     help_str  = "The directory to be used for temporary files.\n"
711     help_str += "When used this parameter overrides the default temporary directory "
712     help_str += "defined in the configuration xml file."
713     opt_parser.add_option("-t",
714                           "--tmp",
715                           action="store",
716                           dest="tmp_dir",
717                           metavar="DIR",
718                           help=help_str)
719     help_str  = "Force all products to be installed from sources \n"
720     help_str += "including SALOME modules.\n"
721     help_str += "If this option is used all the default installation modes are ignored."
722     opt_parser.add_option("-a",
723                           "--all-from-sources",
724                           action="store_true",
725                           dest="force_sources",
726                           default=False,
727                           help=help_str)
728     help_str  = "Install all SALOME binaries packages to one directory.\n"
729     help_str += "This option is ignored when --all-from-sources (-a) option is used."
730     opt_parser.add_option("-s",
731                           "--single-directory",
732                           action="store_true",
733                           dest="single_dir",
734                           default=False,
735                           help=help_str)
736     help_str  = "Prints version information and quits."
737     opt_parser.add_option("-v",
738                           "--version",
739                           action="store_true",
740                           help=help_str)
741     help_str  = "Prints this help and quits."
742     opt_parser.add_option("-h",
743                           "--help",
744                           action="store_true",
745                           help=help_str)
746     (options, args) = opt_parser.parse_args()
747     if options.help:
748         # print help info and quit
749         print "\nSALOME Installation Wizard\n"
750         opt_parser.print_help()
751         print ""
752         sys.exit(0)
753     if options.version:
754         # print version info and quit
755         print ""
756         cmd = "./bin/SALOME_InstallWizard --version"
757         os.system(cmd)
758         print ""
759         sys.exit(0)
760     return [options.xmlfile, options.target_dir, options.tmp_dir, options.gui, options.force_sources, options.single_dir, options.platform]
761
762 #=================================================================
763 # strip : removes spaces at the beginning and at the end of the 
764 #         <param> if it is of string type
765 #=================================================================
766 def strip(param):
767     """
768     Removes spaces at the beginning and at the end
769     of the given parameter.
770     """
771     if type(param) == types.StringType:
772         return param.strip()
773     return param
774     
775 #=================================================================
776 # get_dependencies : extract products dependencies
777 #=================================================================
778 def get_dependencies(prods):
779     """
780     Gets a list of installed and required products.
781     """
782     prods_list = []
783     for product in prods:
784         for dep in product.dependencies:
785             if dep and dep not in prods_list:
786                 prods_list.append( dep )
787                 dep_name = dep
788                 if product.whattodo == __BUILDSRC__:
789                     dep_name = dep + "_src"
790                 if dep_name not in parser.full_prods_list:
791                     msg = "Prerequisite '%s' is required for '%s' product,\n"%(dep, product.name)
792                     msg += "but the first one is absent in the list of products to be installed!\n"
793                     msg += "Please check your XML file."
794                     warning(msg)
795
796         if product.name and product.name not in prods_list:
797             prods_list.append( product.name )
798             
799     return " ".join( prods_list )
800
801 #==============================================================
802 # create_dir : creates a directory with (optional) permissions,
803 #              returns the part of path that existed before
804 #              directory creation; exits with error if access
805 #              is denied
806 #==============================================================
807 def create_dir(directory, access = 0777):
808     """
809     Creates a directory with (optional) permissions,
810     returns the part of path that existed before
811     directory creation; exits with error if access
812     is denied.
813     """
814     dirs = directory.split("/")
815     existing = "";
816     dir = ""
817     root = ""
818     for subdir in dirs:
819         if len(subdir) == 0:  continue
820         dir = "%s/%s"%(dir, subdir)
821         if os.path.exists(dir):
822             existing = dir
823         else:
824             try:
825                 os.mkdir(dir, access)
826             except:
827                 error_exit("Can't create directory: %s.\nAccess is denied."%directory)
828             if dir == "%s/%s"%(existing, subdir):
829                 root = dir
830     return root
831
832 #==============================================================
833 # substituteVars : performes environment variables substistution
834 #                  the given string; if varibale is not defined
835 #                  it is substituted by the empty string
836 #==============================================================
837 def substituteVars(str):
838     """
839     Performes environment variables substistution.
840     """
841     str = os.path.expanduser(str)
842     str = os.path.expandvars(str)
843     return str
844
845 #================================================================
846 # get_program_path : gets program's directory path
847 #                    (and performs 'cd' command there) 
848 #================================================================
849 def get_program_path():
850     """
851     Returns the program directory path
852     (and make this directory current).
853     """
854     path = os.path.dirname(sys.argv[0])
855     if path:
856         os.chdir(path)
857     return os.getcwd()
858
859 #================================================================
860 # check_dir : checks directory existence
861 #================================================================
862 def check_dir(dir):
863     """
864     Checks directory existence.
865     """
866     if (os.path.islink(dir)):
867         realpath = os.path.realpath(dir)
868         if not os.path.exists(realpath):
869             msg = "Invalid link %s.\nThe directory %s a link points to does not exist. Stopped..."%(dir,realpath)
870             error_exit(msg, False)
871     else:
872         if not os.path.exists(dir):
873             msg = "Directory %s does not exist. Stopped..."%dir
874             error_exit(msg, False)
875     pass
876
877 #===============================================================
878 # check_disk_space : checks the disk space;
879 #                    quits if there is no enough disk space
880 #===============================================================
881 def check_disk_space(products, scripts_dir, target_dir, tmp_dir, is_force_src=False):
882     """
883     Checks if there is enough disk space to install products.
884     Quits with error if there is no enough disk space.
885     """
886     install_space = 0
887     temporary_space = 0
888     for product in products:
889         prod_space = 0
890         try:
891             spaces = product.installdiskspace.split(',')
892             prod_space = int( spaces[0] )
893             if product.whattodo == __BINARIES__:
894                 prod_space = int( spaces[0] )
895                 if product.type == __CTX__COMPONENT__:
896                     prod_space += int( spaces[1] )
897             else:
898                 if product.type == __CTX__PREREQUISITE__:
899                     prod_space = int( spaces[0] )
900                 else:
901                     prod_space = int( spaces[2] )
902         except:
903             pass
904         install_space = install_space + prod_space
905         pass
906
907     res = os.system("%s/%s %s %d"%(scripts_dir, "checkSize.sh", target_dir, install_space))
908     if res:
909         msg = "There is no enough space to install the products. Stopped..."
910         error_exit(msg, False)
911     pass
912  
913 #===============================================================
914 # remove_dir : removes temporary directory
915 #===============================================================
916 def remove_dir(path):
917     """
918     Removes temporary directory.
919     """
920     if path and os.path.exists(path):
921         os.system("rm -rf " + path)
922     pass
923
924 #==============================================================
925 # has_binaries : returns True if some product is installed from
926 #                binaries
927 #===============================================================
928 def has_binaries(products):
929     """
930     Returns True if some product is installed in 'binaries' mode.
931     """
932     for product in products:
933         if product.whattodo == __BINARIES__:
934             return True
935     return False
936
937 #==============================================================
938 # has_sources : returns True if some product is installed from
939 #               sources
940 #===============================================================
941 def has_sources(products):
942     """
943     Returns True if some product is installed in 'sources' mode.
944     """
945     for product in products:
946         if product.whattodo == __BUILDSRC__:
947             return True
948     return False
949
950 #==============================================================
951 # get_tmp_dir : gets temporary directory name
952 #===============================================================
953 def get_tmp_dir(dir):
954     """
955     Gets temporary directory path.
956     """
957     max_attempts = 100
958     dir_prefix="INSTALLWORK"
959     range_bottom = 0; range_top = 999999
960     for i in xrange(max_attempts):
961         tmp_dir = "%s/%s%d"%(dir, dir_prefix, random.randint(range_bottom,range_top))
962         if not os.path.exists( tmp_dir ):
963             return tmp_dir
964     return "%s/%s%d"%(dir, dir_prefix, random.randint(range_bottom,range_top))
965
966 #==============================================================
967 # get_os_release : gets OS release; the OS name, version and
968 #                  architecture
969 #                  For example:
970 #                  RedHat, 8.0; Mandriva, 2006.0, 64
971 #===============================================================
972 def get_os_release():
973     filename = "/etc/issue"
974     # ---
975     plt_name = "unknown"
976     plt_ver  = ""
977     plt_arch = ""   
978     if os.path.exists(filename):
979         # ---
980         f = open(filename)
981         lines = f.readlines()
982         f.close()
983         # ---
984         regvar  = re.compile("(.*)\s+[^\s]*[R|r]elease[^\s]*\s+([\d.]*)")
985         regvar1 = re.compile("(.*)\s+[^\s]*[L|l][I|i][N|n][U|u][X|x][^\s]*(.*)\s+([\d.]*)\s+")
986         for l in lines:
987             res = re.search(regvar, l)
988             if not res:
989                 res = re.search(regvar1, l)
990             if res:
991                 plt_name = " ".join(" ".join(res.groups()[:len(res.groups())-1]).split())
992                 # workaround for Mandrake and other platforms
993                 plt_name = plt_name.replace("Linux", "").replace("linux", "").replace("LINUX", "").strip()
994                 # workaround for SuSe
995                 plt_name = plt_name.replace("Welcome to", "").strip()
996                 # ---
997                 plt_name = " ".join(plt_name.split())
998                 plt_ver  = res.group(len(res.groups()))
999                 if re.search(r'x86_64', l):
1000                     plt_arch = "64bit"
1001                     pass
1002                 # workaround for Red Hat Enterprise
1003                 if not plt_arch:
1004                     try:
1005                         import platform
1006                         if platform.machine() == "x86_64":
1007                             plt_arch = "64bit"
1008                             pass
1009                         pass
1010                     except:
1011                         pass
1012                     pass
1013                 break
1014             pass
1015         pass
1016
1017     return plt_name, plt_ver, plt_arch
1018
1019 #==============================================================
1020 # check_xml_file : checks XML file existence and readability
1021 #===============================================================
1022 def check_xml_file(xml_file):
1023     """
1024     Checks XML file existence and readability.
1025     """
1026     if not os.path.isfile(xml_file):
1027         msg = "Configuration file %s is not found!"%xml_file
1028         error_exit(msg, False)
1029
1030     if not os.access(xml_file, os.R_OK):
1031         msg = "There is no read access for %s file!"%xml_file
1032         error_exit(msg, False)
1033     pass
1034
1035 #==============================================================
1036 # get_supported_plts : gets map of supported Linux platforms and
1037 #                      corresponding configuration files
1038 #===============================================================
1039 def get_supported_platforms(xml_file=None):
1040     """
1041     Gets map of supported Linux platforms and
1042     corresponding configuration files.
1043     """
1044     platforms_map = {}
1045     if xml_file:
1046         xml_file_list = [xml_file]
1047         pass
1048     else:
1049         xml_file_list = filter(lambda i: i.endswith(".xml"), os.listdir(get_program_path()))
1050         while 'config.xml' in xml_file_list: xml_file_list.remove('config.xml')
1051         if os.path.exists(os.path.join(get_program_path(), 'config.xml')):
1052             xml_file_list.append('config.xml')
1053         xml_file_list = [os.path.abspath(i) for i in xml_file_list]
1054         pass
1055     for an_xml_file in xml_file_list: # XML files parsing
1056         check_xml_file(an_xml_file)
1057         parser = ConfigParser()
1058         parser.parse(an_xml_file)
1059         if parser.config.platforms is not None:
1060             for plt in parser.config.platforms.split(","):
1061                 if not plt or plt in platforms_map.keys(): continue
1062                 platforms_map[strip(plt)] = an_xml_file
1063                 pass
1064             pass
1065         pass
1066     return platforms_map
1067
1068 #==============================================================
1069 # Print menu with list of supported platform
1070 # and return user choice
1071 #===============================================================
1072 def select_platform(all_platforms):
1073     platforms = all_platforms.keys()
1074     platforms.sort()
1075     pltname = None
1076     while not pltname:
1077         print "Please, select any platform from the list below."
1078         print "--------------------------"
1079         for idx in range(len(platforms)):
1080             print " %2d. %s" % (idx+1, " ".join(platforms[idx].split("_")))
1081         print "  0. Exit"
1082         print "--------------------------"
1083         print "Type your choice (%d-%d) and press <Enter>:" % (0, len(platforms)),
1084         try:
1085             idx = raw_input()
1086         except:
1087             sys.exit(1)
1088         try:
1089             idx = int(idx)
1090         except:
1091             warning("Invalid input!")
1092             pass
1093         if idx == 0: sys.exit(0)
1094         if idx > 0 and idx <= len(platforms):
1095             pltname = platforms[idx-1]
1096         else:
1097             warning("Invalid input!")
1098         pass
1099     return pltname, all_platforms[pltname]
1100
1101 #------------------------------------------------------------------#
1102 #                                                                  #
1103 #                    EXECUTION STARTS HERE                         #
1104 #                                                                  #
1105 #------------------------------------------------------------------#
1106
1107 if __name__ == "__main__":
1108     # parse command line
1109     [xml_file, target_dir, tmp_dir, is_gui, is_force_src, is_single_dir, pltname] = parse_parameters()
1110     if xml_file:   xml_file   = os.path.abspath(xml_file)
1111     if target_dir: target_dir = os.path.abspath(target_dir)
1112     if tmp_dir:    tmp_dir    = os.path.abspath(tmp_dir)
1113     # get program dir
1114     cur_dir = get_program_path()
1115
1116     #---- GUI ----------------
1117
1118     if is_gui : 
1119         env = os.environ
1120         if not env.has_key("PATH") :
1121             env["PATH"] = ""
1122         if not env.has_key("LD_LIBRARY_PATH") :
1123             env["LD_LIBRARY_PATH"] = ""
1124
1125         env["LD_LIBRARY_PATH"] =  "./bin/lib:" + ".:" + env["LD_LIBRARY_PATH"]
1126         env["PATH"] = ".:" + env["PATH"]
1127
1128         cmd = "./bin/SALOME_InstallWizard"
1129         if xml_file is not None:
1130             cmd += " --file %s"%xml_file
1131         if pltname is not None:
1132             cmd += " --platform %s"%pltname
1133         if target_dir is not None:
1134             cmd += " --target %s"%target_dir
1135         if tmp_dir is not None:
1136             cmd += " --tmp %s"%tmp_dir
1137         if is_force_src:
1138             cmd += " --all-from-sources"
1139         if is_single_dir:
1140             cmd += " --single-directory"
1141         cmd += "&"
1142         sys.exit(os.system(cmd))
1143
1144     #-----  TUI ---------------------
1145     #
1146     # define xml file to be used
1147     #
1148     # get current Linux platform
1149     plt_name, plt_ver, plt_arch = get_os_release()
1150     data = []
1151     for i in plt_name, plt_ver, plt_arch:
1152         if i: data.append(i)
1153     full_plt_name = " ".join(data)
1154     # get all supported platforms
1155     all_platforms = get_supported_platforms(xml_file)
1156     if all_platforms:
1157         if pltname:
1158             # platform name is specified in the command line
1159             if pltname in all_platforms:
1160                 # if specified platform is supported, choose the corresponding XML file for use
1161                 xml_file = all_platforms[pltname]
1162             else:
1163                 # if specified platform is NOT supported, print warning message
1164                 # and prompt user to choose another platform
1165                 msg = "Specified platform is not supported: %s" % (pltname)
1166                 warning(msg)
1167                 pltname, xml_file = select_platform(all_platforms)
1168                 pass
1169             pass
1170         elif full_plt_name in all_platforms:
1171             # if current platform is supported, choose the corresponding XML file for use
1172             pltname  = full_plt_name
1173             xml_file = all_platforms[pltname]
1174         else:
1175             if xml_file and len(all_platforms) == 1:
1176                 # XML file is specified and contains only one platform definition
1177                 xml_file = all_platforms.values()[0]
1178                 pltname  = all_platforms.keys()[0]
1179             else:
1180                 # current Linux platform is not supported, print warning message
1181                 # and prompt user to choose platform from the list
1182                 warning("Not supported Linux platform: %s."%" ".join(data))
1183                 pltname, xml_file = select_platform(all_platforms)
1184             pass
1185         pass
1186     else:
1187         # current Linux platform is not supported, exit
1188         if pltname:
1189             msg = "Not supported Linux platform: %s."%pltname
1190         else:
1191             msg = "Not supported Linux platform: %s."%" ".join(data)
1192         error_exit(msg, False)
1193         pass
1194
1195     # parse XML file -----------
1196     message("Parsing XML configuration file: %s"%xml_file)
1197     parser = ConfigParser(is_force_src, pltname)
1198     parser.parse(xml_file)
1199
1200     # source directory map
1201     bin_dir = ""
1202     if parser.config.platforms:
1203         bin_dir += "/%s"%"_".join( parser.pltname.split() )
1204     subdir = { __BINARIES__   : "BINARIES" + bin_dir,
1205                __BUILDSRC__   : "SOURCES",
1206                __PREINSTALL__ : ""}
1207
1208     # check scripts directory -----------
1209     scripts_dir = "%s/%s"%(cur_dir, "config_files")
1210     check_dir(scripts_dir)
1211
1212     # check products archives directories -----------
1213     has_bin = has_binaries(parser.products)
1214     has_src = has_sources(parser.products)
1215     source_dir = "%s/%s"%(cur_dir, "Products")
1216
1217     if has_src or has_bin:
1218         check_dir(source_dir)
1219
1220     if has_src:
1221         check_dir("%s/%s"%(source_dir,subdir[__BUILDSRC__]))
1222
1223     if has_bin:
1224         check_dir("%s/%s"%(source_dir,subdir[__BINARIES__]))
1225
1226     # check/create target dir -----------
1227     if target_dir is None:
1228         target_dir = parser.config.targetdir
1229     target_dir = substituteVars(target_dir)
1230
1231     message("Creating target directory: " + target_dir)
1232     create_dir(target_dir, 0755)
1233
1234     if not os.path.exists(target_dir):
1235         error_exit("Invalid target directory: " + target_dir)
1236
1237     if not os.access(target_dir, os.W_OK) :
1238         error_exit("There is no write permissions for the directory: " + target_dir)
1239
1240     # check/create temporary dir -----------
1241     if tmp_dir is None:
1242         tmp_dir = parser.config.tmpdir
1243     if not tmp_dir:
1244         tmp_dir = "/tmp"
1245     tmp_dir = substituteVars(tmp_dir)
1246     tmp_dir = get_tmp_dir(tmp_dir)
1247
1248     message("Creating temporary directory: " + tmp_dir)
1249     root_path = create_dir(tmp_dir, 0755)
1250    
1251     if not os.path.exists(tmp_dir):
1252         error_exit("Invalid temporary directory: " + tmp_dir)
1253
1254     if not os.access(tmp_dir, os.W_OK) :
1255         error_exit("There is no write permissions for the directory: " + tmp_dir)
1256         
1257     # check available disk space -----------
1258     message("Checking available disk space")
1259     check_disk_space(parser.products, scripts_dir, target_dir, tmp_dir, is_force_src)
1260
1261     # change current directory -----------
1262     os.chdir(scripts_dir)
1263
1264     # get dependencies list -----------
1265     list_of_dep = get_dependencies(parser.products)
1266     products_string = " ".join(parser.full_prods_list)
1267
1268     # don't remove sources and tmp files, by default -----------
1269     rm_src_tmp = "FALSE"
1270
1271     # starting -----------
1272     message("Starting ...")
1273     
1274     # install products -----------
1275     for product in parser.products:
1276         # remove only prerequisites temporary files
1277         if product.type == __CTX__PREREQUISITE__ or \
1278            (product.type == __CTX__COMPONENT__ and product.whattodo == __BUILDSRC__):
1279             rm_src_tmp = "TRUE"
1280         message("... processing %s ..."%product.name)
1281         cmd = '%s/%s %s %s %s/%s %s "%s" %s "%s" %s/%s %s %s/%s' % (
1282             scripts_dir, product.script,
1283             product.whattodo,
1284             tmp_dir,
1285             source_dir, subdir[product.whattodo],
1286             target_dir,
1287             products_string,
1288             product.name,
1289             products_string,
1290             source_dir, subdir[__BUILDSRC__],
1291             rm_src_tmp,
1292             source_dir, subdir[__BINARIES__]
1293             )
1294         # install all modules with GUI
1295         if product.woguiinst is not None and product.woguiinst != "":
1296             cmd += ' TRUE'
1297         # use single directory or not
1298         if product.whattodo == __BINARIES__ and product.type == __CTX__COMPONENT__ and is_single_dir:
1299             cmd += ' TRUE'
1300         res = os.system(cmd)
1301         rm_src_tmp = "FALSE"
1302         pass
1303
1304     # modify *.la files, if --single-directory option was  -----------
1305     if is_single_dir:
1306         message("Modifying of *.la files of SALOME modules...")
1307         cmd = '%s/modifyLaFiles.sh modify_la_files %s' % (scripts_dir, target_dir)
1308         res = os.system(cmd)
1309
1310     # pickup environment -----------
1311     message("Creating environment files")
1312     for product in parser.products :
1313         if check_bool(product.pickupEnv):
1314             cmd = '%s/%s pickup_env %s %s/%s %s "%s" %s "%s" %s/%s %s %s/%s' % (
1315                 scripts_dir, product.script,
1316                 tmp_dir,
1317                 source_dir, subdir[product.whattodo],
1318                 target_dir,
1319                 products_string,
1320                 product.name,
1321                 products_string,
1322                 source_dir, subdir[__BUILDSRC__],
1323                 rm_src_tmp,
1324                 source_dir, subdir[__BINARIES__]
1325                 )
1326             # install all modules with GUI
1327             if product.woguiinst is not None and product.woguiinst != "":
1328                 cmd += ' TRUE'
1329             # use single directory or not
1330             if product.whattodo == __BINARIES__ and product.type == __CTX__COMPONENT__ and is_single_dir:
1331                 cmd += ' TRUE'
1332             res = os.system(cmd)
1333             pass
1334         pass
1335
1336     # clean temporary directory -----------
1337     message("Cleaning temporary directory")
1338     clean_all()
1339     
1340     # finishing -----------
1341     message("Finished!")
1342     pass