~gnuoy/charms/precise/apache2/apache2-openid

« back to all changes in this revision

Viewing changes to hooks/charmhelpers/fetch/archiveurl.py

  • Committer: Marco Ceppi
  • Date: 2013-10-17 03:21:15 UTC
  • mfrom: (27.2.55 master)
  • Revision ID: marco@ceppi.net-20131017032115-iwu78y9cgqwi3a5s
[sidnei] Greatly improved test coverage. Support for 'all_services' set from haproxy relation. Improved documentation.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import os
 
2
import urllib2
 
3
from charmhelpers.fetch import (
 
4
    BaseFetchHandler,
 
5
    UnhandledSource
 
6
)
 
7
from charmhelpers.payload.archive import (
 
8
    get_archive_handler,
 
9
    extract,
 
10
)
 
11
from charmhelpers.core.host import mkdir
 
12
 
 
13
 
 
14
class ArchiveUrlFetchHandler(BaseFetchHandler):
 
15
    """Handler for archives via generic URLs"""
 
16
    def can_handle(self, source):
 
17
        url_parts = self.parse_url(source)
 
18
        if url_parts.scheme not in ('http', 'https', 'ftp', 'file'):
 
19
            return "Wrong source type"
 
20
        if get_archive_handler(self.base_url(source)):
 
21
            return True
 
22
        return False
 
23
 
 
24
    def download(self, source, dest):
 
25
        # propogate all exceptions
 
26
        # URLError, OSError, etc
 
27
        response = urllib2.urlopen(source)
 
28
        try:
 
29
            with open(dest, 'w') as dest_file:
 
30
                dest_file.write(response.read())
 
31
        except Exception as e:
 
32
            if os.path.isfile(dest):
 
33
                os.unlink(dest)
 
34
            raise e
 
35
 
 
36
    def install(self, source):
 
37
        url_parts = self.parse_url(source)
 
38
        dest_dir = os.path.join(os.environ.get('CHARM_DIR'), 'fetched')
 
39
        if not os.path.exists(dest_dir):
 
40
            mkdir(dest_dir, perms=0755)
 
41
        dld_file = os.path.join(dest_dir, os.path.basename(url_parts.path))
 
42
        try:
 
43
            self.download(source, dld_file)
 
44
        except urllib2.URLError as e:
 
45
            raise UnhandledSource(e.reason)
 
46
        except OSError as e:
 
47
            raise UnhandledSource(e.strerror)
 
48
        return extract(dld_file)