~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transport/http/_urllib.py

Merge bzr.dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
import urllib, urllib2
 
18
 
 
19
import bzrlib  # for the version
 
20
from bzrlib.errors import BzrError
 
21
from bzrlib.trace import mutter
 
22
from bzrlib.transport.http import HttpTransportBase, extract_auth, HttpServer
 
23
from bzrlib.errors import (TransportNotPossible, NoSuchFile,
 
24
                           TransportError, ConnectionError)
 
25
 
 
26
 
 
27
class Request(urllib2.Request):
 
28
    """Request object for urllib2 that allows the method to be overridden."""
 
29
 
 
30
    method = None
 
31
 
 
32
    def get_method(self):
 
33
        if self.method is not None:
 
34
            return self.method
 
35
        else:
 
36
            return urllib2.Request.get_method(self)
 
37
 
 
38
 
 
39
class HttpTransport_urllib(HttpTransportBase):
 
40
    """Python urllib transport for http and https.
 
41
    """
 
42
 
 
43
    # TODO: Implement pipelined versions of all of the *_multi() functions.
 
44
 
 
45
    def __init__(self, base):
 
46
        """Set the base path where files will be stored."""
 
47
        super(HttpTransport_urllib, self).__init__(base)
 
48
 
 
49
    def _get(self, relpath, ranges):
 
50
        path = relpath
 
51
        try:
 
52
            path = self._real_abspath(relpath)
 
53
            response = self._get_url_impl(path, method='GET', ranges=ranges)
 
54
            return response.code, response
 
55
        except urllib2.HTTPError, e:
 
56
            mutter('url error code: %s for has url: %r', e.code, path)
 
57
            if e.code == 404:
 
58
                raise NoSuchFile(path, extra=e)
 
59
            raise
 
60
        except (BzrError, IOError), e:
 
61
            if hasattr(e, 'errno'):
 
62
                mutter('io error: %s %s for has url: %r',
 
63
                    e.errno, errno.errorcode.get(e.errno), path)
 
64
                if e.errno == errno.ENOENT:
 
65
                    raise NoSuchFile(path, extra=e)
 
66
            raise ConnectionError(msg = "Error retrieving %s: %s" 
 
67
                             % (self.abspath(relpath), str(e)),
 
68
                             orig_error=e)
 
69
 
 
70
    def _get_url_impl(self, url, method, ranges):
 
71
        """Actually pass get request into urllib
 
72
 
 
73
        :returns: urllib Response object
 
74
        """
 
75
        if ranges:
 
76
            range_string = ranges
 
77
        else:
 
78
            range_string = 'all'
 
79
        mutter("get_url %s [%s]" % (url, range_string))
 
80
        manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
 
81
        url = extract_auth(url, manager)
 
82
        auth_handler = urllib2.HTTPBasicAuthHandler(manager)
 
83
        opener = urllib2.build_opener(auth_handler)
 
84
        request = Request(url)
 
85
        request.method = method
 
86
        request.add_header('User-Agent', 'bzr/%s (urllib)' % bzrlib.__version__)
 
87
        if ranges:
 
88
            assert len(ranges) == 1
 
89
            request.add_header('Range', 'bytes=%d-%d' % ranges[0])
 
90
        response = opener.open(request)
 
91
        return response
 
92
 
 
93
    def should_cache(self):
 
94
        """Return True if the data pulled across should be cached locally.
 
95
        """
 
96
        return True
 
97
 
 
98
    def has(self, relpath):
 
99
        """Does the target location exist?
 
100
        """
 
101
        abspath = self._real_abspath(relpath)
 
102
        try:
 
103
            f = self._get_url_impl(abspath, 'HEAD', [])
 
104
            # Without the read and then close()
 
105
            # we tend to have busy sockets.
 
106
            f.read()
 
107
            f.close()
 
108
            return True
 
109
        except urllib2.URLError, e:
 
110
            mutter('url error code: %s for has url: %r', e.code, abspath)
 
111
            if e.code == 404:
 
112
                return False
 
113
            raise
 
114
        except IOError, e:
 
115
            mutter('io error: %s %s for has url: %r',
 
116
                e.errno, errno.errorcode.get(e.errno), abspath)
 
117
            if e.errno == errno.ENOENT:
 
118
                return False
 
119
            raise TransportError(orig_error=e)
 
120
 
 
121
    def copy_to(self, relpaths, other, mode=None, pb=None):
 
122
        """Copy a set of entries from self into another Transport.
 
123
 
 
124
        :param relpaths: A list/generator of entries to be copied.
 
125
 
 
126
        TODO: if other is LocalTransport, is it possible to
 
127
              do better than put(get())?
 
128
        """
 
129
        # At this point HttpTransport_urllib might be able to check and see if
 
130
        # the remote location is the same, and rather than download, and
 
131
        # then upload, it could just issue a remote copy_this command.
 
132
        if isinstance(other, HttpTransport_urllib):
 
133
            raise TransportNotPossible('http cannot be the target of copy_to()')
 
134
        else:
 
135
            return super(HttpTransport_urllib, self).copy_to(relpaths, other, mode=mode, pb=pb)
 
136
 
 
137
    def move(self, rel_from, rel_to):
 
138
        """Move the item at rel_from to the location at rel_to"""
 
139
        raise TransportNotPossible('http does not support move()')
 
140
 
 
141
    def delete(self, relpath):
 
142
        """Delete the item at relpath"""
 
143
        raise TransportNotPossible('http does not support delete()')
 
144
 
 
145
 
 
146
class HttpServer_urllib(HttpServer):
 
147
    """Subclass of HttpServer that gives http+urllib urls.
 
148
 
 
149
    This is for use in testing: connections to this server will always go
 
150
    through urllib where possible.
 
151
    """
 
152
 
 
153
    # urls returned by this server should require the urllib client impl
 
154
    _url_protocol = 'http+urllib'
 
155
 
 
156
 
 
157
def get_test_permutations():
 
158
    """Return the permutations to be used in testing."""
 
159
    return [(HttpTransport_urllib, HttpServer_urllib),
 
160
            ]