xref: /petsc/config/BuildSystem/retrieval.py (revision b95f98c77ef145c0580cb4aa7360ea673accf953)
1179860b2SJed Brownimport logger
2179860b2SJed Brown
3179860b2SJed Brownimport os
4179860b2SJed Brownimport urllib
5179860b2SJed Brownimport urlparse
6179860b2SJed Brownimport config.base
7179860b2SJed Brown# Fix parsing for nonstandard schemes
8179860b2SJed Brownurlparse.uses_netloc.extend(['bk', 'ssh', 'svn'])
9179860b2SJed Brown
10179860b2SJed Brownclass Retriever(logger.Logger):
11179860b2SJed Brown  def __init__(self, sourceControl, clArgs = None, argDB = None):
12179860b2SJed Brown    logger.Logger.__init__(self, clArgs, argDB)
13179860b2SJed Brown    self.sourceControl = sourceControl
14179860b2SJed Brown    self.stamp = None
15179860b2SJed Brown    return
16179860b2SJed Brown
17179860b2SJed Brown  def getAuthorizedUrl(self, url):
18179860b2SJed Brown    '''This returns a tuple of the unauthorized and authorized URLs for the given URL, and a flag indicating which was input'''
19179860b2SJed Brown    (scheme, location, path, parameters, query, fragment) = urlparse.urlparse(url)
20179860b2SJed Brown    if not location:
21179860b2SJed Brown      url     = urlparse.urlunparse(('', '', path, parameters, query, fragment))
22179860b2SJed Brown      authUrl = None
23179860b2SJed Brown      wasAuth = 0
24179860b2SJed Brown    else:
25179860b2SJed Brown      index = location.find('@')
26179860b2SJed Brown      if index >= 0:
27179860b2SJed Brown        login   = location[0:index]
28179860b2SJed Brown        authUrl = url
29179860b2SJed Brown        url     = urlparse.urlunparse((scheme, location[index+1:], path, parameters, query, fragment))
30179860b2SJed Brown        wasAuth = 1
31179860b2SJed Brown      else:
32179860b2SJed Brown        login   = location.split('.')[0]
33179860b2SJed Brown        authUrl = urlparse.urlunparse((scheme, login+'@'+location, path, parameters, query, fragment))
34179860b2SJed Brown        wasAuth = 0
35179860b2SJed Brown    return (url, authUrl, wasAuth)
36179860b2SJed Brown
37179860b2SJed Brown  def testAuthorizedUrl(self, authUrl):
38179860b2SJed Brown    '''Raise an exception if the URL cannot receive an SSH login without a password'''
39179860b2SJed Brown    if not authUrl:
40179860b2SJed Brown      raise RuntimeError('Url is empty')
41179860b2SJed Brown    (scheme, location, path, parameters, query, fragment) = urlparse.urlparse(authUrl)
42179860b2SJed Brown    return self.executeShellCommand('echo "quit" | ssh -oBatchMode=yes '+location)
43179860b2SJed Brown
44179860b2SJed Brown  def genericRetrieve(self, url, root, name):
45179860b2SJed Brown    '''Fetch the gzipped tarfile indicated by url and expand it into root
46179860b2SJed Brown       - All the logic for removing old versions, updating etc. must move'''
47179860b2SJed Brown
4815ac2963SJed Brown    # get the tarball file name from the URL
4915ac2963SJed Brown    filename = os.path.basename(urlparse.urlparse(url)[2])
5015ac2963SJed Brown    localFile = os.path.join(root,'_d_'+filename)
5115ac2963SJed Brown    ext =  os.path.splitext(localFile)[1]
5215ac2963SJed Brown    if ext not in ['.bz2','.tbz','.gz','.tgz','.zip','.ZIP']:
53179860b2SJed Brown      raise RuntimeError('Unknown compression type in URL: '+ url)
54179860b2SJed Brown    self.logPrint('Downloading '+url+' to '+localFile)
55179860b2SJed Brown    if os.path.exists(localFile):
5615ac2963SJed Brown      os.unlink(localFile)
5715ac2963SJed Brown
58179860b2SJed Brown    try:
59179860b2SJed Brown      urllib.urlretrieve(url, localFile)
60179860b2SJed Brown    except Exception, e:
61179860b2SJed Brown      failureMessage = '''\
62179860b2SJed BrownUnable to download package %s from: %s
63179860b2SJed Brown* If URL specified manually - perhaps there is a typo?
64179860b2SJed Brown* If your network is disconnected - please reconnect and rerun ./configure
6515ac2963SJed Brown* Or perhaps you have a firewall blocking the download
66179860b2SJed Brown* Alternatively, you can download the above URL manually, to /yourselectedlocation/%s
67179860b2SJed Brown  and use the configure option:
68179860b2SJed Brown  --download-%s=/yourselectedlocation/%s
69179860b2SJed Brown''' % (name, url, filename, name.lower(), filename)
70179860b2SJed Brown      raise RuntimeError(failureMessage)
7115ac2963SJed Brown
7215ac2963SJed Brown    self.logPrint('Extracting '+localFile)
7315ac2963SJed Brown    if ext in ['.zip','.ZIP']:
7415ac2963SJed Brown      config.base.Configure.executeShellCommand('cd '+root+'; unzip '+localFile, log = self.log)
7515ac2963SJed Brown      output = config.base.Configure.executeShellCommand('cd '+root+'; zipinfo -1 '+localFile+' | head -n 1', log = self.log)
76179860b2SJed Brown      dirname = os.path.normpath(output[0].strip())
7715ac2963SJed Brown    else:
7815ac2963SJed Brown      failureMessage = '''\
7915ac2963SJed BrownDownloaded package %s from: %s is not a tarball.
8015ac2963SJed Brown[or installed python cannot process compressed files]
8115ac2963SJed Brown* If you are behind a firewall - please fix your proxy and rerun ./configure
8215ac2963SJed Brown  For example at LANL you may need to set the environmental variable http_proxy (or HTTP_PROXY?) to  http://proxyout.lanl.gov
8315ac2963SJed Brown* Alternatively, you can download the above URL manually, to /yourselectedlocation/%s
8415ac2963SJed Brown  and use the configure option:
8515ac2963SJed Brown  --download-%s=/yourselectedlocation/%s
8615ac2963SJed Brown''' % (name, url, filename, name.lower(), filename)
8715ac2963SJed Brown      import tarfile
8815ac2963SJed Brown      try:
8915ac2963SJed Brown        tf  = tarfile.open(os.path.join(root, localFile))
90*b95f98c7SJed Brown      except tarfile.ReadError, e:
91*b95f98c7SJed Brown        raise RuntimeError(str(e)+'\n'+failureMessage)
9215ac2963SJed Brown      # some tarfiles list packagename/ but some list packagename/filename in the first entry
9315ac2963SJed Brown      if not tf: raise RuntimeError(failureMessage)
9415ac2963SJed Brown      if not tf.firstmember: raise RuntimeError(failureMessage)
9515ac2963SJed Brown      if tf.firstmember.isdir():
9615ac2963SJed Brown        dirname = tf.firstmember.name
9715ac2963SJed Brown      else:
9815ac2963SJed Brown        dirname = os.path.dirname(tf.firstmember.name)
9915ac2963SJed Brown      if hasattr(tf,'extractall'): #python 2.5+
10015ac2963SJed Brown        tf.extractall(root)
10115ac2963SJed Brown      else:
10215ac2963SJed Brown        for tfile in tf.getmembers():
10315ac2963SJed Brown          tf.extract(tfile,root)
10415ac2963SJed Brown      tf.close()
10515ac2963SJed Brown
10615ac2963SJed Brown    # fix file permissions for the untared tarballs.
10715ac2963SJed Brown    try:
108179860b2SJed Brown      config.base.Configure.executeShellCommand('cd '+root+'; chmod -R a+r '+dirname+';find  '+dirname + ' -type d -name "*" -exec chmod a+rx {} \;', log = self.log)
109179860b2SJed Brown    except RuntimeError, e:
11015ac2963SJed Brown      raise RuntimeError('Error changing permissions for '+dirname+' obtained from '+localFile+ ' : '+str(e))
111179860b2SJed Brown    os.unlink(localFile)
112179860b2SJed Brown    return
113179860b2SJed Brown
114179860b2SJed Brown  def ftpRetrieve(self, url, root, name,force):
115179860b2SJed Brown    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via ftp', 3, 'install')
116179860b2SJed Brown    return self.genericRetrieve(url, root, name)
117179860b2SJed Brown
118179860b2SJed Brown  def httpRetrieve(self, url, root, name,force):
119179860b2SJed Brown    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via http', 3, 'install')
120179860b2SJed Brown    return self.genericRetrieve(url, root, name)
121179860b2SJed Brown
122179860b2SJed Brown  def fileRetrieve(self, url, root, name,force):
123179860b2SJed Brown    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via cp', 3, 'install')
124179860b2SJed Brown    return self.genericRetrieve(url, root, name)
125179860b2SJed Brown
126179860b2SJed Brown  def svnRetrieve(self, url, root, name,force):
127179860b2SJed Brown    if not hasattr(self.sourceControl, 'svn'):
128179860b2SJed Brown      raise RuntimeError('Cannot retrieve a SVN repository since svn was not found')
129179860b2SJed Brown    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via svn', 3, 'install')
130179860b2SJed Brown    try:
131179860b2SJed Brown      config.base.Configure.executeShellCommand(self.sourceControl.svn+' checkout http'+url[3:]+' '+os.path.join(root, name))
132179860b2SJed Brown    except RuntimeError:
133179860b2SJed Brown      pass
134179860b2SJed Brown
135179860b2SJed Brown
136179860b2SJed Brown  # This is the old code for updating a BK repository
137179860b2SJed Brown  # Stamp used to be stored with a url
138179860b2SJed Brown  def bkUpdate(self):
139179860b2SJed Brown    if not self.stamp is None and url in self.stamp:
140179860b2SJed Brown      if not self.stamp[url] == self.bkHeadRevision(root):
141179860b2SJed Brown        raise RuntimeError('Existing stamp for '+url+' does not match revision of repository in '+root)
142179860b2SJed Brown    (url, authUrl, wasAuth) = self.getAuthorizedUrl(self.getBKParentURL(root))
143179860b2SJed Brown    if not wasAuth:
144179860b2SJed Brown      self.debugPrint('Changing parent from '+url+' --> '+authUrl, 1, 'install')
145179860b2SJed Brown      output = self.executeShellCommand('cd '+root+'; bk parent '+authUrl)
146179860b2SJed Brown    try:
147179860b2SJed Brown      self.testAuthorizedUrl(authUrl)
148179860b2SJed Brown      output = self.executeShellCommand('cd '+root+'; bk pull')
149179860b2SJed Brown    except RuntimeError, e:
150179860b2SJed Brown      (url, authUrl, wasAuth) = self.getAuthorizedUrl(self.getBKParentURL(root))
151179860b2SJed Brown      if wasAuth:
152179860b2SJed Brown        self.debugPrint('Changing parent from '+authUrl+' --> '+url, 1, 'install')
153179860b2SJed Brown        output = self.executeShellCommand('cd '+root+'; bk parent '+url)
154179860b2SJed Brown        output = self.executeShellCommand('cd '+root+'; bk pull')
155179860b2SJed Brown      else:
156179860b2SJed Brown        raise e
157179860b2SJed Brown    return
158179860b2SJed Brown
159179860b2SJed Brown  def bkClone(self, url, root, name):
160179860b2SJed Brown    '''Clone a Bitkeeper repository located at url into root/name
161179860b2SJed Brown       - If self.stamp exists, clone only up to that revision'''
162179860b2SJed Brown    failureMessage = '''\
163179860b2SJed BrownUnable to bk clone %s
164179860b2SJed BrownYou may be off the network. Connect to the internet and run ./configure again
165179860b2SJed Brownor from the directory %s try:
166179860b2SJed Brown  bk clone %s
167179860b2SJed Brownand if that succeeds then rerun ./configure
168179860b2SJed Brown''' % (name, root, url, name)
169179860b2SJed Brown    try:
170179860b2SJed Brown      if not self.stamp is None and url in self.stamp:
171179860b2SJed Brown        (output, error, status) = self.executeShellCommand('bk clone -r'+self.stamp[url]+' '+url+' '+os.path.join(root, name))
172179860b2SJed Brown      else:
173179860b2SJed Brown        (output, error, status) = self.executeShellCommand('bk clone '+url+' '+os.path.join(root, name))
174179860b2SJed Brown    except RuntimeError, e:
175179860b2SJed Brown      status = 1
176179860b2SJed Brown      output = str(e)
177179860b2SJed Brown      error  = ''
178179860b2SJed Brown    if status:
179179860b2SJed Brown      if output.find('ommand not found') >= 0:
180179860b2SJed Brown        failureMessage = 'Unable to locate bk (Bitkeeper) to download repository; make sure bk is in your path'
181179860b2SJed Brown      elif output.find('Cannot resolve host') >= 0:
182179860b2SJed Brown        failureMessage = output+'\n'+error+'\n'+failureMessage
183179860b2SJed Brown      else:
184179860b2SJed Brown        (scheme, location, path, parameters, query, fragment) = urlparse.urlparse(url)
185179860b2SJed Brown        try:
186179860b2SJed Brown          self.bkClone(urlparse.urlunparse(('http', location, path, parameters, query, fragment)), root, name)
187179860b2SJed Brown        except RuntimeError, e:
188179860b2SJed Brown          failureMessage += '\n'+str(e)
189179860b2SJed Brown        else:
190179860b2SJed Brown          return
191179860b2SJed Brown      raise RuntimeError(failureMessage)
192179860b2SJed Brown    return
193179860b2SJed Brown
194179860b2SJed Brown  def bkRetrieve(self, url, root, name):
195179860b2SJed Brown    if not hasattr(self.sourceControl, 'bk'):
196179860b2SJed Brown      raise RuntimeError('Cannot retrieve a BitKeeper repository since BK was not found')
197179860b2SJed Brown    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via bk', 3, 'install')
198179860b2SJed Brown    (url, authUrl, wasAuth) = self.getAuthorizedUrl(url)
199179860b2SJed Brown    try:
200179860b2SJed Brown      self.testAuthorizedUrl(authUrl)
201179860b2SJed Brown      self.bkClone(authUrl, root, name)
202179860b2SJed Brown    except RuntimeError:
203179860b2SJed Brown      pass
204179860b2SJed Brown    else:
205179860b2SJed Brown      return
206179860b2SJed Brown    return self.bkClone(url, root, name)
207179860b2SJed Brown
208179860b2SJed Brown  def retrieve(self, url, root = None, canExist = 0, force = 0):
209179860b2SJed Brown    '''Retrieve the project corresponding to url
210179860b2SJed Brown    - If root is None, the local root directory is automatically determined. If the project
211179860b2SJed Brown      was already installed, this root is used. Otherwise a guess is made based upon the url.
212179860b2SJed Brown    - If canExist is True and the root exists, an update is done instead of a full download.
213179860b2SJed Brown      The canExist is automatically true if the project has been installed. The retrievalCanExist
214179860b2SJed Brown      flag can also be used to set this.
215179860b2SJed Brown    - If force is True, a full download is mandated.
216179860b2SJed Brown    Providing the root is an easy way to make a copy, for instance when making tarballs.
217179860b2SJed Brown    '''
218179860b2SJed Brown    if root is None:
219179860b2SJed Brown      root = self.getInstallRoot(url)
220179860b2SJed Brown    (scheme, location, path, parameters, query, fragment) = urlparse.urlparse(url)
221179860b2SJed Brown    if hasattr(self,scheme+'Retrieve'):
222179860b2SJed Brown      getattr(self, scheme+'Retrieve')(url, os.path.abspath(root), canExist, force)
223179860b2SJed Brown    else:
224179860b2SJed Brown      raise RuntimeError('Invalid transport for retrieval: '+scheme)
225179860b2SJed Brown    return
226179860b2SJed Brown
227179860b2SJed Brown  ##############################################
228179860b2SJed Brown  # This is the old shit
229179860b2SJed Brown  ##############################################
230179860b2SJed Brown  def removeRoot(self, root, canExist, force = 0):
231179860b2SJed Brown    '''Returns 1 if removes root'''
232179860b2SJed Brown    if os.path.exists(root):
233179860b2SJed Brown      if canExist:
234179860b2SJed Brown        if force:
235179860b2SJed Brown          import shutil
236179860b2SJed Brown          shutil.rmtree(root)
237179860b2SJed Brown          return 1
238179860b2SJed Brown        else:
239179860b2SJed Brown          return 0
240179860b2SJed Brown      else:
241179860b2SJed Brown        raise RuntimeError('Root directory '+root+' already exists')
242179860b2SJed Brown    return 1
243179860b2SJed Brown
244179860b2SJed Brown  def getBKParentURL(self, root):
245179860b2SJed Brown    '''Return the parent URL for the BK repository at "root"'''
246179860b2SJed Brown    return self.executeShellCommand('cd '+root+'; bk parent')[21:]
247179860b2SJed Brown
248179860b2SJed Brown  def bkHeadRevision(self, root):
249179860b2SJed Brown    '''Return the last change set revision in the repository'''
250179860b2SJed Brown    return self.executeShellCommand('cd '+root+'; bk changes -and:REV: | head -1')
251179860b2SJed Brown
252179860b2SJed Brown  def bkfileRetrieve(self, url, root, canExist = 0, force = 0):
253179860b2SJed Brown    self.debugPrint('Retrieving '+url+' --> '+root+' via local bk', 3, 'install')
254179860b2SJed Brown    (scheme, location, path, parameters, query, fragment) = urlparse.urlparse(url)
255179860b2SJed Brown    return self.bkRetrieve(urlparse.urlunparse(('file', location, path, parameters, query, fragment)), root, canExist, force)
256179860b2SJed Brown
257179860b2SJed Brown  def sshRetrieve(self, url, root, canExist = 0, force = 0):
258179860b2SJed Brown    command = 'hg clone '+url+' '+os.path.join(root,os.path.basename(url))
259179860b2SJed Brown    output  = config.base.Configure.executeShellCommand(command)
260179860b2SJed Brown    return root
261179860b2SJed Brown
262179860b2SJed Brown  def oldRetrieve(self, url, root = None, canExist = 0, force = 0):
263179860b2SJed Brown    '''Retrieve the project corresponding to url
264179860b2SJed Brown    - If root is None, the local root directory is automatically determined. If the project
265179860b2SJed Brown      was already installed, this root is used. Otherwise a guess is made based upon the url.
266179860b2SJed Brown    - If canExist is True and the root exists, an update is done instead of a full download.
267179860b2SJed Brown      The canExist is automatically true if the project has been installed. The retrievalCanExist
268179860b2SJed Brown      flag can also be used to set this.
269179860b2SJed Brown    - If force is True, a full download is mandated.
270179860b2SJed Brown    Providing the root is an easy way to make a copy, for instance when making tarballs.
271179860b2SJed Brown    '''
272179860b2SJed Brown    origUrl = url
273179860b2SJed Brown    url     = self.getMappedUrl(origUrl)
274179860b2SJed Brown    project = self.getInstalledProject(url)
275179860b2SJed Brown    if not project is None and root is None:
276179860b2SJed Brown      root     = project.getRoot()
277179860b2SJed Brown      canExist = 1
278179860b2SJed Brown    if root is None:
279179860b2SJed Brown      root = self.getInstallRoot(origUrl)
280179860b2SJed Brown    (scheme, location, path, parameters, query, fragment) = urlparse.urlparse(url)
281179860b2SJed Brown    try:
282179860b2SJed Brown      if self.argDB['retrievalCanExist']:
283179860b2SJed Brown        canExist = 1
284179860b2SJed Brown      return getattr(self, scheme+'Retrieve')(url, os.path.abspath(root), canExist, force)
285179860b2SJed Brown    except AttributeError:
286179860b2SJed Brown      raise RuntimeError('Invalid transport for retrieval: '+scheme)
287