xref: /petsc/config/BuildSystem/retrieval.py (revision c094ef4021e955ef5f85f7d8a1bbc6ed64ba7621)
1import logger
2
3import os
4import urllib
5import urlparse
6import config.base
7import socket
8
9# Fix parsing for nonstandard schemes
10urlparse.uses_netloc.extend(['bk', 'ssh', 'svn'])
11
12class Retriever(logger.Logger):
13  def __init__(self, sourceControl, clArgs = None, argDB = None):
14    logger.Logger.__init__(self, clArgs, argDB)
15    self.sourceControl = sourceControl
16    self.stamp = None
17    return
18
19  def getAuthorizedUrl(self, url):
20    '''This returns a tuple of the unauthorized and authorized URLs for the given URL, and a flag indicating which was input'''
21    (scheme, location, path, parameters, query, fragment) = urlparse.urlparse(url)
22    if not location:
23      url     = urlparse.urlunparse(('', '', path, parameters, query, fragment))
24      authUrl = None
25      wasAuth = 0
26    else:
27      index = location.find('@')
28      if index >= 0:
29        login   = location[0:index]
30        authUrl = url
31        url     = urlparse.urlunparse((scheme, location[index+1:], path, parameters, query, fragment))
32        wasAuth = 1
33      else:
34        login   = location.split('.')[0]
35        authUrl = urlparse.urlunparse((scheme, login+'@'+location, path, parameters, query, fragment))
36        wasAuth = 0
37    return (url, authUrl, wasAuth)
38
39  def testAuthorizedUrl(self, authUrl):
40    '''Raise an exception if the URL cannot receive an SSH login without a password'''
41    if not authUrl:
42      raise RuntimeError('Url is empty')
43    (scheme, location, path, parameters, query, fragment) = urlparse.urlparse(authUrl)
44    return self.executeShellCommand('echo "quit" | ssh -oBatchMode=yes '+location)
45
46  def genericRetrieve(self, url, root, package):
47    '''Fetch the gzipped tarfile indicated by url and expand it into root
48       - All the logic for removing old versions, updating etc. must move'''
49
50    # copy a directory
51    if url.startswith('dir://'):
52      import shutil
53      dir = url[6:]
54      if not os.path.isdir(dir): raise RuntimeError('Url begins with dir:// but is not a directory')
55
56      if os.path.isdir(os.path.join(root,os.path.basename(dir))): shutil.rmtree(os.path.join(root,os.path.basename(dir)))
57      if os.path.isfile(os.path.join(root,os.path.basename(dir))): os.unlink(os.path.join(root,os.path.basename(dir)))
58
59      shutil.copytree(dir,os.path.join(root,os.path.basename(dir)))
60      return
61
62    if url.startswith('git://'):
63      if not hasattr(self.sourceControl, 'git'): return
64      import shutil
65      dir = url[6:]
66      if os.path.isdir(dir):
67        if not os.path.isdir(os.path.join(dir,'.git')): raise RuntimeError('Url begins with git:// and is a directory but but does not have a .git subdirectory')
68
69      newgitrepo = os.path.join(root,'git.'+package)
70      if os.path.isdir(newgitrepo): shutil.rmtree(newgitrepo)
71      if os.path.isfile(newgitrepo): os.unlink(newgitrepo)
72
73      config.base.Configure.executeShellCommand(self.sourceControl.git+' clone '+dir+' '+newgitrepo)
74      return
75    # get the tarball file name from the URL
76    filename = os.path.basename(urlparse.urlparse(url)[2])
77    localFile = os.path.join(root,'_d_'+filename)
78    ext =  os.path.splitext(localFile)[1]
79    if ext not in ['.bz2','.tbz','.gz','.tgz','.zip','.ZIP']:
80      raise RuntimeError('Unknown compression type in URL: '+ url)
81    self.logPrint('Downloading '+url+' to '+localFile)
82    if os.path.exists(localFile):
83      os.unlink(localFile)
84
85    try:
86      sav_timeout = socket.getdefaulttimeout()
87      socket.setdefaulttimeout(30)
88      urllib.urlretrieve(url, localFile)
89      socket.setdefaulttimeout(sav_timeout)
90    except Exception, e:
91      socket.setdefaulttimeout(sav_timeout)
92      failureMessage = '''\
93Unable to download package %s from: %s
94* If URL specified manually - perhaps there is a typo?
95* If your network is disconnected - please reconnect and rerun ./configure
96* Or perhaps you have a firewall blocking the download
97* Alternatively, you can download the above URL manually, to /yourselectedlocation/%s
98  and use the configure option:
99  --download-%s=/yourselectedlocation/%s
100''' % (package.upper(), url, filename, package, filename)
101      raise RuntimeError(failureMessage)
102
103    self.logPrint('Extracting '+localFile)
104    if ext in ['.zip','.ZIP']:
105      config.base.Configure.executeShellCommand('cd '+root+'; unzip '+localFile, log = self.log)
106      output = config.base.Configure.executeShellCommand('cd '+root+'; zipinfo -1 '+localFile+' | head -n 1', log = self.log)
107      dirname = os.path.normpath(output[0].strip())
108    else:
109      failureMessage = '''\
110Downloaded package %s from: %s is not a tarball.
111[or installed python cannot process compressed files]
112* If you are behind a firewall - please fix your proxy and rerun ./configure
113  For example at LANL you may need to set the environmental variable http_proxy (or HTTP_PROXY?) to  http://proxyout.lanl.gov
114* Alternatively, you can download the above URL manually, to /yourselectedlocation/%s
115  and use the configure option:
116  --download-%s=/yourselectedlocation/%s
117''' % (package.upper(), url, filename, package, filename)
118      import tarfile
119      try:
120        tf  = tarfile.open(os.path.join(root, localFile))
121      except tarfile.ReadError, e:
122        raise RuntimeError(str(e)+'\n'+failureMessage)
123      if not tf: raise RuntimeError(failureMessage)
124      #git puts 'pax_global_header' as the first entry and some tar utils process this as a file
125      firstname = tf.getnames()[0]
126      if firstname == 'pax_global_header':
127        firstmember = tf.getmembers()[1]
128      else:
129        firstmember = tf.getmembers()[0]
130      # some tarfiles list packagename/ but some list packagename/filename in the first entry
131      if firstmember.isdir():
132        dirname = firstmember.name
133      else:
134        dirname = os.path.dirname(firstmember.name)
135      if hasattr(tf,'extractall'): #python 2.5+
136        tf.extractall(root)
137      else:
138        for tfile in tf.getmembers():
139          tf.extract(tfile,root)
140      tf.close()
141
142    # fix file permissions for the untared tarballs.
143    try:
144      # check if 'dirname' is set'
145      if dirname:
146        config.base.Configure.executeShellCommand('cd '+root+'; chmod -R a+r '+dirname+';find  '+dirname + ' -type d -name "*" -exec chmod a+rx {} \;', log = self.log)
147      else:
148        self.logPrintBox('WARNING: Could not determine dirname extracted by '+localFile+' to fix file permissions')
149    except RuntimeError, e:
150      raise RuntimeError('Error changing permissions for '+dirname+' obtained from '+localFile+ ' : '+str(e))
151    os.unlink(localFile)
152    return
153
154  def ftpRetrieve(self, url, root, name,force):
155    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via ftp', 3, 'install')
156    return self.genericRetrieve(url, root, name)
157
158  def httpRetrieve(self, url, root, name,force):
159    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via http', 3, 'install')
160    return self.genericRetrieve(url, root, name)
161
162  def fileRetrieve(self, url, root, name,force):
163    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via cp', 3, 'install')
164    return self.genericRetrieve(url, root, name)
165
166  def svnRetrieve(self, url, root, name,force):
167    if not hasattr(self.sourceControl, 'svn'):
168      raise RuntimeError('Cannot retrieve a SVN repository since svn was not found')
169    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via svn', 3, 'install')
170    try:
171      config.base.Configure.executeShellCommand(self.sourceControl.svn+' checkout http'+url[3:]+' '+os.path.join(root, name))
172    except RuntimeError:
173      pass
174
175
176