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