xref: /petsc/config/BuildSystem/retrieval.py (revision b93f83881e0faa82a672dc02c0411c95f25e12fd)
1179860b2SJed Brownimport logger
2179860b2SJed Brown
3179860b2SJed Brownimport os
4179860b2SJed Brownimport urllib
5179860b2SJed Brownimport urlparse
6179860b2SJed Brownimport config.base
7728600e6SSatish Balayimport socket
8728600e6SSatish Balay
9179860b2SJed Brown# Fix parsing for nonstandard schemes
10179860b2SJed Brownurlparse.uses_netloc.extend(['bk', 'ssh', 'svn'])
11179860b2SJed Brown
12179860b2SJed Brownclass Retriever(logger.Logger):
13179860b2SJed Brown  def __init__(self, sourceControl, clArgs = None, argDB = None):
14179860b2SJed Brown    logger.Logger.__init__(self, clArgs, argDB)
15179860b2SJed Brown    self.sourceControl = sourceControl
16179860b2SJed Brown    self.stamp = None
17179860b2SJed Brown    return
18179860b2SJed Brown
19179860b2SJed Brown  def getAuthorizedUrl(self, url):
20179860b2SJed Brown    '''This returns a tuple of the unauthorized and authorized URLs for the given URL, and a flag indicating which was input'''
21179860b2SJed Brown    (scheme, location, path, parameters, query, fragment) = urlparse.urlparse(url)
22179860b2SJed Brown    if not location:
23179860b2SJed Brown      url     = urlparse.urlunparse(('', '', path, parameters, query, fragment))
24179860b2SJed Brown      authUrl = None
25179860b2SJed Brown      wasAuth = 0
26179860b2SJed Brown    else:
27179860b2SJed Brown      index = location.find('@')
28179860b2SJed Brown      if index >= 0:
29179860b2SJed Brown        login   = location[0:index]
30179860b2SJed Brown        authUrl = url
31179860b2SJed Brown        url     = urlparse.urlunparse((scheme, location[index+1:], path, parameters, query, fragment))
32179860b2SJed Brown        wasAuth = 1
33179860b2SJed Brown      else:
34179860b2SJed Brown        login   = location.split('.')[0]
35179860b2SJed Brown        authUrl = urlparse.urlunparse((scheme, login+'@'+location, path, parameters, query, fragment))
36179860b2SJed Brown        wasAuth = 0
37179860b2SJed Brown    return (url, authUrl, wasAuth)
38179860b2SJed Brown
39179860b2SJed Brown  def testAuthorizedUrl(self, authUrl):
40179860b2SJed Brown    '''Raise an exception if the URL cannot receive an SSH login without a password'''
41179860b2SJed Brown    if not authUrl:
42179860b2SJed Brown      raise RuntimeError('Url is empty')
43179860b2SJed Brown    (scheme, location, path, parameters, query, fragment) = urlparse.urlparse(authUrl)
441a117d15SMatthew G. Knepley    return self.executeShellCommand('echo "quit" | ssh -oBatchMode=yes '+location, log = self.log)
45179860b2SJed Brown
461aefc9f4SSatish Balay  def genericRetrieve(self, url, root, package):
47179860b2SJed Brown    '''Fetch the gzipped tarfile indicated by url and expand it into root
48179860b2SJed Brown       - All the logic for removing old versions, updating etc. must move'''
49179860b2SJed Brown
5052df3566SBarry Smith    # copy a directory
5152df3566SBarry Smith    if url.startswith('dir://'):
5252df3566SBarry Smith      import shutil
5352df3566SBarry Smith      dir = url[6:]
5452df3566SBarry Smith      if not os.path.isdir(dir): raise RuntimeError('Url begins with dir:// but is not a directory')
5552df3566SBarry Smith
5652df3566SBarry Smith      if os.path.isdir(os.path.join(root,os.path.basename(dir))): shutil.rmtree(os.path.join(root,os.path.basename(dir)))
5752df3566SBarry Smith      if os.path.isfile(os.path.join(root,os.path.basename(dir))): os.unlink(os.path.join(root,os.path.basename(dir)))
5852df3566SBarry Smith
5952df3566SBarry Smith      shutil.copytree(dir,os.path.join(root,os.path.basename(dir)))
6052df3566SBarry Smith      return
6152df3566SBarry Smith
6252df3566SBarry Smith    if url.startswith('git://'):
6352df3566SBarry Smith      if not hasattr(self.sourceControl, 'git'): return
6452df3566SBarry Smith      import shutil
6552df3566SBarry Smith      dir = url[6:]
6652df3566SBarry Smith      if os.path.isdir(dir):
6752df3566SBarry Smith        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')
6852df3566SBarry Smith
691aefc9f4SSatish Balay      newgitrepo = os.path.join(root,'git.'+package)
7052df3566SBarry Smith      if os.path.isdir(newgitrepo): shutil.rmtree(newgitrepo)
7152df3566SBarry Smith      if os.path.isfile(newgitrepo): os.unlink(newgitrepo)
7252df3566SBarry Smith
73*b93f8388SBarry Smith      try:
741a117d15SMatthew G. Knepley        config.base.Configure.executeShellCommand(self.sourceControl.git+' clone '+dir+' '+newgitrepo, log = self.log)
75*b93f8388SBarry Smith      except  RuntimeError, e:
76*b93f8388SBarry Smith        self.logPrint('ERROR: '+str(e))
77*b93f8388SBarry Smith        err = str(e)
78*b93f8388SBarry Smith        failureMessage = '''\
79*b93f8388SBarry SmithUnable to download package %s from: %s
80*b93f8388SBarry Smith* If URL specified manually - perhaps there is a typo?
81*b93f8388SBarry Smith* If your network is disconnected - please reconnect and rerun ./configure
82*b93f8388SBarry Smith* Or perhaps you have a firewall blocking the download
83*b93f8388SBarry Smith* You can run with --with-packages-dir=/adirectory and ./configure will instruct you what packages to download manually
84*b93f8388SBarry Smith* or you can download the above URL manually, to /yourselectedlocation
85*b93f8388SBarry Smith  and use the configure option:
86*b93f8388SBarry Smith  --download-%s=/yourselectedlocation
87*b93f8388SBarry Smith''' % (package.upper(), url, package)
88*b93f8388SBarry Smith        raise RuntimeError('Unable to download '+package+'\n'+err+failureMessage)
8952df3566SBarry Smith      return
905e208ef3SBarry Smith
910c3d3c20SBarry Smith    if url.startswith('hg://'):
920c3d3c20SBarry Smith      if not hasattr(self.sourceControl, 'hg'): return
930c3d3c20SBarry Smith
940c3d3c20SBarry Smith      newgitrepo = os.path.join(root,'hg.'+package)
950c3d3c20SBarry Smith      if os.path.isdir(newgitrepo): shutil.rmtree(newgitrepo)
960c3d3c20SBarry Smith      if os.path.isfile(newgitrepo): os.unlink(newgitrepo)
97*b93f8388SBarry Smith      try:
980c3d3c20SBarry Smith        config.base.Configure.executeShellCommand(self.sourceControl.hg+' clone '+url[5:]+' '+newgitrepo)
99*b93f8388SBarry Smith      except  RuntimeError, e:
100*b93f8388SBarry Smith        self.logPrint('ERROR: '+str(e))
101*b93f8388SBarry Smith        err = str(e)
102*b93f8388SBarry Smith        failureMessage = '''\
103*b93f8388SBarry SmithUnable to download package %s from: %s
104*b93f8388SBarry Smith* If URL specified manually - perhaps there is a typo?
105*b93f8388SBarry Smith* If your network is disconnected - please reconnect and rerun ./configure
106*b93f8388SBarry Smith* Or perhaps you have a firewall blocking the download
107*b93f8388SBarry Smith* You can run with --with-packages-dir=/adirectory and ./configure will instruct you what packages to download manually
108*b93f8388SBarry Smith* or you can download the above URL manually, to /yourselectedlocation
109*b93f8388SBarry Smith  and use the configure option:
110*b93f8388SBarry Smith  --download-%s=/yourselectedlocation
111*b93f8388SBarry Smith''' % (package.upper(), url, package)
112*b93f8388SBarry Smith        raise RuntimeError('Unable to download '+package+'\n'+err+failureMessage)
1130c3d3c20SBarry Smith      return
1140c3d3c20SBarry Smith
1155e208ef3SBarry Smith    if url.startswith('ssh://hg@'):
1165e208ef3SBarry Smith      if not hasattr(self.sourceControl, 'hg'): return
1175e208ef3SBarry Smith
1185e208ef3SBarry Smith      newgitrepo = os.path.join(root,'hg.'+package)
1195e208ef3SBarry Smith      if os.path.isdir(newgitrepo): shutil.rmtree(newgitrepo)
1205e208ef3SBarry Smith      if os.path.isfile(newgitrepo): os.unlink(newgitrepo)
121*b93f8388SBarry Smith      try:
1225e208ef3SBarry Smith        config.base.Configure.executeShellCommand(self.sourceControl.hg+' clone '+url+' '+newgitrepo)
123*b93f8388SBarry Smith      except  RuntimeError, e:
124*b93f8388SBarry Smith        self.logPrint('ERROR: '+str(e))
125*b93f8388SBarry Smith        err = str(e)
126*b93f8388SBarry Smith        failureMessage = '''\
127*b93f8388SBarry SmithUnable to download package %s from: %s
128*b93f8388SBarry Smith* If URL specified manually - perhaps there is a typo?
129*b93f8388SBarry Smith* If your network is disconnected - please reconnect and rerun ./configure
130*b93f8388SBarry Smith* Or perhaps you have a firewall blocking the download
131*b93f8388SBarry Smith* You can run with --with-packages-dir=/adirectory and ./configure will instruct you what packages to download manually
132*b93f8388SBarry Smith* or you can download the above URL manually, to /yourselectedlocation
133*b93f8388SBarry Smith  and use the configure option:
134*b93f8388SBarry Smith  --download-%s=/yourselectedlocation
135*b93f8388SBarry Smith''' % (package.upper(), url, package)
136*b93f8388SBarry Smith        raise RuntimeError('Unable to download '+package+'\n'+err+failureMessage)
1375e208ef3SBarry Smith      return
1385e208ef3SBarry Smith
13915ac2963SJed Brown    # get the tarball file name from the URL
14015ac2963SJed Brown    filename = os.path.basename(urlparse.urlparse(url)[2])
14115ac2963SJed Brown    localFile = os.path.join(root,'_d_'+filename)
14215ac2963SJed Brown    ext =  os.path.splitext(localFile)[1]
14315ac2963SJed Brown    if ext not in ['.bz2','.tbz','.gz','.tgz','.zip','.ZIP']:
144179860b2SJed Brown      raise RuntimeError('Unknown compression type in URL: '+ url)
145179860b2SJed Brown    self.logPrint('Downloading '+url+' to '+localFile)
146179860b2SJed Brown    if os.path.exists(localFile):
14715ac2963SJed Brown      os.unlink(localFile)
14815ac2963SJed Brown
149179860b2SJed Brown    try:
150728600e6SSatish Balay      sav_timeout = socket.getdefaulttimeout()
151728600e6SSatish Balay      socket.setdefaulttimeout(30)
152179860b2SJed Brown      urllib.urlretrieve(url, localFile)
153728600e6SSatish Balay      socket.setdefaulttimeout(sav_timeout)
154179860b2SJed Brown    except Exception, e:
155728600e6SSatish Balay      socket.setdefaulttimeout(sav_timeout)
156179860b2SJed Brown      failureMessage = '''\
157179860b2SJed BrownUnable to download package %s from: %s
158179860b2SJed Brown* If URL specified manually - perhaps there is a typo?
159179860b2SJed Brown* If your network is disconnected - please reconnect and rerun ./configure
16015ac2963SJed Brown* Or perhaps you have a firewall blocking the download
161*b93f8388SBarry Smith* You can run with --with-packages-dir=/adirectory and ./configure will instruct you what packages to download manually
162*b93f8388SBarry Smith* or you can download the above URL manually, to /yourselectedlocation/%s
163179860b2SJed Brown  and use the configure option:
164179860b2SJed Brown  --download-%s=/yourselectedlocation/%s
1651aefc9f4SSatish Balay''' % (package.upper(), url, filename, package, filename)
166179860b2SJed Brown      raise RuntimeError(failureMessage)
16715ac2963SJed Brown
16815ac2963SJed Brown    self.logPrint('Extracting '+localFile)
16915ac2963SJed Brown    if ext in ['.zip','.ZIP']:
17015ac2963SJed Brown      config.base.Configure.executeShellCommand('cd '+root+'; unzip '+localFile, log = self.log)
17115ac2963SJed Brown      output = config.base.Configure.executeShellCommand('cd '+root+'; zipinfo -1 '+localFile+' | head -n 1', log = self.log)
172179860b2SJed Brown      dirname = os.path.normpath(output[0].strip())
17315ac2963SJed Brown    else:
17415ac2963SJed Brown      failureMessage = '''\
17515ac2963SJed BrownDownloaded package %s from: %s is not a tarball.
17615ac2963SJed Brown[or installed python cannot process compressed files]
17715ac2963SJed Brown* If you are behind a firewall - please fix your proxy and rerun ./configure
17815ac2963SJed Brown  For example at LANL you may need to set the environmental variable http_proxy (or HTTP_PROXY?) to  http://proxyout.lanl.gov
179*b93f8388SBarry Smith* You can run with --with-packages-dir=/adirectory and ./configure will instruct you what packages to download manually
180*b93f8388SBarry Smith* or you can download the above URL manually, to /yourselectedlocation/%s
18115ac2963SJed Brown  and use the configure option:
18215ac2963SJed Brown  --download-%s=/yourselectedlocation/%s
1831aefc9f4SSatish Balay''' % (package.upper(), url, filename, package, filename)
18415ac2963SJed Brown      import tarfile
18515ac2963SJed Brown      try:
18615ac2963SJed Brown        tf  = tarfile.open(os.path.join(root, localFile))
187b95f98c7SJed Brown      except tarfile.ReadError, e:
188b95f98c7SJed Brown        raise RuntimeError(str(e)+'\n'+failureMessage)
18915ac2963SJed Brown      if not tf: raise RuntimeError(failureMessage)
1902501eaf6SSatish Balay      #git puts 'pax_global_header' as the first entry and some tar utils process this as a file
1912501eaf6SSatish Balay      firstname = tf.getnames()[0]
1922501eaf6SSatish Balay      if firstname == 'pax_global_header':
1932501eaf6SSatish Balay        firstmember = tf.getmembers()[1]
19415ac2963SJed Brown      else:
1952501eaf6SSatish Balay        firstmember = tf.getmembers()[0]
1962501eaf6SSatish Balay      # some tarfiles list packagename/ but some list packagename/filename in the first entry
1972501eaf6SSatish Balay      if firstmember.isdir():
1982501eaf6SSatish Balay        dirname = firstmember.name
1992501eaf6SSatish Balay      else:
2002501eaf6SSatish Balay        dirname = os.path.dirname(firstmember.name)
20115ac2963SJed Brown      if hasattr(tf,'extractall'): #python 2.5+
20215ac2963SJed Brown        tf.extractall(root)
20315ac2963SJed Brown      else:
20415ac2963SJed Brown        for tfile in tf.getmembers():
20515ac2963SJed Brown          tf.extract(tfile,root)
20615ac2963SJed Brown      tf.close()
20715ac2963SJed Brown
20815ac2963SJed Brown    # fix file permissions for the untared tarballs.
20915ac2963SJed Brown    try:
2102501eaf6SSatish Balay      # check if 'dirname' is set'
2112501eaf6SSatish Balay      if dirname:
212179860b2SJed Brown        config.base.Configure.executeShellCommand('cd '+root+'; chmod -R a+r '+dirname+';find  '+dirname + ' -type d -name "*" -exec chmod a+rx {} \;', log = self.log)
2132501eaf6SSatish Balay      else:
2142501eaf6SSatish Balay        self.logPrintBox('WARNING: Could not determine dirname extracted by '+localFile+' to fix file permissions')
215179860b2SJed Brown    except RuntimeError, e:
21615ac2963SJed Brown      raise RuntimeError('Error changing permissions for '+dirname+' obtained from '+localFile+ ' : '+str(e))
217179860b2SJed Brown    os.unlink(localFile)
218179860b2SJed Brown    return
219179860b2SJed Brown
220179860b2SJed Brown  def ftpRetrieve(self, url, root, name,force):
221179860b2SJed Brown    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via ftp', 3, 'install')
222179860b2SJed Brown    return self.genericRetrieve(url, root, name)
223179860b2SJed Brown
224179860b2SJed Brown  def httpRetrieve(self, url, root, name,force):
225179860b2SJed Brown    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via http', 3, 'install')
226179860b2SJed Brown    return self.genericRetrieve(url, root, name)
227179860b2SJed Brown
228179860b2SJed Brown  def fileRetrieve(self, url, root, name,force):
229179860b2SJed Brown    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via cp', 3, 'install')
230179860b2SJed Brown    return self.genericRetrieve(url, root, name)
231179860b2SJed Brown
232179860b2SJed Brown  def svnRetrieve(self, url, root, name,force):
233179860b2SJed Brown    if not hasattr(self.sourceControl, 'svn'):
234179860b2SJed Brown      raise RuntimeError('Cannot retrieve a SVN repository since svn was not found')
235179860b2SJed Brown    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via svn', 3, 'install')
236179860b2SJed Brown    try:
2371a117d15SMatthew G. Knepley      config.base.Configure.executeShellCommand(self.sourceControl.svn+' checkout http'+url[3:]+' '+os.path.join(root, name), log = self.log)
238179860b2SJed Brown    except RuntimeError:
239179860b2SJed Brown      pass
240179860b2SJed Brown
241179860b2SJed Brown
242