xref: /petsc/config/BuildSystem/retrieval.py (revision 2501eaf601289d3360808f8cc222983423629496)
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))
90b95f98c7SJed Brown      except tarfile.ReadError, e:
91b95f98c7SJed Brown        raise RuntimeError(str(e)+'\n'+failureMessage)
9215ac2963SJed Brown      if not tf: raise RuntimeError(failureMessage)
93*2501eaf6SSatish Balay      #git puts 'pax_global_header' as the first entry and some tar utils process this as a file
94*2501eaf6SSatish Balay      firstname = tf.getnames()[0]
95*2501eaf6SSatish Balay      if firstname == 'pax_global_header':
96*2501eaf6SSatish Balay        firstmember = tf.getmembers()[1]
9715ac2963SJed Brown      else:
98*2501eaf6SSatish Balay        firstmember = tf.getmembers()[0]
99*2501eaf6SSatish Balay      # some tarfiles list packagename/ but some list packagename/filename in the first entry
100*2501eaf6SSatish Balay      if firstmember.isdir():
101*2501eaf6SSatish Balay        dirname = firstmember.name
102*2501eaf6SSatish Balay      else:
103*2501eaf6SSatish Balay        dirname = os.path.dirname(firstmember.name)
10415ac2963SJed Brown      if hasattr(tf,'extractall'): #python 2.5+
10515ac2963SJed Brown        tf.extractall(root)
10615ac2963SJed Brown      else:
10715ac2963SJed Brown        for tfile in tf.getmembers():
10815ac2963SJed Brown          tf.extract(tfile,root)
10915ac2963SJed Brown      tf.close()
11015ac2963SJed Brown
11115ac2963SJed Brown    # fix file permissions for the untared tarballs.
11215ac2963SJed Brown    try:
113*2501eaf6SSatish Balay      # check if 'dirname' is set'
114*2501eaf6SSatish Balay      if dirname:
115179860b2SJed Brown        config.base.Configure.executeShellCommand('cd '+root+'; chmod -R a+r '+dirname+';find  '+dirname + ' -type d -name "*" -exec chmod a+rx {} \;', log = self.log)
116*2501eaf6SSatish Balay      else:
117*2501eaf6SSatish Balay        self.logPrintBox('WARNING: Could not determine dirname extracted by '+localFile+' to fix file permissions')
118179860b2SJed Brown    except RuntimeError, e:
11915ac2963SJed Brown      raise RuntimeError('Error changing permissions for '+dirname+' obtained from '+localFile+ ' : '+str(e))
120179860b2SJed Brown    os.unlink(localFile)
121179860b2SJed Brown    return
122179860b2SJed Brown
123179860b2SJed Brown  def ftpRetrieve(self, url, root, name,force):
124179860b2SJed Brown    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via ftp', 3, 'install')
125179860b2SJed Brown    return self.genericRetrieve(url, root, name)
126179860b2SJed Brown
127179860b2SJed Brown  def httpRetrieve(self, url, root, name,force):
128179860b2SJed Brown    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via http', 3, 'install')
129179860b2SJed Brown    return self.genericRetrieve(url, root, name)
130179860b2SJed Brown
131179860b2SJed Brown  def fileRetrieve(self, url, root, name,force):
132179860b2SJed Brown    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via cp', 3, 'install')
133179860b2SJed Brown    return self.genericRetrieve(url, root, name)
134179860b2SJed Brown
135179860b2SJed Brown  def svnRetrieve(self, url, root, name,force):
136179860b2SJed Brown    if not hasattr(self.sourceControl, 'svn'):
137179860b2SJed Brown      raise RuntimeError('Cannot retrieve a SVN repository since svn was not found')
138179860b2SJed Brown    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via svn', 3, 'install')
139179860b2SJed Brown    try:
140179860b2SJed Brown      config.base.Configure.executeShellCommand(self.sourceControl.svn+' checkout http'+url[3:]+' '+os.path.join(root, name))
141179860b2SJed Brown    except RuntimeError:
142179860b2SJed Brown      pass
143179860b2SJed Brown
144179860b2SJed Brown
145179860b2SJed Brown  # This is the old code for updating a BK repository
146179860b2SJed Brown  # Stamp used to be stored with a url
147179860b2SJed Brown  def bkUpdate(self):
148179860b2SJed Brown    if not self.stamp is None and url in self.stamp:
149179860b2SJed Brown      if not self.stamp[url] == self.bkHeadRevision(root):
150179860b2SJed Brown        raise RuntimeError('Existing stamp for '+url+' does not match revision of repository in '+root)
151179860b2SJed Brown    (url, authUrl, wasAuth) = self.getAuthorizedUrl(self.getBKParentURL(root))
152179860b2SJed Brown    if not wasAuth:
153179860b2SJed Brown      self.debugPrint('Changing parent from '+url+' --> '+authUrl, 1, 'install')
154179860b2SJed Brown      output = self.executeShellCommand('cd '+root+'; bk parent '+authUrl)
155179860b2SJed Brown    try:
156179860b2SJed Brown      self.testAuthorizedUrl(authUrl)
157179860b2SJed Brown      output = self.executeShellCommand('cd '+root+'; bk pull')
158179860b2SJed Brown    except RuntimeError, e:
159179860b2SJed Brown      (url, authUrl, wasAuth) = self.getAuthorizedUrl(self.getBKParentURL(root))
160179860b2SJed Brown      if wasAuth:
161179860b2SJed Brown        self.debugPrint('Changing parent from '+authUrl+' --> '+url, 1, 'install')
162179860b2SJed Brown        output = self.executeShellCommand('cd '+root+'; bk parent '+url)
163179860b2SJed Brown        output = self.executeShellCommand('cd '+root+'; bk pull')
164179860b2SJed Brown      else:
165179860b2SJed Brown        raise e
166179860b2SJed Brown    return
167179860b2SJed Brown
168179860b2SJed Brown  def bkClone(self, url, root, name):
169179860b2SJed Brown    '''Clone a Bitkeeper repository located at url into root/name
170179860b2SJed Brown       - If self.stamp exists, clone only up to that revision'''
171179860b2SJed Brown    failureMessage = '''\
172179860b2SJed BrownUnable to bk clone %s
173179860b2SJed BrownYou may be off the network. Connect to the internet and run ./configure again
174179860b2SJed Brownor from the directory %s try:
175179860b2SJed Brown  bk clone %s
176179860b2SJed Brownand if that succeeds then rerun ./configure
177179860b2SJed Brown''' % (name, root, url, name)
178179860b2SJed Brown    try:
179179860b2SJed Brown      if not self.stamp is None and url in self.stamp:
180179860b2SJed Brown        (output, error, status) = self.executeShellCommand('bk clone -r'+self.stamp[url]+' '+url+' '+os.path.join(root, name))
181179860b2SJed Brown      else:
182179860b2SJed Brown        (output, error, status) = self.executeShellCommand('bk clone '+url+' '+os.path.join(root, name))
183179860b2SJed Brown    except RuntimeError, e:
184179860b2SJed Brown      status = 1
185179860b2SJed Brown      output = str(e)
186179860b2SJed Brown      error  = ''
187179860b2SJed Brown    if status:
188179860b2SJed Brown      if output.find('ommand not found') >= 0:
189179860b2SJed Brown        failureMessage = 'Unable to locate bk (Bitkeeper) to download repository; make sure bk is in your path'
190179860b2SJed Brown      elif output.find('Cannot resolve host') >= 0:
191179860b2SJed Brown        failureMessage = output+'\n'+error+'\n'+failureMessage
192179860b2SJed Brown      else:
193179860b2SJed Brown        (scheme, location, path, parameters, query, fragment) = urlparse.urlparse(url)
194179860b2SJed Brown        try:
195179860b2SJed Brown          self.bkClone(urlparse.urlunparse(('http', location, path, parameters, query, fragment)), root, name)
196179860b2SJed Brown        except RuntimeError, e:
197179860b2SJed Brown          failureMessage += '\n'+str(e)
198179860b2SJed Brown        else:
199179860b2SJed Brown          return
200179860b2SJed Brown      raise RuntimeError(failureMessage)
201179860b2SJed Brown    return
202179860b2SJed Brown
203179860b2SJed Brown  def bkRetrieve(self, url, root, name):
204179860b2SJed Brown    if not hasattr(self.sourceControl, 'bk'):
205179860b2SJed Brown      raise RuntimeError('Cannot retrieve a BitKeeper repository since BK was not found')
206179860b2SJed Brown    self.logPrint('Retrieving '+url+' --> '+os.path.join(root, name)+' via bk', 3, 'install')
207179860b2SJed Brown    (url, authUrl, wasAuth) = self.getAuthorizedUrl(url)
208179860b2SJed Brown    try:
209179860b2SJed Brown      self.testAuthorizedUrl(authUrl)
210179860b2SJed Brown      self.bkClone(authUrl, root, name)
211179860b2SJed Brown    except RuntimeError:
212179860b2SJed Brown      pass
213179860b2SJed Brown    else:
214179860b2SJed Brown      return
215179860b2SJed Brown    return self.bkClone(url, root, name)
216179860b2SJed Brown
217179860b2SJed Brown  def retrieve(self, url, root = None, canExist = 0, force = 0):
218179860b2SJed Brown    '''Retrieve the project corresponding to url
219179860b2SJed Brown    - If root is None, the local root directory is automatically determined. If the project
220179860b2SJed Brown      was already installed, this root is used. Otherwise a guess is made based upon the url.
221179860b2SJed Brown    - If canExist is True and the root exists, an update is done instead of a full download.
222179860b2SJed Brown      The canExist is automatically true if the project has been installed. The retrievalCanExist
223179860b2SJed Brown      flag can also be used to set this.
224179860b2SJed Brown    - If force is True, a full download is mandated.
225179860b2SJed Brown    Providing the root is an easy way to make a copy, for instance when making tarballs.
226179860b2SJed Brown    '''
227179860b2SJed Brown    if root is None:
228179860b2SJed Brown      root = self.getInstallRoot(url)
229179860b2SJed Brown    (scheme, location, path, parameters, query, fragment) = urlparse.urlparse(url)
230179860b2SJed Brown    if hasattr(self,scheme+'Retrieve'):
231179860b2SJed Brown      getattr(self, scheme+'Retrieve')(url, os.path.abspath(root), canExist, force)
232179860b2SJed Brown    else:
233179860b2SJed Brown      raise RuntimeError('Invalid transport for retrieval: '+scheme)
234179860b2SJed Brown    return
235179860b2SJed Brown
236179860b2SJed Brown  ##############################################
237179860b2SJed Brown  # This is the old shit
238179860b2SJed Brown  ##############################################
239179860b2SJed Brown  def removeRoot(self, root, canExist, force = 0):
240179860b2SJed Brown    '''Returns 1 if removes root'''
241179860b2SJed Brown    if os.path.exists(root):
242179860b2SJed Brown      if canExist:
243179860b2SJed Brown        if force:
244179860b2SJed Brown          import shutil
245179860b2SJed Brown          shutil.rmtree(root)
246179860b2SJed Brown          return 1
247179860b2SJed Brown        else:
248179860b2SJed Brown          return 0
249179860b2SJed Brown      else:
250179860b2SJed Brown        raise RuntimeError('Root directory '+root+' already exists')
251179860b2SJed Brown    return 1
252179860b2SJed Brown
253179860b2SJed Brown  def getBKParentURL(self, root):
254179860b2SJed Brown    '''Return the parent URL for the BK repository at "root"'''
255179860b2SJed Brown    return self.executeShellCommand('cd '+root+'; bk parent')[21:]
256179860b2SJed Brown
257179860b2SJed Brown  def bkHeadRevision(self, root):
258179860b2SJed Brown    '''Return the last change set revision in the repository'''
259179860b2SJed Brown    return self.executeShellCommand('cd '+root+'; bk changes -and:REV: | head -1')
260179860b2SJed Brown
261179860b2SJed Brown  def bkfileRetrieve(self, url, root, canExist = 0, force = 0):
262179860b2SJed Brown    self.debugPrint('Retrieving '+url+' --> '+root+' via local bk', 3, 'install')
263179860b2SJed Brown    (scheme, location, path, parameters, query, fragment) = urlparse.urlparse(url)
264179860b2SJed Brown    return self.bkRetrieve(urlparse.urlunparse(('file', location, path, parameters, query, fragment)), root, canExist, force)
265179860b2SJed Brown
266179860b2SJed Brown  def sshRetrieve(self, url, root, canExist = 0, force = 0):
267179860b2SJed Brown    command = 'hg clone '+url+' '+os.path.join(root,os.path.basename(url))
268179860b2SJed Brown    output  = config.base.Configure.executeShellCommand(command)
269179860b2SJed Brown    return root
270179860b2SJed Brown
271179860b2SJed Brown  def oldRetrieve(self, url, root = None, canExist = 0, force = 0):
272179860b2SJed Brown    '''Retrieve the project corresponding to url
273179860b2SJed Brown    - If root is None, the local root directory is automatically determined. If the project
274179860b2SJed Brown      was already installed, this root is used. Otherwise a guess is made based upon the url.
275179860b2SJed Brown    - If canExist is True and the root exists, an update is done instead of a full download.
276179860b2SJed Brown      The canExist is automatically true if the project has been installed. The retrievalCanExist
277179860b2SJed Brown      flag can also be used to set this.
278179860b2SJed Brown    - If force is True, a full download is mandated.
279179860b2SJed Brown    Providing the root is an easy way to make a copy, for instance when making tarballs.
280179860b2SJed Brown    '''
281179860b2SJed Brown    origUrl = url
282179860b2SJed Brown    url     = self.getMappedUrl(origUrl)
283179860b2SJed Brown    project = self.getInstalledProject(url)
284179860b2SJed Brown    if not project is None and root is None:
285179860b2SJed Brown      root     = project.getRoot()
286179860b2SJed Brown      canExist = 1
287179860b2SJed Brown    if root is None:
288179860b2SJed Brown      root = self.getInstallRoot(origUrl)
289179860b2SJed Brown    (scheme, location, path, parameters, query, fragment) = urlparse.urlparse(url)
290179860b2SJed Brown    try:
291179860b2SJed Brown      if self.argDB['retrievalCanExist']:
292179860b2SJed Brown        canExist = 1
293179860b2SJed Brown      return getattr(self, scheme+'Retrieve')(url, os.path.abspath(root), canExist, force)
294179860b2SJed Brown    except AttributeError:
295179860b2SJed Brown      raise RuntimeError('Invalid transport for retrieval: '+scheme)
296