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 failureMessage = self.getDownloadFailureMessage(self.packagename, url) 158 raise RuntimeError('Unable to clone '+self.packagename+'\n'+str(e)+'\n'+failureMessage) 159 160 def hgRetrieve(self, url, root): 161 self.logPrint('Retrieving %s as hg repo' % url, 3, 'install') 162 if not hasattr(self.sourceControl, 'hg'): 163 raise RuntimeError('self.sourceControl.hg not set') 164 165 newgitrepo = os.path.join(root,'hg.'+self.packagename) 166 self.removeTarget(newgitrepo) 167 try: 168 config.base.Configure.executeShellCommand('%s clone %s %s' % (self.sourceControl.hg, url, newgitrepo), log = self.log, timeout = 120.0) 169 except RuntimeError as e: 170 self.logPrint('ERROR: '+str(e)) 171 failureMessage = self.getDownloadFailureMessage(self.packagename, url) 172 raise RuntimeError('Unable to clone '+self.packagename+'\n'+str(e)+'\n'+failureMessage) 173 174 def tarballRetrieve(self, url, root): 175 parsed = urlparse_local.urlparse(url) 176 filename = os.path.basename(parsed[2]) 177 localFile = os.path.join(root,'_d_'+filename) 178 self.logPrint('Retrieving %s as tarball to %s' % (url,localFile) , 3, 'install') 179 ext = os.path.splitext(localFile)[1] 180 if ext not in ['.bz2','.tbz','.gz','.tgz','.zip','.ZIP']: 181 raise RuntimeError('Unknown compression type in URL: '+ url) 182 183 self.removeTarget(localFile) 184 185 if parsed[0] == 'file' and not parsed[1]: 186 url = parsed[2] 187 if os.path.exists(url): 188 if not os.path.isfile(url): 189 raise RuntimeError('Local path exists but is not a regular file: '+ url) 190 # copy local file 191 shutil.copyfile(url, localFile) 192 else: 193 # fetch remote file 194 try: 195 from urllib.request import Request, urlopen 196 sav_timeout = socket.getdefaulttimeout() 197 socket.setdefaulttimeout(30) 198 req = Request(url) 199 req.headers['User-Agent'] = 'PetscConfigure/'+self.ver 200 with open(localFile, 'wb') as f: 201 f.write(urlopen(req).read()) 202 socket.setdefaulttimeout(sav_timeout) 203 except Exception as e: 204 socket.setdefaulttimeout(sav_timeout) 205 failureMessage = self.getDownloadFailureMessage(self.packagename, url, filename) 206 raise RuntimeError(str(e)+'\n'+failureMessage) 207 208 self.logPrint('Extracting '+localFile) 209 if ext in ['.zip','.ZIP']: 210 config.base.Configure.executeShellCommand('cd '+root+'; unzip '+localFile, log = self.log) 211 output = config.base.Configure.executeShellCommand('cd '+root+'; zipinfo -1 '+localFile+' | head -n 1', log = self.log) 212 dirname = os.path.normpath(output[0].strip()) 213 else: 214 failureMessage = '''\ 215Downloaded package %s from: %s is not a tarball. 216[or installed python cannot process compressed files] 217* If you are behind a firewall - please fix your proxy and rerun ./configure 218 For example at LANL you may need to set the environmental variable http_proxy (or HTTP_PROXY?) to http://proxyout.lanl.gov 219* You can run with --with-packages-download-dir=/adirectory and ./configure will instruct you what packages to download manually 220* or you can download the above URL manually, to /yourselectedlocation/%s 221 and use the configure option: 222 --download-%s=/yourselectedlocation/%s 223''' % (self.packagename.upper(), url, filename, self.packagename, filename) 224 import tarfile 225 try: 226 tf = tarfile.open(os.path.join(root, localFile)) 227 except tarfile.ReadError as e: 228 raise RuntimeError(str(e)+'\n'+failureMessage) 229 if not tf: raise RuntimeError(failureMessage) 230 #git puts 'pax_global_header' as the first entry and some tar utils process this as a file 231 firstname = tf.getnames()[0] 232 if firstname == 'pax_global_header': 233 firstmember = tf.getmembers()[1] 234 else: 235 firstmember = tf.getmembers()[0] 236 # some tarfiles list packagename/ but some list packagename/filename in the first entry 237 if firstmember.isdir(): 238 dirname = firstmember.name 239 else: 240 dirname = os.path.dirname(firstmember.name) 241 tf.extractall(root) 242 tf.close() 243 244 # fix file permissions for the untared tarballs. 245 try: 246 # check if 'dirname' is set' 247 if dirname: 248 config.base.Configure.executeShellCommand('cd '+root+'; chmod -R a+r '+dirname+';find '+dirname + r' -type d -name "*" -exec chmod a+rx {} \;', log = self.log) 249 else: 250 self.logPrintBox('WARNING: Could not determine dirname extracted by '+localFile+' to fix file permissions') 251 except RuntimeError as e: 252 raise RuntimeError('Error changing permissions for '+dirname+' obtained from '+localFile+ ' : '+str(e)) 253 os.unlink(localFile) 254