xref: /petsc/config/BuildSystem/retrieval.py (revision 09378cb4d5d28b496e4cff5aa10db32bddd41be7)
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:
51c189a2f2SPierre Jolivet        self.tarball_urls.extend([url])
52ed0bf72bSSatish Balay
53fbfe4939SVaclav Hapla  def isDirectoryGitRepo(self, directory):
54ed0bf72bSSatish Balay    if not hasattr(self.sourceControl, 'git'):
55ed0bf72bSSatish Balay      self.logPrint('git not found in self.sourceControl - cannot evaluate isDirectoryGitRepo(): '+directory)
56ed0bf72bSSatish Balay      return False
57fbfe4939SVaclav Hapla    from config.base import Configure
58fbfe4939SVaclav Hapla    for loc in ['.git','']:
59fbfe4939SVaclav Hapla      cmd = '%s rev-parse --resolve-git-dir  %s'  % (self.sourceControl.git, os.path.join(directory,loc))
60fbfe4939SVaclav Hapla      (output, error, ret) = Configure.executeShellCommand(cmd, checkCommand = Configure.passCheckCommand, log = self.log)
61fbfe4939SVaclav Hapla      if not ret:
62fbfe4939SVaclav Hapla        return True
63fbfe4939SVaclav Hapla    return False
64fbfe4939SVaclav Hapla
65fbfe4939SVaclav Hapla  @staticmethod
66fbfe4939SVaclav Hapla  def removeTarget(t):
67fbfe4939SVaclav Hapla    if os.path.islink(t) or os.path.isfile(t):
68fbfe4939SVaclav Hapla      os.unlink(t) # same as os.remove(t)
69fbfe4939SVaclav Hapla    elif os.path.isdir(t):
70fbfe4939SVaclav Hapla      shutil.rmtree(t)
71fbfe4939SVaclav Hapla
72fbfe4939SVaclav Hapla  @staticmethod
73fbfe4939SVaclav Hapla  def getDownloadFailureMessage(package, url, filename=None):
74fbfe4939SVaclav Hapla    slashFilename = '/'+filename if filename else ''
75fbfe4939SVaclav Hapla    return '''\
76fbfe4939SVaclav HaplaUnable to download package %s from: %s
77fbfe4939SVaclav Hapla* If URL specified manually - perhaps there is a typo?
78fbfe4939SVaclav Hapla* If your network is disconnected - please reconnect and rerun ./configure
79fbfe4939SVaclav Hapla* Or perhaps you have a firewall blocking the download
80fbfe4939SVaclav Hapla* You can run with --with-packages-download-dir=/adirectory and ./configure will instruct you what packages to download manually
81fbfe4939SVaclav Hapla* or you can download the above URL manually, to /yourselectedlocation%s
82fbfe4939SVaclav Hapla  and use the configure option:
83fbfe4939SVaclav Hapla  --download-%s=/yourselectedlocation%s
84fbfe4939SVaclav Hapla    ''' % (package.upper(), url, slashFilename, package, slashFilename)
85fbfe4939SVaclav Hapla
86fbfe4939SVaclav Hapla  @staticmethod
87fbfe4939SVaclav Hapla  def removePrefix(url,prefix):
88fbfe4939SVaclav Hapla    '''Replacement for str.removeprefix() supported only since Python 3.9'''
89fbfe4939SVaclav Hapla    if url.startswith(prefix):
90fbfe4939SVaclav Hapla      return url[len(prefix):]
91fbfe4939SVaclav Hapla    return url
92fbfe4939SVaclav Hapla
93ed0bf72bSSatish Balay  def generateURLs(self):
94ed0bf72bSSatish Balay    if hasattr(self.sourceControl, 'git') and self.gitprereq:
95ed0bf72bSSatish Balay      for url in self.git_urls:
96ed0bf72bSSatish Balay        yield('git',url)
97ed0bf72bSSatish Balay    else:
98ed0bf72bSSatish Balay      self.logPrint('Git not found or gitprereq check failed! skipping giturls: '+str(self.git_urls)+'\n')
99ed0bf72bSSatish Balay    if hasattr(self.sourceControl, 'hg'):
100ed0bf72bSSatish Balay      for url in self.hg_urls:
101ed0bf72bSSatish Balay        yield('hg',url)
102ed0bf72bSSatish Balay    else:
103ed0bf72bSSatish Balay      self.logPrint('Hg not found - skipping hgurls: '+str(self.hg_urls)+'\n')
104ed0bf72bSSatish Balay    for url in self.dir_urls:
105ed0bf72bSSatish Balay      yield('dir',url)
106ed0bf72bSSatish Balay    for url in self.link_urls:
107c189a2f2SPierre Jolivet      yield('link',url)
108ed0bf72bSSatish Balay    for url in self.tarball_urls:
109ed0bf72bSSatish Balay      yield('tarball',url)
110ed0bf72bSSatish Balay
111ed0bf72bSSatish Balay  def genericRetrieve(self,proto,url,root):
112fbfe4939SVaclav Hapla    '''Fetch package from version control repository or tarfile indicated by URL and extract it into root'''
113ed0bf72bSSatish Balay    if proto == 'git':
114ed0bf72bSSatish Balay      return self.gitRetrieve(url,root)
115ed0bf72bSSatish Balay    elif proto == 'hg':
116ed0bf72bSSatish Balay      return self.hgRetrieve(url,root)
117ed0bf72bSSatish Balay    elif proto == 'dir':
118ed0bf72bSSatish Balay      return self.dirRetrieve(url,root)
119ed0bf72bSSatish Balay    elif proto == 'link':
120ed0bf72bSSatish Balay      self.linkRetrieve(url,root)
121ed0bf72bSSatish Balay    elif proto == 'tarball':
122ed0bf72bSSatish Balay      self.tarballRetrieve(url,root)
123179860b2SJed Brown
124ed0bf72bSSatish Balay  def dirRetrieve(self, url, root):
125fbfe4939SVaclav Hapla    self.logPrint('Retrieving %s as directory' % url, 3, 'install')
126ed0bf72bSSatish Balay    if not os.path.isdir(url): raise RuntimeError('URL %s is not a directory' % url)
12752df3566SBarry Smith
128ed0bf72bSSatish Balay    t = os.path.join(root,os.path.basename(url))
129fbfe4939SVaclav Hapla    self.removeTarget(t)
130ed0bf72bSSatish Balay    shutil.copytree(url,t)
13152df3566SBarry Smith
132ed0bf72bSSatish Balay  def linkRetrieve(self, url, root):
133fbfe4939SVaclav Hapla    self.logPrint('Retrieving %s as link' % url, 3, 'install')
134ed0bf72bSSatish Balay    if not os.path.isdir(url): raise RuntimeError('URL %s is not pointing to a directory' % url)
1353a911845SSatish Balay
136ed0bf72bSSatish Balay    t = os.path.join(root,os.path.basename(url))
137fbfe4939SVaclav Hapla    self.removeTarget(t)
138ed0bf72bSSatish Balay    os.symlink(os.path.abspath(url),t)
1393a911845SSatish Balay
140ed0bf72bSSatish Balay  def gitRetrieve(self, url, root):
141fbfe4939SVaclav Hapla    self.logPrint('Retrieving %s as git repo' % url, 3, 'install')
142fbfe4939SVaclav Hapla    if not hasattr(self.sourceControl, 'git'):
143fbfe4939SVaclav Hapla      raise RuntimeError('self.sourceControl.git not set')
144ed0bf72bSSatish Balay    if os.path.isdir(url) and not self.isDirectoryGitRepo(url):
145fbfe4939SVaclav Hapla      raise RuntimeError('URL %s is a directory but not a git repository' % url)
14652df3566SBarry Smith
147ed0bf72bSSatish Balay    newgitrepo = os.path.join(root,'git.'+self.packagename)
148fbfe4939SVaclav Hapla    self.removeTarget(newgitrepo)
14952df3566SBarry Smith
150b93f8388SBarry Smith    try:
1510a7c9ef6SSatish Balay      submodopt =''
152ed0bf72bSSatish Balay      for itm in self.gitsubmodules:
1530a7c9ef6SSatish Balay        submodopt += ' --recurse-submodules='+itm
154ed0bf72bSSatish Balay      config.base.Configure.executeShellCommand('%s clone %s %s %s' % (self.sourceControl.git, submodopt, url, newgitrepo), log = self.log, timeout = 120.0)
1555b6bfdb9SJed Brown    except  RuntimeError as e:
156b93f8388SBarry Smith      self.logPrint('ERROR: '+str(e))
157ed0bf72bSSatish Balay      failureMessage = self.getDownloadFailureMessage(self.packagename, url)
158*16b6c915SMatthew G. Knepley      raise RuntimeError('Unable to clone '+self.packagename+'\n'+str(e)+'\n'+failureMessage)
1595e208ef3SBarry Smith
160ed0bf72bSSatish Balay  def hgRetrieve(self, url, root):
161fbfe4939SVaclav Hapla    self.logPrint('Retrieving %s as hg repo' % url, 3, 'install')
162fbfe4939SVaclav Hapla    if not hasattr(self.sourceControl, 'hg'):
163fbfe4939SVaclav Hapla      raise RuntimeError('self.sourceControl.hg not set')
1640c3d3c20SBarry Smith
165ed0bf72bSSatish Balay    newgitrepo = os.path.join(root,'hg.'+self.packagename)
166fbfe4939SVaclav Hapla    self.removeTarget(newgitrepo)
167b93f8388SBarry Smith    try:
168ed0bf72bSSatish Balay      config.base.Configure.executeShellCommand('%s clone %s %s' % (self.sourceControl.hg, url, newgitrepo), log = self.log, timeout = 120.0)
1695b6bfdb9SJed Brown    except  RuntimeError as e:
170b93f8388SBarry Smith      self.logPrint('ERROR: '+str(e))
171ed0bf72bSSatish Balay      failureMessage = self.getDownloadFailureMessage(self.packagename, url)
172*16b6c915SMatthew G. Knepley      raise RuntimeError('Unable to clone '+self.packagename+'\n'+str(e)+'\n'+failureMessage)
1730c3d3c20SBarry Smith
174ed0bf72bSSatish Balay  def tarballRetrieve(self, url, root):
175fbfe4939SVaclav Hapla    parsed = urlparse_local.urlparse(url)
176fbfe4939SVaclav Hapla    filename = os.path.basename(parsed[2])
17715ac2963SJed Brown    localFile = os.path.join(root,'_d_'+filename)
178fbfe4939SVaclav Hapla    self.logPrint('Retrieving %s as tarball to %s' % (url,localFile) , 3, 'install')
17915ac2963SJed Brown    ext =  os.path.splitext(localFile)[1]
18015ac2963SJed Brown    if ext not in ['.bz2','.tbz','.gz','.tgz','.zip','.ZIP']:
181179860b2SJed Brown      raise RuntimeError('Unknown compression type in URL: '+ url)
18215ac2963SJed Brown
183fbfe4939SVaclav Hapla    self.removeTarget(localFile)
184fbfe4939SVaclav Hapla
185fbfe4939SVaclav Hapla    if parsed[0] == 'file' and not parsed[1]:
186fbfe4939SVaclav Hapla      url = parsed[2]
187fbfe4939SVaclav Hapla    if os.path.exists(url):
188fbfe4939SVaclav Hapla      if not os.path.isfile(url):
189fbfe4939SVaclav Hapla        raise RuntimeError('Local path exists but is not a regular file: '+ url)
190fbfe4939SVaclav Hapla      # copy local file
191fbfe4939SVaclav Hapla      shutil.copyfile(url, localFile)
192fbfe4939SVaclav Hapla    else:
193fbfe4939SVaclav Hapla      # fetch remote file
194179860b2SJed Brown      try:
19556e1c110SSatish Balay        from urllib.request import Request, urlopen
196728600e6SSatish Balay        sav_timeout = socket.getdefaulttimeout()
197728600e6SSatish Balay        socket.setdefaulttimeout(30)
19856e1c110SSatish Balay        req = Request(url)
19956e1c110SSatish Balay        req.headers['User-Agent'] = 'PetscConfigure/'+self.ver
20056e1c110SSatish Balay        with open(localFile, 'wb') as f:
20156e1c110SSatish Balay          f.write(urlopen(req).read())
202728600e6SSatish Balay        socket.setdefaulttimeout(sav_timeout)
2035b6bfdb9SJed Brown      except Exception as e:
204728600e6SSatish Balay        socket.setdefaulttimeout(sav_timeout)
205ed0bf72bSSatish Balay        failureMessage = self.getDownloadFailureMessage(self.packagename, url, filename)
206*16b6c915SMatthew G. Knepley        raise RuntimeError(str(e)+'\n'+failureMessage)
20715ac2963SJed Brown
20815ac2963SJed Brown    self.logPrint('Extracting '+localFile)
20915ac2963SJed Brown    if ext in ['.zip','.ZIP']:
21015ac2963SJed Brown      config.base.Configure.executeShellCommand('cd '+root+'; unzip '+localFile, log = self.log)
21115ac2963SJed Brown      output = config.base.Configure.executeShellCommand('cd '+root+'; zipinfo -1 '+localFile+' | head -n 1', log = self.log)
212179860b2SJed Brown      dirname = os.path.normpath(output[0].strip())
21315ac2963SJed Brown    else:
21415ac2963SJed Brown      failureMessage = '''\
21515ac2963SJed BrownDownloaded package %s from: %s is not a tarball.
21615ac2963SJed Brown[or installed python cannot process compressed files]
21715ac2963SJed Brown* If you are behind a firewall - please fix your proxy and rerun ./configure
21815ac2963SJed Brown  For example at LANL you may need to set the environmental variable http_proxy (or HTTP_PROXY?) to  http://proxyout.lanl.gov
2190aa1f76dSSatish Balay* You can run with --with-packages-download-dir=/adirectory and ./configure will instruct you what packages to download manually
220b93f8388SBarry Smith* or you can download the above URL manually, to /yourselectedlocation/%s
22115ac2963SJed Brown  and use the configure option:
22215ac2963SJed Brown  --download-%s=/yourselectedlocation/%s
223ed0bf72bSSatish Balay''' % (self.packagename.upper(), url, filename, self.packagename, filename)
22415ac2963SJed Brown      import tarfile
22515ac2963SJed Brown      try:
22615ac2963SJed Brown        tf  = tarfile.open(os.path.join(root, localFile))
2275b6bfdb9SJed Brown      except tarfile.ReadError as e:
228b95f98c7SJed Brown        raise RuntimeError(str(e)+'\n'+failureMessage)
22915ac2963SJed Brown      if not tf: raise RuntimeError(failureMessage)
2302501eaf6SSatish Balay      #git puts 'pax_global_header' as the first entry and some tar utils process this as a file
2312501eaf6SSatish Balay      firstname = tf.getnames()[0]
2322501eaf6SSatish Balay      if firstname == 'pax_global_header':
2332501eaf6SSatish Balay        firstmember = tf.getmembers()[1]
23415ac2963SJed Brown      else:
2352501eaf6SSatish Balay        firstmember = tf.getmembers()[0]
2362501eaf6SSatish Balay      # some tarfiles list packagename/ but some list packagename/filename in the first entry
2372501eaf6SSatish Balay      if firstmember.isdir():
2382501eaf6SSatish Balay        dirname = firstmember.name
2392501eaf6SSatish Balay      else:
2402501eaf6SSatish Balay        dirname = os.path.dirname(firstmember.name)
24115ac2963SJed Brown      tf.extractall(root)
24215ac2963SJed Brown      tf.close()
24315ac2963SJed Brown
24415ac2963SJed Brown    # fix file permissions for the untared tarballs.
24515ac2963SJed Brown    try:
2462501eaf6SSatish Balay      # check if 'dirname' is set'
2472501eaf6SSatish Balay      if dirname:
2483be2e2fdSJose 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)
2492501eaf6SSatish Balay      else:
2502501eaf6SSatish Balay        self.logPrintBox('WARNING: Could not determine dirname extracted by '+localFile+' to fix file permissions')
2515b6bfdb9SJed Brown    except RuntimeError as e:
25215ac2963SJed Brown      raise RuntimeError('Error changing permissions for '+dirname+' obtained from '+localFile+ ' : '+str(e))
253179860b2SJed Brown    os.unlink(localFile)
254