xref: /petsc/config/BuildSystem/retrieval.py (revision 6b2c4af1c65e71ae9956c63ddd07b514e626c624)
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
76    if url.startswith('ssh://hg@'):
77      if not hasattr(self.sourceControl, 'hg'): return
78
79      newgitrepo = os.path.join(root,'hg.'+package)
80      if os.path.isdir(newgitrepo): shutil.rmtree(newgitrepo)
81      if os.path.isfile(newgitrepo): os.unlink(newgitrepo)
82
83      config.base.Configure.executeShellCommand(self.sourceControl.hg+' clone '+url+' '+newgitrepo)
84      return
85
86    # get the tarball file name from the URL
87    filename = os.path.basename(urlparse.urlparse(url)[2])
88    localFile = os.path.join(root,'_d_'+filename)
89    ext =  os.path.splitext(localFile)[1]
90    if ext not in ['.bz2','.tbz','.gz','.tgz','.zip','.ZIP']:
91      raise RuntimeError('Unknown compression type in URL: '+ url)
92    self.logPrint('Downloading '+url+' to '+localFile)
93    if os.path.exists(localFile):
94      os.unlink(localFile)
95
96    try:
97      sav_timeout = socket.getdefaulttimeout()
98      socket.setdefaulttimeout(30)
99      urllib.urlretrieve(url, localFile)
100      socket.setdefaulttimeout(sav_timeout)
101    except Exception, e:
102      socket.setdefaulttimeout(sav_timeout)
103      failureMessage = '''\
104Unable to download package %s from: %s
105* If URL specified manually - perhaps there is a typo?
106* If your network is disconnected - please reconnect and rerun ./configure
107* Or perhaps you have a firewall blocking the download
108* Alternatively, you can download the above URL manually, to /yourselectedlocation/%s
109  and use the configure option:
110  --download-%s=/yourselectedlocation/%s
111''' % (package.upper(), url, filename, package, filename)
112      raise RuntimeError(failureMessage)
113
114    self.logPrint('Extracting '+localFile)
115    if ext in ['.zip','.ZIP']:
116      config.base.Configure.executeShellCommand('cd '+root+'; unzip '+localFile, log = self.log)
117      output = config.base.Configure.executeShellCommand('cd '+root+'; zipinfo -1 '+localFile+' | head -n 1', log = self.log)
118      dirname = os.path.normpath(output[0].strip())
119    else:
120      failureMessage = '''\
121Downloaded package %s from: %s is not a tarball.
122[or installed python cannot process compressed files]
123* If you are behind a firewall - please fix your proxy and rerun ./configure
124  For example at LANL you may need to set the environmental variable http_proxy (or HTTP_PROXY?) to  http://proxyout.lanl.gov
125* Alternatively, you can download the above URL manually, to /yourselectedlocation/%s
126  and use the configure option:
127  --download-%s=/yourselectedlocation/%s
128''' % (package.upper(), url, filename, package, filename)
129      import tarfile
130      try:
131        tf  = tarfile.open(os.path.join(root, localFile))
132      except tarfile.ReadError, e:
133        raise RuntimeError(str(e)+'\n'+failureMessage)
134      if not tf: raise RuntimeError(failureMessage)
135      #git puts 'pax_global_header' as the first entry and some tar utils process this as a file
136      firstname = tf.getnames()[0]
137      if firstname == 'pax_global_header':
138        firstmember = tf.getmembers()[1]
139      else:
140        firstmember = tf.getmembers()[0]
141      # some tarfiles list packagename/ but some list packagename/filename in the first entry
142      if firstmember.isdir():
143        dirname = firstmember.name
144      else:
145        dirname = os.path.dirname(firstmember.name)
146      if hasattr(tf,'extractall'): #python 2.5+
147        tf.extractall(root)
148      else:
149        for tfile in tf.getmembers():
150          tf.extract(tfile,root)
151      tf.close()
152
153    # fix file permissions for the untared tarballs.
154    try:
155      # check if 'dirname' is set'
156      if dirname:
157        config.base.Configure.executeShellCommand('cd '+root+'; chmod -R a+r '+dirname+';find  '+dirname + ' -type d -name "*" -exec chmod a+rx {} \;', log = self.log)
158      else:
159        self.logPrintBox('WARNING: Could not determine dirname extracted by '+localFile+' to fix file permissions')
160    except RuntimeError, e:
161      raise RuntimeError('Error changing permissions for '+dirname+' obtained from '+localFile+ ' : '+str(e))
162    os.unlink(localFile)
163    return
164
165  def ftpRetrieve(self, url, root, name,force):
166    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via ftp', 3, 'install')
167    return self.genericRetrieve(url, root, name)
168
169  def httpRetrieve(self, url, root, name,force):
170    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via http', 3, 'install')
171    return self.genericRetrieve(url, root, name)
172
173  def fileRetrieve(self, url, root, name,force):
174    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via cp', 3, 'install')
175    return self.genericRetrieve(url, root, name)
176
177  def svnRetrieve(self, url, root, name,force):
178    if not hasattr(self.sourceControl, 'svn'):
179      raise RuntimeError('Cannot retrieve a SVN repository since svn was not found')
180    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via svn', 3, 'install')
181    try:
182      config.base.Configure.executeShellCommand(self.sourceControl.svn+' checkout http'+url[3:]+' '+os.path.join(root, name))
183    except RuntimeError:
184      pass
185
186
187