1from __future__ import absolute_import 2import logger 3 4import os 5from urllib import parse as urlparse_local 6import config.base 7import socket 8import shutil 9 10# Fix parsing for nonstandard schemes 11urlparse_local.uses_netloc.extend(['bk', 'ssh', 'svn']) 12 13class Retriever(logger.Logger): 14 def __init__(self, sourceControl, clArgs = None, argDB = None): 15 logger.Logger.__init__(self, clArgs, argDB) 16 self.sourceControl = sourceControl 17 self.gitsubmodules = [] 18 self.gitprereq = 1 19 self.git_urls = [] 20 self.hg_urls = [] 21 self.dir_urls = [] 22 self.link_urls = [] 23 self.tarball_urls = [] 24 self.stamp = None 25 self.ver = 'unknown' 26 return 27 28 def isGitURL(self, url): 29 parsed = urlparse_local.urlparse(url) 30 if (parsed[0] == 'git') or (parsed[0] == 'ssh' and parsed[2].endswith('.git')) or (parsed[0] == 'https' and parsed[2].endswith('.git')): 31 return True 32 elif os.path.isdir(url) and self.isDirectoryGitRepo(url): 33 return True 34 return False 35 36 def setupURLs(self,packagename,urls,gitsubmodules,gitprereq): 37 self.packagename = packagename 38 self.gitsubmodules = gitsubmodules 39 self.gitprereq = gitprereq 40 for url in urls: 41 parsed = urlparse_local.urlparse(url) 42 if self.isGitURL(url): 43 self.git_urls.append(self.removePrefix(url,'git://')) 44 elif parsed[0] == 'hg'or (parsed[0] == 'ssh' and parsed[1].startswith('hg@')): 45 self.hg_urls.append(self.removePrefix(url,'hg://')) 46 elif parsed[0] == 'dir' or os.path.isdir(url): 47 self.dir_urls.append(self.removePrefix(url,'dir://')) 48 elif parsed[0] == 'link': 49 self.link_urls.append(self.removePrefix(url,'link://')) 50 else: 51 self.tarball_urls.extend([url]) 52 53 def isDirectoryGitRepo(self, directory): 54 if not hasattr(self.sourceControl, 'git'): 55 self.logPrint('git not found in self.sourceControl - cannot evaluate isDirectoryGitRepo(): '+directory) 56 return False 57 from config.base import Configure 58 for loc in ['.git','']: 59 cmd = '%s rev-parse --resolve-git-dir %s' % (self.sourceControl.git, os.path.join(directory,loc)) 60 (output, error, ret) = Configure.executeShellCommand(cmd, checkCommand = Configure.passCheckCommand, log = self.log) 61 if not ret: 62 return True 63 return False 64 65 @staticmethod 66 def removeTarget(t): 67 if os.path.islink(t) or os.path.isfile(t): 68 os.unlink(t) # same as os.remove(t) 69 elif os.path.isdir(t): 70 shutil.rmtree(t) 71 72 @staticmethod 73 def getDownloadFailureMessage(package, url, filename=None): 74 slashFilename = '/'+filename if filename else '' 75 return '''\ 76Unable to download package %s from: %s 77* If URL specified manually - perhaps there is a typo? 78* If your network is disconnected - please reconnect and rerun ./configure 79* Or perhaps you have a firewall blocking the download 80* You can run with --with-packages-download-dir=/adirectory and ./configure will instruct you what packages to download manually 81* or you can download the above URL manually, to /yourselectedlocation%s 82 and use the configure option: 83 --download-%s=/yourselectedlocation%s 84 ''' % (package.upper(), url, slashFilename, package, slashFilename) 85 86 @staticmethod 87 def removePrefix(url,prefix): 88 '''Replacement for str.removeprefix() supported only since Python 3.9''' 89 if url.startswith(prefix): 90 return url[len(prefix):] 91 return url 92 93 def generateURLs(self): 94 if hasattr(self.sourceControl, 'git') and self.gitprereq: 95 for url in self.git_urls: 96 yield('git',url) 97 else: 98 self.logPrint('Git not found or gitprereq check failed! skipping giturls: '+str(self.git_urls)+'\n') 99 if hasattr(self.sourceControl, 'hg'): 100 for url in self.hg_urls: 101 yield('hg',url) 102 else: 103 self.logPrint('Hg not found - skipping hgurls: '+str(self.hg_urls)+'\n') 104 for url in self.dir_urls: 105 yield('dir',url) 106 for url in self.link_urls: 107 yield('link',url) 108 for url in self.tarball_urls: 109 yield('tarball',url) 110 111 def genericRetrieve(self,proto,url,root): 112 '''Fetch package from version control repository or tarfile indicated by URL and extract it into root''' 113 if proto == 'git': 114 return self.gitRetrieve(url,root) 115 elif proto == 'hg': 116 return self.hgRetrieve(url,root) 117 elif proto == 'dir': 118 return self.dirRetrieve(url,root) 119 elif proto == 'link': 120 self.linkRetrieve(url,root) 121 elif proto == 'tarball': 122 self.tarballRetrieve(url,root) 123 124 def dirRetrieve(self, url, root): 125 self.logPrint('Retrieving %s as directory' % url, 3, 'install') 126 if not os.path.isdir(url): raise RuntimeError('URL %s is not a directory' % url) 127 128 t = os.path.join(root,os.path.basename(url)) 129 self.removeTarget(t) 130 shutil.copytree(url,t) 131 132 def linkRetrieve(self, url, root): 133 self.logPrint('Retrieving %s as link' % url, 3, 'install') 134 if not os.path.isdir(url): raise RuntimeError('URL %s is not pointing to a directory' % url) 135 136 t = os.path.join(root,os.path.basename(url)) 137 self.removeTarget(t) 138 os.symlink(os.path.abspath(url),t) 139 140 def gitRetrieve(self, url, root): 141 self.logPrint('Retrieving %s as git repo' % url, 3, 'install') 142 if not hasattr(self.sourceControl, 'git'): 143 raise RuntimeError('self.sourceControl.git not set') 144 if os.path.isdir(url) and not self.isDirectoryGitRepo(url): 145 raise RuntimeError('URL %s is a directory but not a git repository' % url) 146 147 newgitrepo = os.path.join(root,'git.'+self.packagename) 148 self.removeTarget(newgitrepo) 149 150 try: 151 submodopt ='' 152 for itm in self.gitsubmodules: 153 submodopt += ' --recurse-submodules='+itm 154 config.base.Configure.executeShellCommand('%s clone %s %s %s' % (self.sourceControl.git, submodopt, url, newgitrepo), log = self.log, timeout = 120.0) 155 except RuntimeError as e: 156 self.logPrint('ERROR: '+str(e)) 157 err = str(e) 158 failureMessage = self.getDownloadFailureMessage(self.packagename, url) 159 raise RuntimeError('Unable to clone '+self.packagename+'\n'+err+failureMessage) 160 161 def hgRetrieve(self, url, root): 162 self.logPrint('Retrieving %s as hg repo' % url, 3, 'install') 163 if not hasattr(self.sourceControl, 'hg'): 164 raise RuntimeError('self.sourceControl.hg not set') 165 166 newgitrepo = os.path.join(root,'hg.'+self.packagename) 167 self.removeTarget(newgitrepo) 168 try: 169 config.base.Configure.executeShellCommand('%s clone %s %s' % (self.sourceControl.hg, url, newgitrepo), log = self.log, timeout = 120.0) 170 except RuntimeError as e: 171 self.logPrint('ERROR: '+str(e)) 172 err = str(e) 173 failureMessage = self.getDownloadFailureMessage(self.packagename, url) 174 raise RuntimeError('Unable to clone '+self.packagename+'\n'+err+failureMessage) 175 176 def tarballRetrieve(self, url, root): 177 parsed = urlparse_local.urlparse(url) 178 filename = os.path.basename(parsed[2]) 179 localFile = os.path.join(root,'_d_'+filename) 180 self.logPrint('Retrieving %s as tarball to %s' % (url,localFile) , 3, 'install') 181 ext = os.path.splitext(localFile)[1] 182 if ext not in ['.bz2','.tbz','.gz','.tgz','.zip','.ZIP']: 183 raise RuntimeError('Unknown compression type in URL: '+ url) 184 185 self.removeTarget(localFile) 186 187 if parsed[0] == 'file' and not parsed[1]: 188 url = parsed[2] 189 if os.path.exists(url): 190 if not os.path.isfile(url): 191 raise RuntimeError('Local path exists but is not a regular file: '+ url) 192 # copy local file 193 shutil.copyfile(url, localFile) 194 else: 195 # fetch remote file 196 try: 197 from urllib.request import Request, urlopen 198 sav_timeout = socket.getdefaulttimeout() 199 socket.setdefaulttimeout(30) 200 req = Request(url) 201 req.headers['User-Agent'] = 'PetscConfigure/'+self.ver 202 with open(localFile, 'wb') as f: 203 f.write(urlopen(req).read()) 204 socket.setdefaulttimeout(sav_timeout) 205 except Exception as e: 206 socket.setdefaulttimeout(sav_timeout) 207 failureMessage = self.getDownloadFailureMessage(self.packagename, url, filename) 208 raise RuntimeError(failureMessage) 209 210 self.logPrint('Extracting '+localFile) 211 if ext in ['.zip','.ZIP']: 212 config.base.Configure.executeShellCommand('cd '+root+'; unzip '+localFile, log = self.log) 213 output = config.base.Configure.executeShellCommand('cd '+root+'; zipinfo -1 '+localFile+' | head -n 1', log = self.log) 214 dirname = os.path.normpath(output[0].strip()) 215 else: 216 failureMessage = '''\ 217Downloaded package %s from: %s is not a tarball. 218[or installed python cannot process compressed files] 219* If you are behind a firewall - please fix your proxy and rerun ./configure 220 For example at LANL you may need to set the environmental variable http_proxy (or HTTP_PROXY?) to http://proxyout.lanl.gov 221* You can run with --with-packages-download-dir=/adirectory and ./configure will instruct you what packages to download manually 222* or you can download the above URL manually, to /yourselectedlocation/%s 223 and use the configure option: 224 --download-%s=/yourselectedlocation/%s 225''' % (self.packagename.upper(), url, filename, self.packagename, filename) 226 import tarfile 227 try: 228 tf = tarfile.open(os.path.join(root, localFile)) 229 except tarfile.ReadError as e: 230 raise RuntimeError(str(e)+'\n'+failureMessage) 231 if not tf: raise RuntimeError(failureMessage) 232 #git puts 'pax_global_header' as the first entry and some tar utils process this as a file 233 firstname = tf.getnames()[0] 234 if firstname == 'pax_global_header': 235 firstmember = tf.getmembers()[1] 236 else: 237 firstmember = tf.getmembers()[0] 238 # some tarfiles list packagename/ but some list packagename/filename in the first entry 239 if firstmember.isdir(): 240 dirname = firstmember.name 241 else: 242 dirname = os.path.dirname(firstmember.name) 243 tf.extractall(root) 244 tf.close() 245 246 # fix file permissions for the untared tarballs. 247 try: 248 # check if 'dirname' is set' 249 if dirname: 250 config.base.Configure.executeShellCommand('cd '+root+'; chmod -R a+r '+dirname+';find '+dirname + r' -type d -name "*" -exec chmod a+rx {} \;', log = self.log) 251 else: 252 self.logPrintBox('WARNING: Could not determine dirname extracted by '+localFile+' to fix file permissions') 253 except RuntimeError as e: 254 raise RuntimeError('Error changing permissions for '+dirname+' obtained from '+localFile+ ' : '+str(e)) 255 os.unlink(localFile) 256