xref: /petsc/config/install.py (revision 7d0a6c19129e7069c8a40e210b34ed62989173db)
1#!/usr/bin/env python
2import re, os, sys, shutil
3
4if os.environ.has_key('PETSC_DIR'):
5  PETSC_DIR = os.environ['PETSC_DIR']
6else:
7  fd = file(os.path.join('conf','petscvariables'))
8  a = fd.readline()
9  a = fd.readline()
10  PETSC_DIR = a.split('=')[1][0:-1]
11  fd.close()
12
13if os.environ.has_key('PETSC_ARCH'):
14  PETSC_ARCH = os.environ['PETSC_ARCH']
15else:
16  fd = file(os.path.join('conf','petscvariables'))
17  a = fd.readline()
18  PETSC_ARCH = a.split('=')[1][0:-1]
19  fd.close()
20
21print '*** using PETSC_DIR='+PETSC_DIR+' PETSC_ARCH='+PETSC_ARCH+' ***'
22sys.path.insert(0, os.path.join(PETSC_DIR, 'config'))
23sys.path.insert(0, os.path.join(PETSC_DIR, 'config', 'BuildSystem'))
24
25import script
26
27try:
28  WindowsError
29except NameError:
30  WindowsError = None
31
32class Installer(script.Script):
33  def __init__(self, clArgs = None):
34    import RDict
35    argDB = RDict.RDict(None, None, 0, 0, readonly = True)
36    if os.environ.has_key('PETSC_DIR'):
37      PETSC_DIR = os.environ['PETSC_DIR']
38    else:
39      fd = file(os.path.join('conf','petscvariables'))
40      a = fd.readline()
41      a = fd.readline()
42      PETSC_DIR = a.split('=')[1][0:-1]
43      fd.close()
44    argDB.saveFilename = os.path.join(PETSC_DIR, PETSC_ARCH, 'conf', 'RDict.db')
45    argDB.load()
46    script.Script.__init__(self, argDB = argDB)
47    if not clArgs is None: self.clArgs = clArgs
48    self.copies = []
49    return
50
51  def setupHelp(self, help):
52    import nargs
53    script.Script.setupHelp(self, help)
54    help.addArgument('Installer', '-destDir=<path>', nargs.Arg(None, None, 'Destination Directory for install'))
55    return
56
57
58  def setupModules(self):
59    self.setCompilers  = self.framework.require('config.setCompilers',         None)
60    self.arch          = self.framework.require('PETSc.utilities.arch',        None)
61    self.petscdir      = self.framework.require('PETSc.utilities.petscdir',    None)
62    self.makesys       = self.framework.require('config.programs',        None)
63    self.compilers     = self.framework.require('config.compilers',            None)
64    return
65
66  def setup(self):
67    script.Script.setup(self)
68    self.framework = self.loadConfigure()
69    self.setupModules()
70    return
71
72  def setupDirectories(self):
73    self.rootDir    = self.petscdir.dir
74    self.destDir    = os.path.abspath(self.argDB['destDir'])
75    self.installDir = self.framework.argDB['prefix']
76    self.arch       = self.arch.arch
77    self.rootIncludeDir    = os.path.join(self.rootDir, 'include')
78    self.archIncludeDir    = os.path.join(self.rootDir, self.arch, 'include')
79    self.rootConfDir       = os.path.join(self.rootDir, 'conf')
80    self.archConfDir       = os.path.join(self.rootDir, self.arch, 'conf')
81    self.rootBinDir        = os.path.join(self.rootDir, 'bin')
82    self.archBinDir        = os.path.join(self.rootDir, self.arch, 'bin')
83    self.archLibDir        = os.path.join(self.rootDir, self.arch, 'lib')
84    self.destIncludeDir    = os.path.join(self.destDir, 'include')
85    self.destConfDir       = os.path.join(self.destDir, 'conf')
86    self.destLibDir        = os.path.join(self.destDir, 'lib')
87    self.destBinDir        = os.path.join(self.destDir, 'bin')
88    self.installIncludeDir = os.path.join(self.installDir, 'include')
89    self.installBinDir     = os.path.join(self.installDir, 'bin')
90
91    self.make      = self.makesys.make+' '+self.makesys.flags
92    self.ranlib    = self.compilers.RANLIB
93    self.libSuffix = self.compilers.AR_LIB_SUFFIX
94    return
95
96  def copytree(self, src, dst, symlinks = False, copyFunc = shutil.copy2):
97    """Recursively copy a directory tree using copyFunc, which defaults to shutil.copy2().
98
99    The destination directory must not already exist.
100    If exception(s) occur, an shutil.Error is raised with a list of reasons.
101
102    If the optional symlinks flag is true, symbolic links in the
103    source tree result in symbolic links in the destination tree; if
104    it is false, the contents of the files pointed to by symbolic
105    links are copied.
106    """
107    copies = []
108    names  = os.listdir(src)
109    if not os.path.exists(dst):
110      os.makedirs(dst)
111    elif not os.path.isdir(dst):
112      raise shutil.Error, 'Destination is not a directory'
113    errors = []
114    for name in names:
115      srcname = os.path.join(src, name)
116      dstname = os.path.join(dst, name)
117      try:
118        if symlinks and os.path.islink(srcname):
119          linkto = os.readlink(srcname)
120          os.symlink(linkto, dstname)
121        elif os.path.isdir(srcname):
122          copies.extend(self.copytree(srcname, dstname, symlinks))
123        else:
124          copyFunc(srcname, dstname)
125          copies.append((srcname, dstname))
126        # XXX What about devices, sockets etc.?
127      except (IOError, os.error), why:
128        errors.append((srcname, dstname, str(why)))
129      # catch the Error from the recursive copytree so that we can
130      # continue with other files
131      except shutil.Error, err:
132        errors.extend(err.args[0])
133    try:
134      shutil.copystat(src, dst)
135    except OSError, e:
136      if WindowsError is not None and isinstance(e, WindowsError):
137        # Copying file access times may fail on Windows
138        pass
139      else:
140        errors.extend((src, dst, str(e)))
141    if errors:
142      raise shutil.Error, errors
143    return copies
144
145
146  def fixConfFile(self, src):
147    lines   = []
148    oldFile = open(src, 'r')
149    for line in oldFile.readlines():
150      # paths generated by configure could be different link-path than whats used by user, so fix both
151      line = re.sub(re.escape(os.path.join(self.rootDir, self.arch)), self.installDir, line)
152      line = re.sub(re.escape(os.path.realpath(os.path.join(self.rootDir, self.arch))), self.installDir, line)
153      line = re.sub(re.escape(os.path.join(self.rootDir, 'bin')), self.installBinDir, line)
154      line = re.sub(re.escape(os.path.realpath(os.path.join(self.rootDir, 'bin'))), self.installBinDir, line)
155      line = re.sub(re.escape(os.path.join(self.rootDir, 'include')), self.installIncludeDir, line)
156      line = re.sub(re.escape(os.path.realpath(os.path.join(self.rootDir, 'include'))), self.installIncludeDir, line)
157      # remove PETSC_DIR/PETSC_ARCH variables from conf-makefiles. They are no longer necessary
158      line = re.sub('\$\{PETSC_DIR\}/\$\{PETSC_ARCH\}', self.installDir, line)
159      line = re.sub('PETSC_ARCH=\$\{PETSC_ARCH\}', '', line)
160      line = re.sub('\$\{PETSC_DIR\}', self.installDir, line)
161      lines.append(line)
162    oldFile.close()
163    newFile = open(src, 'w')
164    newFile.write(''.join(lines))
165    newFile.close()
166    return
167
168  def fixConf(self):
169    import shutil
170    # copy standard rules and variables file so that we can change them in place
171    for file in ['rules', 'variables']:
172      shutil.copy2(os.path.join(self.rootConfDir,file),os.path.join(self.archConfDir,file))
173    for file in ['rules', 'variables','petscrules', 'petscvariables']:
174      self.fixConfFile(os.path.join(self.archConfDir,file))
175
176  def createUninstaller(self):
177    uninstallscript = os.path.join(self.archConfDir, 'uninstall.py')
178    f = open(uninstallscript, 'w')
179    # Could use the Python AST to do this
180    f.write('#!'+sys.executable+'\n')
181    f.write('import os\n')
182
183    f.write('copies = '+re.sub(self.destDir,self.installDir,repr(self.copies)))
184    f.write('''
185for src, dst in copies:
186  if os.path.exists(dst):
187    os.remove(dst)
188''')
189    f.close()
190    os.chmod(uninstallscript,0744)
191    return
192
193  def installIncludes(self):
194    self.copies.extend(self.copytree(self.rootIncludeDir, self.destIncludeDir))
195    self.copies.extend(self.copytree(self.archIncludeDir, self.destIncludeDir))
196    return
197
198  def installConf(self):
199    self.copies.extend(self.copytree(self.rootConfDir, self.destConfDir))
200    self.copies.extend(self.copytree(self.archConfDir, self.destConfDir))
201
202  def installBin(self):
203    self.copies.extend(self.copytree(self.rootBinDir, self.destBinDir))
204    self.copies.extend(self.copytree(self.archBinDir, self.destBinDir))
205    return
206
207  def copyLib(self, src, dst):
208    '''Run ranlib on the destination library if it is an archive. Also run install_name_tool on dylib on Mac'''
209    shutil.copy2(src, dst)
210    if os.path.splitext(dst)[1] == '.'+self.libSuffix:
211      self.executeShellCommand(self.ranlib+' '+dst)
212    if os.path.splitext(dst)[1] == '.dylib' and os.path.isfile('/usr/bin/install_name_tool'):
213      installName = re.sub(self.destDir, self.installDir, dst)
214      self.executeShellCommand('/usr/bin/install_name_tool -id ' + installName + ' ' + dst)
215    return
216
217  def installLib(self):
218    self.copies.extend(self.copytree(self.archLibDir, self.destLibDir, copyFunc = self.copyLib))
219    return
220
221
222  def outputHelp(self):
223    print '''\
224====================================
225Install complete. It is useable with PETSC_DIR=%s [and no more PETSC_ARCH].
226Now to check if the libraries are working do (in current directory):
227make PETSC_DIR=%s test
228====================================\
229''' % (self.installDir,self.installDir)
230    return
231
232  def runfix(self):
233    self.setup()
234    self.setupDirectories()
235    self.createUninstaller()
236    self.fixConf()
237
238  def runcopy(self):
239    if os.path.exists(self.destDir) and os.path.samefile(self.destDir, os.path.join(self.rootDir,self.arch)):
240      print '********************************************************************'
241      print 'Install directory is current directory; nothing needs to be done'
242      print '********************************************************************'
243      return
244    print '*** Installing PETSc at',self.destDir, ' ***'
245    if not os.path.exists(self.destDir):
246      try:
247        os.makedirs(self.destDir)
248      except:
249        print '********************************************************************'
250        print 'Unable to create', self.destDir, 'Perhaps you need to do "sudo make install"'
251        print '********************************************************************'
252        return
253    if not os.path.isdir(os.path.realpath(self.destDir)):
254      print '********************************************************************'
255      print 'Specified destDir', self.destDir, 'is not a directory. Cannot proceed!'
256      print '********************************************************************'
257      return
258    if not os.access(self.destDir, os.W_OK):
259      print '********************************************************************'
260      print 'Unable to write to ', self.destDir, 'Perhaps you need to do "sudo make install"'
261      print '********************************************************************'
262      return
263
264    self.outputHelp()
265    self.installIncludes()
266    self.installConf()
267    self.installBin()
268    self.installLib()
269
270    return
271
272  def run(self):
273    self.runfix()
274    self.runcopy()
275
276if __name__ == '__main__':
277  Installer(sys.argv[1:]).run()
278  # temporary hack - delete log files created by BuildSystem - when 'sudo make install' is invoked
279  delfiles=['RDict.db','RDict.log','build.log','default.log','build.log.bkp','default.log.bkp']
280  for delfile in delfiles:
281    if os.path.exists(delfile) and (os.stat(delfile).st_uid==0):
282      os.remove(delfile)
283