xref: /petsc/config/BuildSystem/retrieval.py (revision c189a2f2c83bbf756b4cbb984a33c38cce550a3f)
15b6bfdb9SJed Brownfrom __future__ import absolute_import
2179860b2SJed Brownimport logger
3179860b2SJed Brown
4179860b2SJed Brownimport os
5e7c47bf1SJed Browntry:
6e7c47bf1SJed Brown  from urllib import urlretrieve
7e7c47bf1SJed Brownexcept ImportError:
8e7c47bf1SJed Brown  from urllib.request import urlretrieve
9e7c47bf1SJed Browntry:
108f450857SSatish Balay  import urlparse as urlparse_local # novermin
119ad79eecSSatish Balayexcept ImportError:
1227711972SSatish Balay  from urllib import parse as urlparse_local # novermin
13179860b2SJed Brownimport config.base
14728600e6SSatish Balayimport socket
15fbfe4939SVaclav Haplaimport shutil
16728600e6SSatish Balay
17179860b2SJed Brown# Fix parsing for nonstandard schemes
188f450857SSatish Balayurlparse_local.uses_netloc.extend(['bk', 'ssh', 'svn'])
19179860b2SJed Brown
20179860b2SJed Brownclass Retriever(logger.Logger):
21179860b2SJed Brown  def __init__(self, sourceControl, clArgs = None, argDB = None):
22179860b2SJed Brown    logger.Logger.__init__(self, clArgs, argDB)
23179860b2SJed Brown    self.sourceControl = sourceControl
24ed0bf72bSSatish Balay    self.gitsubmodules = []
25ed0bf72bSSatish Balay    self.gitprereq = 1
26ed0bf72bSSatish Balay    self.git_urls = []
27ed0bf72bSSatish Balay    self.hg_urls = []
28ed0bf72bSSatish Balay    self.dir_urls = []
29ed0bf72bSSatish Balay    self.link_urls = []
30ed0bf72bSSatish Balay    self.tarball_urls = []
31179860b2SJed Brown    self.stamp = None
32179860b2SJed Brown    return
33179860b2SJed Brown
34ed0bf72bSSatish Balay  def isGitURL(self, url):
35ed0bf72bSSatish Balay    parsed = urlparse_local.urlparse(url)
36ed0bf72bSSatish Balay    if (parsed[0] == 'git') or (parsed[0] == 'ssh' and parsed[2].endswith('.git')) or (parsed[0] == 'https' and parsed[2].endswith('.git')):
37ed0bf72bSSatish Balay      return True
38ed0bf72bSSatish Balay    elif os.path.isdir(url) and self.isDirectoryGitRepo(url):
39ed0bf72bSSatish Balay      return True
40ed0bf72bSSatish Balay    return False
41ed0bf72bSSatish Balay
42ed0bf72bSSatish Balay  def setupURLs(self,packagename,urls,gitsubmodules,gitprereq):
43ed0bf72bSSatish Balay    self.packagename = packagename
44ed0bf72bSSatish Balay    self.gitsubmodules = gitsubmodules
45ed0bf72bSSatish Balay    self.gitprereq = gitprereq
46ed0bf72bSSatish Balay    for url in urls:
47ed0bf72bSSatish Balay      parsed = urlparse_local.urlparse(url)
48ed0bf72bSSatish Balay      if self.isGitURL(url):
49ed0bf72bSSatish Balay        self.git_urls.append(self.removePrefix(url,'git://'))
50ed0bf72bSSatish Balay      elif parsed[0] == 'hg'or (parsed[0] == 'ssh' and parsed[1].startswith('hg@')):
51ed0bf72bSSatish Balay        self.hg_urls.append(self.removePrefix(url,'hg://'))
52ed0bf72bSSatish Balay      elif parsed[0] == 'dir' or os.path.isdir(url):
53ed0bf72bSSatish Balay        self.dir_urls.append(self.removePrefix(url,'dir://'))
54ed0bf72bSSatish Balay      elif parsed[0] == 'link':
55ed0bf72bSSatish Balay        self.link_urls.append(self.removePrefix(url,'link://'))
56ed0bf72bSSatish Balay      else:
57ed0bf72bSSatish Balay        # check for ftp.mcs.anl.gov - and use https://,www.mcs.anl.gov,ftp://
58*c189a2f2SPierre Jolivet        if url.find('ftp.mcs.anl.gov') != -1:
59ed0bf72bSSatish Balay          https_url = url.replace('http://','https://').replace('ftp://','http://')
60ed0bf72bSSatish Balay          self.tarball_urls.extend([https_url,https_url.replace('ftp.mcs.anl.gov/pub/petsc/','www.mcs.anl.gov/petsc/mirror/'),https_url.replace('https://','ftp')])
61*c189a2f2SPierre Jolivet        else:
62*c189a2f2SPierre Jolivet          self.tarball_urls.extend([url])
63ed0bf72bSSatish Balay
64fbfe4939SVaclav Hapla  def isDirectoryGitRepo(self, directory):
65ed0bf72bSSatish Balay    if not hasattr(self.sourceControl, 'git'):
66ed0bf72bSSatish Balay      self.logPrint('git not found in self.sourceControl - cannot evaluate isDirectoryGitRepo(): '+directory)
67ed0bf72bSSatish Balay      return False
68fbfe4939SVaclav Hapla    from config.base import Configure
69fbfe4939SVaclav Hapla    for loc in ['.git','']:
70fbfe4939SVaclav Hapla      cmd = '%s rev-parse --resolve-git-dir  %s'  % (self.sourceControl.git, os.path.join(directory,loc))
71fbfe4939SVaclav Hapla      (output, error, ret) = Configure.executeShellCommand(cmd, checkCommand = Configure.passCheckCommand, log = self.log)
72fbfe4939SVaclav Hapla      if not ret:
73fbfe4939SVaclav Hapla        return True
74fbfe4939SVaclav Hapla    return False
75fbfe4939SVaclav Hapla
76fbfe4939SVaclav Hapla  @staticmethod
77fbfe4939SVaclav Hapla  def removeTarget(t):
78fbfe4939SVaclav Hapla    if os.path.islink(t) or os.path.isfile(t):
79fbfe4939SVaclav Hapla      os.unlink(t) # same as os.remove(t)
80fbfe4939SVaclav Hapla    elif os.path.isdir(t):
81fbfe4939SVaclav Hapla      shutil.rmtree(t)
82fbfe4939SVaclav Hapla
83fbfe4939SVaclav Hapla  @staticmethod
84fbfe4939SVaclav Hapla  def getDownloadFailureMessage(package, url, filename=None):
85fbfe4939SVaclav Hapla    slashFilename = '/'+filename if filename else ''
86fbfe4939SVaclav Hapla    return '''\
87fbfe4939SVaclav HaplaUnable to download package %s from: %s
88fbfe4939SVaclav Hapla* If URL specified manually - perhaps there is a typo?
89fbfe4939SVaclav Hapla* If your network is disconnected - please reconnect and rerun ./configure
90fbfe4939SVaclav Hapla* Or perhaps you have a firewall blocking the download
91fbfe4939SVaclav Hapla* You can run with --with-packages-download-dir=/adirectory and ./configure will instruct you what packages to download manually
92fbfe4939SVaclav Hapla* or you can download the above URL manually, to /yourselectedlocation%s
93fbfe4939SVaclav Hapla  and use the configure option:
94fbfe4939SVaclav Hapla  --download-%s=/yourselectedlocation%s
95fbfe4939SVaclav Hapla    ''' % (package.upper(), url, slashFilename, package, slashFilename)
96fbfe4939SVaclav Hapla
97fbfe4939SVaclav Hapla  @staticmethod
98fbfe4939SVaclav Hapla  def removePrefix(url,prefix):
99fbfe4939SVaclav Hapla    '''Replacement for str.removeprefix() supported only since Python 3.9'''
100fbfe4939SVaclav Hapla    if url.startswith(prefix):
101fbfe4939SVaclav Hapla      return url[len(prefix):]
102fbfe4939SVaclav Hapla    return url
103fbfe4939SVaclav Hapla
104ed0bf72bSSatish Balay  def generateURLs(self):
105ed0bf72bSSatish Balay    if hasattr(self.sourceControl, 'git') and self.gitprereq:
106ed0bf72bSSatish Balay      for url in self.git_urls:
107ed0bf72bSSatish Balay        yield('git',url)
108ed0bf72bSSatish Balay    else:
109ed0bf72bSSatish Balay      self.logPrint('Git not found or gitprereq check failed! skipping giturls: '+str(self.git_urls)+'\n')
110ed0bf72bSSatish Balay    if hasattr(self.sourceControl, 'hg'):
111ed0bf72bSSatish Balay      for url in self.hg_urls:
112ed0bf72bSSatish Balay        yield('hg',url)
113ed0bf72bSSatish Balay    else:
114ed0bf72bSSatish Balay      self.logPrint('Hg not found - skipping hgurls: '+str(self.hg_urls)+'\n')
115ed0bf72bSSatish Balay    for url in self.dir_urls:
116ed0bf72bSSatish Balay      yield('dir',url)
117ed0bf72bSSatish Balay    for url in self.link_urls:
118*c189a2f2SPierre Jolivet      yield('link',url)
119ed0bf72bSSatish Balay    for url in self.tarball_urls:
120ed0bf72bSSatish Balay      yield('tarball',url)
121ed0bf72bSSatish Balay
122ed0bf72bSSatish Balay  def genericRetrieve(self,proto,url,root):
123fbfe4939SVaclav Hapla    '''Fetch package from version control repository or tarfile indicated by URL and extract it into root'''
124ed0bf72bSSatish Balay    if proto == 'git':
125ed0bf72bSSatish Balay      return self.gitRetrieve(url,root)
126ed0bf72bSSatish Balay    elif proto == 'hg':
127ed0bf72bSSatish Balay      return self.hgRetrieve(url,root)
128ed0bf72bSSatish Balay    elif proto == 'dir':
129ed0bf72bSSatish Balay      return self.dirRetrieve(url,root)
130ed0bf72bSSatish Balay    elif proto == 'link':
131ed0bf72bSSatish Balay      self.linkRetrieve(url,root)
132ed0bf72bSSatish Balay    elif proto == 'tarball':
133ed0bf72bSSatish Balay      self.tarballRetrieve(url,root)
134179860b2SJed Brown
135ed0bf72bSSatish Balay  def dirRetrieve(self, url, root):
136fbfe4939SVaclav Hapla    self.logPrint('Retrieving %s as directory' % url, 3, 'install')
137ed0bf72bSSatish Balay    if not os.path.isdir(url): raise RuntimeError('URL %s is not a directory' % url)
13852df3566SBarry Smith
139ed0bf72bSSatish Balay    t = os.path.join(root,os.path.basename(url))
140fbfe4939SVaclav Hapla    self.removeTarget(t)
141ed0bf72bSSatish Balay    shutil.copytree(url,t)
14252df3566SBarry Smith
143ed0bf72bSSatish Balay  def linkRetrieve(self, url, root):
144fbfe4939SVaclav Hapla    self.logPrint('Retrieving %s as link' % url, 3, 'install')
145ed0bf72bSSatish Balay    if not os.path.isdir(url): raise RuntimeError('URL %s is not pointing to a directory' % url)
1463a911845SSatish Balay
147ed0bf72bSSatish Balay    t = os.path.join(root,os.path.basename(url))
148fbfe4939SVaclav Hapla    self.removeTarget(t)
149ed0bf72bSSatish Balay    os.symlink(os.path.abspath(url),t)
1503a911845SSatish Balay
151ed0bf72bSSatish Balay  def gitRetrieve(self, url, root):
152fbfe4939SVaclav Hapla    self.logPrint('Retrieving %s as git repo' % url, 3, 'install')
153fbfe4939SVaclav Hapla    if not hasattr(self.sourceControl, 'git'):
154fbfe4939SVaclav Hapla      raise RuntimeError('self.sourceControl.git not set')
155ed0bf72bSSatish Balay    if os.path.isdir(url) and not self.isDirectoryGitRepo(url):
156fbfe4939SVaclav Hapla      raise RuntimeError('URL %s is a directory but not a git repository' % url)
15752df3566SBarry Smith
158ed0bf72bSSatish Balay    newgitrepo = os.path.join(root,'git.'+self.packagename)
159fbfe4939SVaclav Hapla    self.removeTarget(newgitrepo)
16052df3566SBarry Smith
161b93f8388SBarry Smith    try:
1620a7c9ef6SSatish Balay      submodopt =''
163ed0bf72bSSatish Balay      for itm in self.gitsubmodules:
1640a7c9ef6SSatish Balay        submodopt += ' --recurse-submodules='+itm
165ed0bf72bSSatish Balay      config.base.Configure.executeShellCommand('%s clone %s %s %s' % (self.sourceControl.git, submodopt, url, newgitrepo), log = self.log, timeout = 120.0)
1665b6bfdb9SJed Brown    except  RuntimeError as e:
167b93f8388SBarry Smith      self.logPrint('ERROR: '+str(e))
168b93f8388SBarry Smith      err = str(e)
169ed0bf72bSSatish Balay      failureMessage = self.getDownloadFailureMessage(self.packagename, url)
170ed0bf72bSSatish Balay      raise RuntimeError('Unable to clone '+self.packagename+'\n'+err+failureMessage)
1715e208ef3SBarry Smith
172ed0bf72bSSatish Balay  def hgRetrieve(self, url, root):
173fbfe4939SVaclav Hapla    self.logPrint('Retrieving %s as hg repo' % url, 3, 'install')
174fbfe4939SVaclav Hapla    if not hasattr(self.sourceControl, 'hg'):
175fbfe4939SVaclav Hapla      raise RuntimeError('self.sourceControl.hg not set')
1760c3d3c20SBarry Smith
177ed0bf72bSSatish Balay    newgitrepo = os.path.join(root,'hg.'+self.packagename)
178fbfe4939SVaclav Hapla    self.removeTarget(newgitrepo)
179b93f8388SBarry Smith    try:
180ed0bf72bSSatish Balay      config.base.Configure.executeShellCommand('%s clone %s %s' % (self.sourceControl.hg, url, newgitrepo), log = self.log, timeout = 120.0)
1815b6bfdb9SJed Brown    except  RuntimeError as e:
182b93f8388SBarry Smith      self.logPrint('ERROR: '+str(e))
183b93f8388SBarry Smith      err = str(e)
184ed0bf72bSSatish Balay      failureMessage = self.getDownloadFailureMessage(self.packagename, url)
185ed0bf72bSSatish Balay      raise RuntimeError('Unable to clone '+self.packagename+'\n'+err+failureMessage)
1860c3d3c20SBarry Smith
187ed0bf72bSSatish Balay  def tarballRetrieve(self, url, root):
188fbfe4939SVaclav Hapla    parsed = urlparse_local.urlparse(url)
189fbfe4939SVaclav Hapla    filename = os.path.basename(parsed[2])
19015ac2963SJed Brown    localFile = os.path.join(root,'_d_'+filename)
191fbfe4939SVaclav Hapla    self.logPrint('Retrieving %s as tarball to %s' % (url,localFile) , 3, 'install')
19215ac2963SJed Brown    ext =  os.path.splitext(localFile)[1]
19315ac2963SJed Brown    if ext not in ['.bz2','.tbz','.gz','.tgz','.zip','.ZIP']:
194179860b2SJed Brown      raise RuntimeError('Unknown compression type in URL: '+ url)
19515ac2963SJed Brown
196fbfe4939SVaclav Hapla    self.removeTarget(localFile)
197fbfe4939SVaclav Hapla
198fbfe4939SVaclav Hapla    if parsed[0] == 'file' and not parsed[1]:
199fbfe4939SVaclav Hapla      url = parsed[2]
200fbfe4939SVaclav Hapla    if os.path.exists(url):
201fbfe4939SVaclav Hapla      if not os.path.isfile(url):
202fbfe4939SVaclav Hapla        raise RuntimeError('Local path exists but is not a regular file: '+ url)
203fbfe4939SVaclav Hapla      # copy local file
204fbfe4939SVaclav Hapla      shutil.copyfile(url, localFile)
205fbfe4939SVaclav Hapla    else:
206fbfe4939SVaclav Hapla      # fetch remote file
207179860b2SJed Brown      try:
208728600e6SSatish Balay        sav_timeout = socket.getdefaulttimeout()
209728600e6SSatish Balay        socket.setdefaulttimeout(30)
210e7c47bf1SJed Brown        urlretrieve(url, localFile)
211728600e6SSatish Balay        socket.setdefaulttimeout(sav_timeout)
2125b6bfdb9SJed Brown      except Exception as e:
213728600e6SSatish Balay        socket.setdefaulttimeout(sav_timeout)
214ed0bf72bSSatish Balay        failureMessage = self.getDownloadFailureMessage(self.packagename, url, filename)
215179860b2SJed Brown        raise RuntimeError(failureMessage)
21615ac2963SJed Brown
21715ac2963SJed Brown    self.logPrint('Extracting '+localFile)
21815ac2963SJed Brown    if ext in ['.zip','.ZIP']:
21915ac2963SJed Brown      config.base.Configure.executeShellCommand('cd '+root+'; unzip '+localFile, log = self.log)
22015ac2963SJed Brown      output = config.base.Configure.executeShellCommand('cd '+root+'; zipinfo -1 '+localFile+' | head -n 1', log = self.log)
221179860b2SJed Brown      dirname = os.path.normpath(output[0].strip())
22215ac2963SJed Brown    else:
22315ac2963SJed Brown      failureMessage = '''\
22415ac2963SJed BrownDownloaded package %s from: %s is not a tarball.
22515ac2963SJed Brown[or installed python cannot process compressed files]
22615ac2963SJed Brown* If you are behind a firewall - please fix your proxy and rerun ./configure
22715ac2963SJed Brown  For example at LANL you may need to set the environmental variable http_proxy (or HTTP_PROXY?) to  http://proxyout.lanl.gov
2280aa1f76dSSatish Balay* You can run with --with-packages-download-dir=/adirectory and ./configure will instruct you what packages to download manually
229b93f8388SBarry Smith* or you can download the above URL manually, to /yourselectedlocation/%s
23015ac2963SJed Brown  and use the configure option:
23115ac2963SJed Brown  --download-%s=/yourselectedlocation/%s
232ed0bf72bSSatish Balay''' % (self.packagename.upper(), url, filename, self.packagename, filename)
23315ac2963SJed Brown      import tarfile
23415ac2963SJed Brown      try:
23515ac2963SJed Brown        tf  = tarfile.open(os.path.join(root, localFile))
2365b6bfdb9SJed Brown      except tarfile.ReadError as e:
237b95f98c7SJed Brown        raise RuntimeError(str(e)+'\n'+failureMessage)
23815ac2963SJed Brown      if not tf: raise RuntimeError(failureMessage)
2392501eaf6SSatish Balay      #git puts 'pax_global_header' as the first entry and some tar utils process this as a file
2402501eaf6SSatish Balay      firstname = tf.getnames()[0]
2412501eaf6SSatish Balay      if firstname == 'pax_global_header':
2422501eaf6SSatish Balay        firstmember = tf.getmembers()[1]
24315ac2963SJed Brown      else:
2442501eaf6SSatish Balay        firstmember = tf.getmembers()[0]
2452501eaf6SSatish Balay      # some tarfiles list packagename/ but some list packagename/filename in the first entry
2462501eaf6SSatish Balay      if firstmember.isdir():
2472501eaf6SSatish Balay        dirname = firstmember.name
2482501eaf6SSatish Balay      else:
2492501eaf6SSatish Balay        dirname = os.path.dirname(firstmember.name)
25015ac2963SJed Brown      tf.extractall(root)
25115ac2963SJed Brown      tf.close()
25215ac2963SJed Brown
25315ac2963SJed Brown    # fix file permissions for the untared tarballs.
25415ac2963SJed Brown    try:
2552501eaf6SSatish Balay      # check if 'dirname' is set'
2562501eaf6SSatish Balay      if dirname:
257179860b2SJed Brown        config.base.Configure.executeShellCommand('cd '+root+'; chmod -R a+r '+dirname+';find  '+dirname + ' -type d -name "*" -exec chmod a+rx {} \;', log = self.log)
2582501eaf6SSatish Balay      else:
2592501eaf6SSatish Balay        self.logPrintBox('WARNING: Could not determine dirname extracted by '+localFile+' to fix file permissions')
2605b6bfdb9SJed Brown    except RuntimeError as e:
26115ac2963SJed Brown      raise RuntimeError('Error changing permissions for '+dirname+' obtained from '+localFile+ ' : '+str(e))
262179860b2SJed Brown    os.unlink(localFile)
263