xref: /petsc/config/BuildSystem/retrieval.py (revision 3be2e2fd51614bfbd789968ca6fbd36d439d7250)
15b6bfdb9SJed Brownfrom __future__ import absolute_import
2179860b2SJed Brownimport logger
3179860b2SJed Brown
4179860b2SJed Brownimport os
5df3bd252SSatish Balayfrom urllib import parse as urlparse_local
6179860b2SJed Brownimport config.base
7728600e6SSatish Balayimport socket
8fbfe4939SVaclav Haplaimport shutil
9728600e6SSatish Balay
10179860b2SJed Brown# Fix parsing for nonstandard schemes
118f450857SSatish Balayurlparse_local.uses_netloc.extend(['bk', 'ssh', 'svn'])
12179860b2SJed Brown
13179860b2SJed Brownclass Retriever(logger.Logger):
14179860b2SJed Brown  def __init__(self, sourceControl, clArgs = None, argDB = None):
15179860b2SJed Brown    logger.Logger.__init__(self, clArgs, argDB)
16179860b2SJed Brown    self.sourceControl = sourceControl
17ed0bf72bSSatish Balay    self.gitsubmodules = []
18ed0bf72bSSatish Balay    self.gitprereq = 1
19ed0bf72bSSatish Balay    self.git_urls = []
20ed0bf72bSSatish Balay    self.hg_urls = []
21ed0bf72bSSatish Balay    self.dir_urls = []
22ed0bf72bSSatish Balay    self.link_urls = []
23ed0bf72bSSatish Balay    self.tarball_urls = []
24179860b2SJed Brown    self.stamp = None
2556e1c110SSatish Balay    self.ver = 'unknown'
26179860b2SJed Brown    return
27179860b2SJed Brown
28ed0bf72bSSatish Balay  def isGitURL(self, url):
29ed0bf72bSSatish Balay    parsed = urlparse_local.urlparse(url)
30ed0bf72bSSatish Balay    if (parsed[0] == 'git') or (parsed[0] == 'ssh' and parsed[2].endswith('.git')) or (parsed[0] == 'https' and parsed[2].endswith('.git')):
31ed0bf72bSSatish Balay      return True
32ed0bf72bSSatish Balay    elif os.path.isdir(url) and self.isDirectoryGitRepo(url):
33ed0bf72bSSatish Balay      return True
34ed0bf72bSSatish Balay    return False
35ed0bf72bSSatish Balay
36ed0bf72bSSatish Balay  def setupURLs(self,packagename,urls,gitsubmodules,gitprereq):
37ed0bf72bSSatish Balay    self.packagename = packagename
38ed0bf72bSSatish Balay    self.gitsubmodules = gitsubmodules
39ed0bf72bSSatish Balay    self.gitprereq = gitprereq
40ed0bf72bSSatish Balay    for url in urls:
41ed0bf72bSSatish Balay      parsed = urlparse_local.urlparse(url)
42ed0bf72bSSatish Balay      if self.isGitURL(url):
43ed0bf72bSSatish Balay        self.git_urls.append(self.removePrefix(url,'git://'))
44ed0bf72bSSatish Balay      elif parsed[0] == 'hg'or (parsed[0] == 'ssh' and parsed[1].startswith('hg@')):
45ed0bf72bSSatish Balay        self.hg_urls.append(self.removePrefix(url,'hg://'))
46ed0bf72bSSatish Balay      elif parsed[0] == 'dir' or os.path.isdir(url):
47ed0bf72bSSatish Balay        self.dir_urls.append(self.removePrefix(url,'dir://'))
48ed0bf72bSSatish Balay      elif parsed[0] == 'link':
49ed0bf72bSSatish Balay        self.link_urls.append(self.removePrefix(url,'link://'))
50ed0bf72bSSatish Balay      else:
51ed0bf72bSSatish Balay        # check for ftp.mcs.anl.gov - and use https://,www.mcs.anl.gov,ftp://
52c189a2f2SPierre Jolivet        if url.find('ftp.mcs.anl.gov') != -1:
53ed0bf72bSSatish Balay          https_url = url.replace('http://','https://').replace('ftp://','http://')
549868c90eSBarry Smith          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://')])
55c189a2f2SPierre Jolivet        else:
56c189a2f2SPierre Jolivet          self.tarball_urls.extend([url])
57ed0bf72bSSatish Balay
58fbfe4939SVaclav Hapla  def isDirectoryGitRepo(self, directory):
59ed0bf72bSSatish Balay    if not hasattr(self.sourceControl, 'git'):
60ed0bf72bSSatish Balay      self.logPrint('git not found in self.sourceControl - cannot evaluate isDirectoryGitRepo(): '+directory)
61ed0bf72bSSatish Balay      return False
62fbfe4939SVaclav Hapla    from config.base import Configure
63fbfe4939SVaclav Hapla    for loc in ['.git','']:
64fbfe4939SVaclav Hapla      cmd = '%s rev-parse --resolve-git-dir  %s'  % (self.sourceControl.git, os.path.join(directory,loc))
65fbfe4939SVaclav Hapla      (output, error, ret) = Configure.executeShellCommand(cmd, checkCommand = Configure.passCheckCommand, log = self.log)
66fbfe4939SVaclav Hapla      if not ret:
67fbfe4939SVaclav Hapla        return True
68fbfe4939SVaclav Hapla    return False
69fbfe4939SVaclav Hapla
70fbfe4939SVaclav Hapla  @staticmethod
71fbfe4939SVaclav Hapla  def removeTarget(t):
72fbfe4939SVaclav Hapla    if os.path.islink(t) or os.path.isfile(t):
73fbfe4939SVaclav Hapla      os.unlink(t) # same as os.remove(t)
74fbfe4939SVaclav Hapla    elif os.path.isdir(t):
75fbfe4939SVaclav Hapla      shutil.rmtree(t)
76fbfe4939SVaclav Hapla
77fbfe4939SVaclav Hapla  @staticmethod
78fbfe4939SVaclav Hapla  def getDownloadFailureMessage(package, url, filename=None):
79fbfe4939SVaclav Hapla    slashFilename = '/'+filename if filename else ''
80fbfe4939SVaclav Hapla    return '''\
81fbfe4939SVaclav HaplaUnable to download package %s from: %s
82fbfe4939SVaclav Hapla* If URL specified manually - perhaps there is a typo?
83fbfe4939SVaclav Hapla* If your network is disconnected - please reconnect and rerun ./configure
84fbfe4939SVaclav Hapla* Or perhaps you have a firewall blocking the download
85fbfe4939SVaclav Hapla* You can run with --with-packages-download-dir=/adirectory and ./configure will instruct you what packages to download manually
86fbfe4939SVaclav Hapla* or you can download the above URL manually, to /yourselectedlocation%s
87fbfe4939SVaclav Hapla  and use the configure option:
88fbfe4939SVaclav Hapla  --download-%s=/yourselectedlocation%s
89fbfe4939SVaclav Hapla    ''' % (package.upper(), url, slashFilename, package, slashFilename)
90fbfe4939SVaclav Hapla
91fbfe4939SVaclav Hapla  @staticmethod
92fbfe4939SVaclav Hapla  def removePrefix(url,prefix):
93fbfe4939SVaclav Hapla    '''Replacement for str.removeprefix() supported only since Python 3.9'''
94fbfe4939SVaclav Hapla    if url.startswith(prefix):
95fbfe4939SVaclav Hapla      return url[len(prefix):]
96fbfe4939SVaclav Hapla    return url
97fbfe4939SVaclav Hapla
98ed0bf72bSSatish Balay  def generateURLs(self):
99ed0bf72bSSatish Balay    if hasattr(self.sourceControl, 'git') and self.gitprereq:
100ed0bf72bSSatish Balay      for url in self.git_urls:
101ed0bf72bSSatish Balay        yield('git',url)
102ed0bf72bSSatish Balay    else:
103ed0bf72bSSatish Balay      self.logPrint('Git not found or gitprereq check failed! skipping giturls: '+str(self.git_urls)+'\n')
104ed0bf72bSSatish Balay    if hasattr(self.sourceControl, 'hg'):
105ed0bf72bSSatish Balay      for url in self.hg_urls:
106ed0bf72bSSatish Balay        yield('hg',url)
107ed0bf72bSSatish Balay    else:
108ed0bf72bSSatish Balay      self.logPrint('Hg not found - skipping hgurls: '+str(self.hg_urls)+'\n')
109ed0bf72bSSatish Balay    for url in self.dir_urls:
110ed0bf72bSSatish Balay      yield('dir',url)
111ed0bf72bSSatish Balay    for url in self.link_urls:
112c189a2f2SPierre Jolivet      yield('link',url)
113ed0bf72bSSatish Balay    for url in self.tarball_urls:
114ed0bf72bSSatish Balay      yield('tarball',url)
115ed0bf72bSSatish Balay
116ed0bf72bSSatish Balay  def genericRetrieve(self,proto,url,root):
117fbfe4939SVaclav Hapla    '''Fetch package from version control repository or tarfile indicated by URL and extract it into root'''
118ed0bf72bSSatish Balay    if proto == 'git':
119ed0bf72bSSatish Balay      return self.gitRetrieve(url,root)
120ed0bf72bSSatish Balay    elif proto == 'hg':
121ed0bf72bSSatish Balay      return self.hgRetrieve(url,root)
122ed0bf72bSSatish Balay    elif proto == 'dir':
123ed0bf72bSSatish Balay      return self.dirRetrieve(url,root)
124ed0bf72bSSatish Balay    elif proto == 'link':
125ed0bf72bSSatish Balay      self.linkRetrieve(url,root)
126ed0bf72bSSatish Balay    elif proto == 'tarball':
127ed0bf72bSSatish Balay      self.tarballRetrieve(url,root)
128179860b2SJed Brown
129ed0bf72bSSatish Balay  def dirRetrieve(self, url, root):
130fbfe4939SVaclav Hapla    self.logPrint('Retrieving %s as directory' % url, 3, 'install')
131ed0bf72bSSatish Balay    if not os.path.isdir(url): raise RuntimeError('URL %s is not a directory' % url)
13252df3566SBarry Smith
133ed0bf72bSSatish Balay    t = os.path.join(root,os.path.basename(url))
134fbfe4939SVaclav Hapla    self.removeTarget(t)
135ed0bf72bSSatish Balay    shutil.copytree(url,t)
13652df3566SBarry Smith
137ed0bf72bSSatish Balay  def linkRetrieve(self, url, root):
138fbfe4939SVaclav Hapla    self.logPrint('Retrieving %s as link' % url, 3, 'install')
139ed0bf72bSSatish Balay    if not os.path.isdir(url): raise RuntimeError('URL %s is not pointing to a directory' % url)
1403a911845SSatish Balay
141ed0bf72bSSatish Balay    t = os.path.join(root,os.path.basename(url))
142fbfe4939SVaclav Hapla    self.removeTarget(t)
143ed0bf72bSSatish Balay    os.symlink(os.path.abspath(url),t)
1443a911845SSatish Balay
145ed0bf72bSSatish Balay  def gitRetrieve(self, url, root):
146fbfe4939SVaclav Hapla    self.logPrint('Retrieving %s as git repo' % url, 3, 'install')
147fbfe4939SVaclav Hapla    if not hasattr(self.sourceControl, 'git'):
148fbfe4939SVaclav Hapla      raise RuntimeError('self.sourceControl.git not set')
149ed0bf72bSSatish Balay    if os.path.isdir(url) and not self.isDirectoryGitRepo(url):
150fbfe4939SVaclav Hapla      raise RuntimeError('URL %s is a directory but not a git repository' % url)
15152df3566SBarry Smith
152ed0bf72bSSatish Balay    newgitrepo = os.path.join(root,'git.'+self.packagename)
153fbfe4939SVaclav Hapla    self.removeTarget(newgitrepo)
15452df3566SBarry Smith
155b93f8388SBarry Smith    try:
1560a7c9ef6SSatish Balay      submodopt =''
157ed0bf72bSSatish Balay      for itm in self.gitsubmodules:
1580a7c9ef6SSatish Balay        submodopt += ' --recurse-submodules='+itm
159ed0bf72bSSatish Balay      config.base.Configure.executeShellCommand('%s clone %s %s %s' % (self.sourceControl.git, submodopt, url, newgitrepo), log = self.log, timeout = 120.0)
1605b6bfdb9SJed Brown    except  RuntimeError as e:
161b93f8388SBarry Smith      self.logPrint('ERROR: '+str(e))
162b93f8388SBarry Smith      err = str(e)
163ed0bf72bSSatish Balay      failureMessage = self.getDownloadFailureMessage(self.packagename, url)
164ed0bf72bSSatish Balay      raise RuntimeError('Unable to clone '+self.packagename+'\n'+err+failureMessage)
1655e208ef3SBarry Smith
166ed0bf72bSSatish Balay  def hgRetrieve(self, url, root):
167fbfe4939SVaclav Hapla    self.logPrint('Retrieving %s as hg repo' % url, 3, 'install')
168fbfe4939SVaclav Hapla    if not hasattr(self.sourceControl, 'hg'):
169fbfe4939SVaclav Hapla      raise RuntimeError('self.sourceControl.hg not set')
1700c3d3c20SBarry Smith
171ed0bf72bSSatish Balay    newgitrepo = os.path.join(root,'hg.'+self.packagename)
172fbfe4939SVaclav Hapla    self.removeTarget(newgitrepo)
173b93f8388SBarry Smith    try:
174ed0bf72bSSatish Balay      config.base.Configure.executeShellCommand('%s clone %s %s' % (self.sourceControl.hg, url, newgitrepo), log = self.log, timeout = 120.0)
1755b6bfdb9SJed Brown    except  RuntimeError as e:
176b93f8388SBarry Smith      self.logPrint('ERROR: '+str(e))
177b93f8388SBarry Smith      err = str(e)
178ed0bf72bSSatish Balay      failureMessage = self.getDownloadFailureMessage(self.packagename, url)
179ed0bf72bSSatish Balay      raise RuntimeError('Unable to clone '+self.packagename+'\n'+err+failureMessage)
1800c3d3c20SBarry Smith
181ed0bf72bSSatish Balay  def tarballRetrieve(self, url, root):
182fbfe4939SVaclav Hapla    parsed = urlparse_local.urlparse(url)
183fbfe4939SVaclav Hapla    filename = os.path.basename(parsed[2])
18415ac2963SJed Brown    localFile = os.path.join(root,'_d_'+filename)
185fbfe4939SVaclav Hapla    self.logPrint('Retrieving %s as tarball to %s' % (url,localFile) , 3, 'install')
18615ac2963SJed Brown    ext =  os.path.splitext(localFile)[1]
18715ac2963SJed Brown    if ext not in ['.bz2','.tbz','.gz','.tgz','.zip','.ZIP']:
188179860b2SJed Brown      raise RuntimeError('Unknown compression type in URL: '+ url)
18915ac2963SJed Brown
190fbfe4939SVaclav Hapla    self.removeTarget(localFile)
191fbfe4939SVaclav Hapla
192fbfe4939SVaclav Hapla    if parsed[0] == 'file' and not parsed[1]:
193fbfe4939SVaclav Hapla      url = parsed[2]
194fbfe4939SVaclav Hapla    if os.path.exists(url):
195fbfe4939SVaclav Hapla      if not os.path.isfile(url):
196fbfe4939SVaclav Hapla        raise RuntimeError('Local path exists but is not a regular file: '+ url)
197fbfe4939SVaclav Hapla      # copy local file
198fbfe4939SVaclav Hapla      shutil.copyfile(url, localFile)
199fbfe4939SVaclav Hapla    else:
200fbfe4939SVaclav Hapla      # fetch remote file
201179860b2SJed Brown      try:
20256e1c110SSatish Balay        from urllib.request import Request, urlopen
203728600e6SSatish Balay        sav_timeout = socket.getdefaulttimeout()
204728600e6SSatish Balay        socket.setdefaulttimeout(30)
20556e1c110SSatish Balay        req = Request(url)
20656e1c110SSatish Balay        req.headers['User-Agent'] = 'PetscConfigure/'+self.ver
20756e1c110SSatish Balay        with open(localFile, 'wb') as f:
20856e1c110SSatish Balay          f.write(urlopen(req).read())
209728600e6SSatish Balay        socket.setdefaulttimeout(sav_timeout)
2105b6bfdb9SJed Brown      except Exception as e:
211728600e6SSatish Balay        socket.setdefaulttimeout(sav_timeout)
212ed0bf72bSSatish Balay        failureMessage = self.getDownloadFailureMessage(self.packagename, url, filename)
213179860b2SJed Brown        raise RuntimeError(failureMessage)
21415ac2963SJed Brown
21515ac2963SJed Brown    self.logPrint('Extracting '+localFile)
21615ac2963SJed Brown    if ext in ['.zip','.ZIP']:
21715ac2963SJed Brown      config.base.Configure.executeShellCommand('cd '+root+'; unzip '+localFile, log = self.log)
21815ac2963SJed Brown      output = config.base.Configure.executeShellCommand('cd '+root+'; zipinfo -1 '+localFile+' | head -n 1', log = self.log)
219179860b2SJed Brown      dirname = os.path.normpath(output[0].strip())
22015ac2963SJed Brown    else:
22115ac2963SJed Brown      failureMessage = '''\
22215ac2963SJed BrownDownloaded package %s from: %s is not a tarball.
22315ac2963SJed Brown[or installed python cannot process compressed files]
22415ac2963SJed Brown* If you are behind a firewall - please fix your proxy and rerun ./configure
22515ac2963SJed Brown  For example at LANL you may need to set the environmental variable http_proxy (or HTTP_PROXY?) to  http://proxyout.lanl.gov
2260aa1f76dSSatish Balay* You can run with --with-packages-download-dir=/adirectory and ./configure will instruct you what packages to download manually
227b93f8388SBarry Smith* or you can download the above URL manually, to /yourselectedlocation/%s
22815ac2963SJed Brown  and use the configure option:
22915ac2963SJed Brown  --download-%s=/yourselectedlocation/%s
230ed0bf72bSSatish Balay''' % (self.packagename.upper(), url, filename, self.packagename, filename)
23115ac2963SJed Brown      import tarfile
23215ac2963SJed Brown      try:
23315ac2963SJed Brown        tf  = tarfile.open(os.path.join(root, localFile))
2345b6bfdb9SJed Brown      except tarfile.ReadError as e:
235b95f98c7SJed Brown        raise RuntimeError(str(e)+'\n'+failureMessage)
23615ac2963SJed Brown      if not tf: raise RuntimeError(failureMessage)
2372501eaf6SSatish Balay      #git puts 'pax_global_header' as the first entry and some tar utils process this as a file
2382501eaf6SSatish Balay      firstname = tf.getnames()[0]
2392501eaf6SSatish Balay      if firstname == 'pax_global_header':
2402501eaf6SSatish Balay        firstmember = tf.getmembers()[1]
24115ac2963SJed Brown      else:
2422501eaf6SSatish Balay        firstmember = tf.getmembers()[0]
2432501eaf6SSatish Balay      # some tarfiles list packagename/ but some list packagename/filename in the first entry
2442501eaf6SSatish Balay      if firstmember.isdir():
2452501eaf6SSatish Balay        dirname = firstmember.name
2462501eaf6SSatish Balay      else:
2472501eaf6SSatish Balay        dirname = os.path.dirname(firstmember.name)
24815ac2963SJed Brown      tf.extractall(root)
24915ac2963SJed Brown      tf.close()
25015ac2963SJed Brown
25115ac2963SJed Brown    # fix file permissions for the untared tarballs.
25215ac2963SJed Brown    try:
2532501eaf6SSatish Balay      # check if 'dirname' is set'
2542501eaf6SSatish Balay      if dirname:
255*3be2e2fdSJose E. Roman        config.base.Configure.executeShellCommand('cd '+root+'; chmod -R a+r '+dirname+';find  '+dirname + r' -type d -name "*" -exec chmod a+rx {} \;', log = self.log)
2562501eaf6SSatish Balay      else:
2572501eaf6SSatish Balay        self.logPrintBox('WARNING: Could not determine dirname extracted by '+localFile+' to fix file permissions')
2585b6bfdb9SJed Brown    except RuntimeError as e:
25915ac2963SJed Brown      raise RuntimeError('Error changing permissions for '+dirname+' obtained from '+localFile+ ' : '+str(e))
260179860b2SJed Brown    os.unlink(localFile)
261