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 11except ImportError: 12 from urllib import parse as urlparse 13import config.base 14import socket 15 16# Fix parsing for nonstandard schemes 17urlparse.uses_netloc.extend(['bk', 'ssh', 'svn']) 18 19class Retriever(logger.Logger): 20 def __init__(self, sourceControl, clArgs = None, argDB = None): 21 logger.Logger.__init__(self, clArgs, argDB) 22 self.sourceControl = sourceControl 23 self.stamp = None 24 return 25 26 def getAuthorizedUrl(self, url): 27 '''This returns a tuple of the unauthorized and authorized URLs for the given URL, and a flag indicating which was input''' 28 (scheme, location, path, parameters, query, fragment) = urlparse.urlparse(url) 29 if not location: 30 url = urlparse.urlunparse(('', '', path, parameters, query, fragment)) 31 authUrl = None 32 wasAuth = 0 33 else: 34 index = location.find('@') 35 if index >= 0: 36 login = location[0:index] 37 authUrl = url 38 url = urlparse.urlunparse((scheme, location[index+1:], path, parameters, query, fragment)) 39 wasAuth = 1 40 else: 41 login = location.split('.')[0] 42 authUrl = urlparse.urlunparse((scheme, login+'@'+location, path, parameters, query, fragment)) 43 wasAuth = 0 44 return (url, authUrl, wasAuth) 45 46 def testAuthorizedUrl(self, authUrl): 47 '''Raise an exception if the URL cannot receive an SSH login without a password''' 48 if not authUrl: 49 raise RuntimeError('Url is empty') 50 (scheme, location, path, parameters, query, fragment) = urlparse.urlparse(authUrl) 51 return self.executeShellCommand('echo "quit" | ssh -oBatchMode=yes '+location, log = self.log) 52 53 def genericRetrieve(self, url, root, package): 54 '''Fetch the gzipped tarfile indicated by url and expand it into root 55 - All the logic for removing old versions, updating etc. must move''' 56 57 # copy a directory 58 if url.startswith('dir://'): 59 import shutil 60 dir = url[6:] 61 if not os.path.isdir(dir): raise RuntimeError('Url begins with dir:// but is not a directory') 62 63 if os.path.isdir(os.path.join(root,os.path.basename(dir))): shutil.rmtree(os.path.join(root,os.path.basename(dir))) 64 if os.path.isfile(os.path.join(root,os.path.basename(dir))): os.unlink(os.path.join(root,os.path.basename(dir))) 65 66 shutil.copytree(dir,os.path.join(root,os.path.basename(dir))) 67 return 68 69 if url.startswith('git://'): 70 if not hasattr(self.sourceControl, 'git'): return 71 import shutil 72 dir = url[6:] 73 if os.path.isdir(dir): 74 if not os.path.isdir(os.path.join(dir,'.git')): raise RuntimeError('Url begins with git:// and is a directory but but does not have a .git subdirectory') 75 76 newgitrepo = os.path.join(root,'git.'+package) 77 if os.path.isdir(newgitrepo): shutil.rmtree(newgitrepo) 78 if os.path.isfile(newgitrepo): os.unlink(newgitrepo) 79 80 try: 81 config.base.Configure.executeShellCommand(self.sourceControl.git+' clone '+dir+' '+newgitrepo, log = self.log) 82 except RuntimeError as e: 83 self.logPrint('ERROR: '+str(e)) 84 err = str(e) 85 failureMessage = '''\ 86Unable to download package %s from: %s 87* If URL specified manually - perhaps there is a typo? 88* If your network is disconnected - please reconnect and rerun ./configure 89* Or perhaps you have a firewall blocking the download 90* You can run with --with-packages-download-dir=/adirectory and ./configure will instruct you what packages to download manually 91* or you can download the above URL manually, to /yourselectedlocation 92 and use the configure option: 93 --download-%s=/yourselectedlocation 94''' % (package.upper(), url, package) 95 raise RuntimeError('Unable to download '+package+'\n'+err+failureMessage) 96 return 97 98 if url.startswith('hg://'): 99 if not hasattr(self.sourceControl, 'hg'): return 100 101 newgitrepo = os.path.join(root,'hg.'+package) 102 if os.path.isdir(newgitrepo): shutil.rmtree(newgitrepo) 103 if os.path.isfile(newgitrepo): os.unlink(newgitrepo) 104 try: 105 config.base.Configure.executeShellCommand(self.sourceControl.hg+' clone '+url[5:]+' '+newgitrepo) 106 except RuntimeError as e: 107 self.logPrint('ERROR: '+str(e)) 108 err = str(e) 109 failureMessage = '''\ 110Unable to download package %s from: %s 111* If URL specified manually - perhaps there is a typo? 112* If your network is disconnected - please reconnect and rerun ./configure 113* Or perhaps you have a firewall blocking the download 114* You can run with --with-packages-download-dir=/adirectory and ./configure will instruct you what packages to download manually 115* or you can download the above URL manually, to /yourselectedlocation 116 and use the configure option: 117 --download-%s=/yourselectedlocation 118''' % (package.upper(), url, package) 119 raise RuntimeError('Unable to download '+package+'\n'+err+failureMessage) 120 return 121 122 if url.startswith('ssh://hg@'): 123 if not hasattr(self.sourceControl, 'hg'): return 124 125 newgitrepo = os.path.join(root,'hg.'+package) 126 if os.path.isdir(newgitrepo): shutil.rmtree(newgitrepo) 127 if os.path.isfile(newgitrepo): os.unlink(newgitrepo) 128 try: 129 config.base.Configure.executeShellCommand(self.sourceControl.hg+' clone '+url+' '+newgitrepo) 130 except RuntimeError as e: 131 self.logPrint('ERROR: '+str(e)) 132 err = str(e) 133 failureMessage = '''\ 134Unable to download package %s from: %s 135* If URL specified manually - perhaps there is a typo? 136* If your network is disconnected - please reconnect and rerun ./configure 137* Or perhaps you have a firewall blocking the download 138* You can run with --with-packages-download-dir=/adirectory and ./configure will instruct you what packages to download manually 139* or you can download the above URL manually, to /yourselectedlocation 140 and use the configure option: 141 --download-%s=/yourselectedlocation 142''' % (package.upper(), url, package) 143 raise RuntimeError('Unable to download '+package+'\n'+err+failureMessage) 144 return 145 146 # get the tarball file name from the URL 147 filename = os.path.basename(urlparse.urlparse(url)[2]) 148 localFile = os.path.join(root,'_d_'+filename) 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 self.logPrint('Downloading '+url+' to '+localFile) 153 if os.path.exists(localFile): 154 os.unlink(localFile) 155 156 try: 157 sav_timeout = socket.getdefaulttimeout() 158 socket.setdefaulttimeout(30) 159 urlretrieve(url, localFile) 160 socket.setdefaulttimeout(sav_timeout) 161 except Exception as e: 162 socket.setdefaulttimeout(sav_timeout) 163 failureMessage = '''\ 164Unable to download package %s from: %s 165* If URL specified manually - perhaps there is a typo? 166* If your network is disconnected - please reconnect and rerun ./configure 167* Or perhaps you have a firewall blocking the download 168* You can run with --with-packages-download-dir=/adirectory and ./configure will instruct you what packages to download manually 169* or you can download the above URL manually, to /yourselectedlocation/%s 170 and use the configure option: 171 --download-%s=/yourselectedlocation/%s 172''' % (package.upper(), url, filename, package, filename) 173 raise RuntimeError(failureMessage) 174 175 self.logPrint('Extracting '+localFile) 176 if ext in ['.zip','.ZIP']: 177 config.base.Configure.executeShellCommand('cd '+root+'; unzip '+localFile, log = self.log) 178 output = config.base.Configure.executeShellCommand('cd '+root+'; zipinfo -1 '+localFile+' | head -n 1', log = self.log) 179 dirname = os.path.normpath(output[0].strip()) 180 else: 181 failureMessage = '''\ 182Downloaded package %s from: %s is not a tarball. 183[or installed python cannot process compressed files] 184* If you are behind a firewall - please fix your proxy and rerun ./configure 185 For example at LANL you may need to set the environmental variable http_proxy (or HTTP_PROXY?) to http://proxyout.lanl.gov 186* You can run with --with-packages-download-dir=/adirectory and ./configure will instruct you what packages to download manually 187* or you can download the above URL manually, to /yourselectedlocation/%s 188 and use the configure option: 189 --download-%s=/yourselectedlocation/%s 190''' % (package.upper(), url, filename, package, filename) 191 import tarfile 192 try: 193 tf = tarfile.open(os.path.join(root, localFile)) 194 except tarfile.ReadError as e: 195 raise RuntimeError(str(e)+'\n'+failureMessage) 196 if not tf: raise RuntimeError(failureMessage) 197 #git puts 'pax_global_header' as the first entry and some tar utils process this as a file 198 firstname = tf.getnames()[0] 199 if firstname == 'pax_global_header': 200 firstmember = tf.getmembers()[1] 201 else: 202 firstmember = tf.getmembers()[0] 203 # some tarfiles list packagename/ but some list packagename/filename in the first entry 204 if firstmember.isdir(): 205 dirname = firstmember.name 206 else: 207 dirname = os.path.dirname(firstmember.name) 208 tf.extractall(root) 209 tf.close() 210 211 # fix file permissions for the untared tarballs. 212 try: 213 # check if 'dirname' is set' 214 if dirname: 215 config.base.Configure.executeShellCommand('cd '+root+'; chmod -R a+r '+dirname+';find '+dirname + ' -type d -name "*" -exec chmod a+rx {} \;', log = self.log) 216 else: 217 self.logPrintBox('WARNING: Could not determine dirname extracted by '+localFile+' to fix file permissions') 218 except RuntimeError as e: 219 raise RuntimeError('Error changing permissions for '+dirname+' obtained from '+localFile+ ' : '+str(e)) 220 os.unlink(localFile) 221 return 222 223 def ftpRetrieve(self, url, root, name,force): 224 self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via ftp', 3, 'install') 225 return self.genericRetrieve(url, root, name) 226 227 def httpRetrieve(self, url, root, name,force): 228 self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via http', 3, 'install') 229 return self.genericRetrieve(url, root, name) 230 231 def fileRetrieve(self, url, root, name,force): 232 self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via cp', 3, 'install') 233 return self.genericRetrieve(url, root, name) 234 235 def svnRetrieve(self, url, root, name,force): 236 if not hasattr(self.sourceControl, 'svn'): 237 raise RuntimeError('Cannot retrieve a SVN repository since svn was not found') 238 self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via svn', 3, 'install') 239 try: 240 config.base.Configure.executeShellCommand(self.sourceControl.svn+' checkout http'+url[3:]+' '+os.path.join(root, name), log = self.log) 241 except RuntimeError: 242 pass 243 244 245