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