~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transport/http.py

  • Committer: Martin Pool
  • Date: 2005-11-04 01:46:31 UTC
  • mto: (1185.33.49 bzr.dev)
  • mto: This revision was merged to the branch mainline in revision 1512.
  • Revision ID: mbp@sourcefrog.net-20051104014631-750e0ad4172c952c
Make biobench directly executable

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
2
 
#
 
1
# Copyright (C) 2005 Canonical Ltd
 
2
 
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
#
 
7
 
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
11
# GNU General Public License for more details.
12
 
#
 
12
 
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
 
 
17
 
"""Base implementation of Transport over http.
18
 
 
19
 
There are separate implementation modules for each http client implementation.
 
16
"""Implementation of Transport over http.
20
17
"""
21
18
 
 
19
from bzrlib.transport import Transport, register_transport
 
20
from bzrlib.errors import (TransportNotPossible, NoSuchFile, 
 
21
                           NonRelativePath, TransportError)
 
22
import os, errno
22
23
from cStringIO import StringIO
23
 
import mimetools
24
 
import re
 
24
import urllib2
25
25
import urlparse
26
 
import urllib
27
 
import sys
28
26
 
29
 
from bzrlib import (
30
 
    errors,
31
 
    ui,
32
 
    urlutils,
33
 
    )
34
 
from bzrlib.smart import medium
35
 
from bzrlib.symbol_versioning import (
36
 
        deprecated_method,
37
 
        zero_seventeen,
38
 
        )
 
27
from bzrlib.errors import BzrError, BzrCheckError
 
28
from bzrlib.branch import Branch
39
29
from bzrlib.trace import mutter
40
 
from bzrlib.transport import (
41
 
    ConnectedTransport,
42
 
    _CoalescedOffset,
43
 
    Transport,
44
 
    )
45
 
 
46
 
# TODO: This is not used anymore by HttpTransport_urllib
47
 
# (extracting the auth info and prompting the user for a password
48
 
# have been split), only the tests still use it. It should be
49
 
# deleted and the tests rewritten ASAP to stay in sync.
50
 
def extract_auth(url, password_manager):
51
 
    """Extract auth parameters from am HTTP/HTTPS url and add them to the given
52
 
    password manager.  Return the url, minus those auth parameters (which
53
 
    confuse urllib2).
54
 
    """
55
 
    assert re.match(r'^(https?)(\+\w+)?://', url), \
56
 
            'invalid absolute url %r' % url
57
 
    scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
58
 
 
59
 
    if '@' in netloc:
60
 
        auth, netloc = netloc.split('@', 1)
61
 
        if ':' in auth:
62
 
            username, password = auth.split(':', 1)
63
 
        else:
64
 
            username, password = auth, None
65
 
        if ':' in netloc:
66
 
            host = netloc.split(':', 1)[0]
67
 
        else:
68
 
            host = netloc
69
 
        username = urllib.unquote(username)
70
 
        if password is not None:
71
 
            password = urllib.unquote(password)
72
 
        else:
73
 
            password = ui.ui_factory.get_password(
74
 
                prompt='HTTP %(user)s@%(host)s password',
75
 
                user=username, host=host)
76
 
        password_manager.add_password(None, host, username, password)
77
 
    url = urlparse.urlunsplit((scheme, netloc, path, query, fragment))
78
 
    return url
79
 
 
80
 
 
81
 
class HttpTransportBase(ConnectedTransport, medium.SmartClientMedium):
82
 
    """Base class for http implementations.
83
 
 
84
 
    Does URL parsing, etc, but not any network IO.
85
 
 
86
 
    The protocol can be given as e.g. http+urllib://host/ to use a particular
87
 
    implementation.
88
 
    """
89
 
 
90
 
    # _unqualified_scheme: "http" or "https"
91
 
    # _scheme: may have "+pycurl", etc
92
 
 
93
 
    def __init__(self, base, _from_transport=None):
 
30
 
 
31
 
 
32
def get_url(url):
 
33
    import urllib2
 
34
    mutter("get_url %s" % url)
 
35
    url_f = urllib2.urlopen(url)
 
36
    return url_f
 
37
 
 
38
class HttpTransportError(TransportError):
 
39
    pass
 
40
 
 
41
class HttpTransport(Transport):
 
42
    """This is the transport agent for http:// access.
 
43
    
 
44
    TODO: Implement pipelined versions of all of the *_multi() functions.
 
45
    """
 
46
 
 
47
    def __init__(self, base):
94
48
        """Set the base path where files will be stored."""
95
 
        proto_match = re.match(r'^(https?)(\+\w+)?://', base)
96
 
        if not proto_match:
97
 
            raise AssertionError("not a http url: %r" % base)
98
 
        self._unqualified_scheme = proto_match.group(1)
99
 
        impl_name = proto_match.group(2)
100
 
        if impl_name:
101
 
            impl_name = impl_name[1:]
102
 
        self._impl_name = impl_name
103
 
        super(HttpTransportBase, self).__init__(base,
104
 
                                                _from_transport=_from_transport)
105
 
        # range hint is handled dynamically throughout the life
106
 
        # of the transport object. We start by trying multi-range
107
 
        # requests and if the server returns bogus results, we
108
 
        # retry with single range requests and, finally, we
109
 
        # forget about range if the server really can't
110
 
        # understand. Once acquired, this piece of info is
111
 
        # propagated to clones.
112
 
        if _from_transport is not None:
113
 
            self._range_hint = _from_transport._range_hint
114
 
        else:
115
 
            self._range_hint = 'multi'
 
49
        assert base.startswith('http://') or base.startswith('https://')
 
50
        super(HttpTransport, self).__init__(base)
 
51
        # In the future we might actually connect to the remote host
 
52
        # rather than using get_url
 
53
        # self._connection = None
 
54
        (self._proto, self._host,
 
55
            self._path, self._parameters,
 
56
            self._query, self._fragment) = urlparse.urlparse(self.base)
 
57
 
 
58
    def should_cache(self):
 
59
        """Return True if the data pulled across should be cached locally.
 
60
        """
 
61
        return True
 
62
 
 
63
    def clone(self, offset=None):
 
64
        """Return a new HttpTransport with root at self.base + offset
 
65
        For now HttpTransport does not actually connect, so just return
 
66
        a new HttpTransport object.
 
67
        """
 
68
        if offset is None:
 
69
            return HttpTransport(self.base)
 
70
        else:
 
71
            return HttpTransport(self.abspath(offset))
 
72
 
 
73
    def abspath(self, relpath):
 
74
        """Return the full url to the given relative path.
 
75
        This can be supplied with a string or a list
 
76
        """
 
77
        assert isinstance(relpath, basestring)
 
78
        if isinstance(relpath, basestring):
 
79
            relpath_parts = relpath.split('/')
 
80
        else:
 
81
            # TODO: Don't call this with an array - no magic interfaces
 
82
            relpath_parts = relpath[:]
 
83
        if len(relpath_parts) > 1:
 
84
            if relpath_parts[0] == '':
 
85
                raise ValueError("path %r within branch %r seems to be absolute"
 
86
                                 % (relpath, self._path))
 
87
            if relpath_parts[-1] == '':
 
88
                raise ValueError("path %r within branch %r seems to be a directory"
 
89
                                 % (relpath, self._path))
 
90
        basepath = self._path.split('/')
 
91
        if len(basepath) > 0 and basepath[-1] == '':
 
92
            basepath = basepath[:-1]
 
93
        for p in relpath_parts:
 
94
            if p == '..':
 
95
                if len(basepath) == 0:
 
96
                    # In most filesystems, a request for the parent
 
97
                    # of root, just returns root.
 
98
                    continue
 
99
                basepath.pop()
 
100
            elif p == '.' or p == '':
 
101
                continue # No-op
 
102
            else:
 
103
                basepath.append(p)
 
104
        # Possibly, we could use urlparse.urljoin() here, but
 
105
        # I'm concerned about when it chooses to strip the last
 
106
        # portion of the path, and when it doesn't.
 
107
        path = '/'.join(basepath)
 
108
        return urlparse.urlunparse((self._proto,
 
109
                self._host, path, '', '', ''))
116
110
 
117
111
    def has(self, relpath):
118
 
        raise NotImplementedError("has() is abstract on %r" % self)
119
 
 
120
 
    def get(self, relpath):
 
112
        """Does the target location exist?
 
113
 
 
114
        TODO: HttpTransport.has() should use a HEAD request,
 
115
        not a full GET request.
 
116
 
 
117
        TODO: This should be changed so that we don't use
 
118
        urllib2 and get an exception, the code path would be
 
119
        cleaner if we just do an http HEAD request, and parse
 
120
        the return code.
 
121
        """
 
122
        try:
 
123
            f = get_url(self.abspath(relpath))
 
124
            # Without the read and then close()
 
125
            # we tend to have busy sockets.
 
126
            f.read()
 
127
            f.close()
 
128
            return True
 
129
        except urllib2.URLError, e:
 
130
            if e.code == 404:
 
131
                return False
 
132
            raise
 
133
        except IOError, e:
 
134
            if e.errno == errno.ENOENT:
 
135
                return False
 
136
            raise HttpTransportError(orig_error=e)
 
137
 
 
138
    def get(self, relpath, decode=False):
121
139
        """Get the file at the given relative path.
122
140
 
123
141
        :param relpath: The relative path to the file
124
142
        """
125
 
        code, response_file = self._get(relpath, None)
126
 
        # FIXME: some callers want an iterable... One step forward, three steps
127
 
        # backwards :-/ And not only an iterable, but an iterable that can be
128
 
        # seeked backwards, so we will never be able to do that.  One such
129
 
        # known client is bzrlib.bundle.serializer.v4.get_bundle_reader. At the
130
 
        # time of this writing it's even the only known client -- vila20071203
131
 
        return StringIO(response_file.read())
132
 
 
133
 
    def _get(self, relpath, ranges, tail_amount=0):
134
 
        """Get a file, or part of a file.
135
 
 
136
 
        :param relpath: Path relative to transport base URL
137
 
        :param ranges: None to get the whole file;
138
 
            or  a list of _CoalescedOffset to fetch parts of a file.
139
 
        :param tail_amount: The amount to get from the end of the file.
140
 
 
141
 
        :returns: (http_code, result_file)
142
 
        """
143
 
        raise NotImplementedError(self._get)
144
 
 
145
 
    def _remote_path(self, relpath):
146
 
        """See ConnectedTransport._remote_path.
147
 
 
148
 
        user and passwords are not embedded in the path provided to the server.
149
 
        """
150
 
        relative = urlutils.unescape(relpath).encode('utf-8')
151
 
        path = self._combine_paths(self._path, relative)
152
 
        return self._unsplit_url(self._unqualified_scheme,
153
 
                                 None, None, self._host, self._port, path)
154
 
 
155
 
    def _create_auth(self):
156
 
        """Returns a dict returning the credentials provided at build time."""
157
 
        auth = dict(host=self._host, port=self._port,
158
 
                    user=self._user, password=self._password,
159
 
                    protocol=self._unqualified_scheme,
160
 
                    path=self._path)
161
 
        return auth
162
 
 
163
 
    def get_request(self):
164
 
        return SmartClientHTTPMediumRequest(self)
165
 
 
166
 
    def get_smart_medium(self):
167
 
        """See Transport.get_smart_medium.
168
 
 
169
 
        HttpTransportBase directly implements the minimal interface of
170
 
        SmartMediumClient, so this returns self.
171
 
        """
172
 
        return self
173
 
 
174
 
    def _degrade_range_hint(self, relpath, ranges, exc_info):
175
 
        if self._range_hint == 'multi':
176
 
            self._range_hint = 'single'
177
 
            mutter('Retry "%s" with single range request' % relpath)
178
 
        elif self._range_hint == 'single':
179
 
            self._range_hint = None
180
 
            mutter('Retry "%s" without ranges' % relpath)
181
 
        else:
182
 
            # We tried all the tricks, but nothing worked. We re-raise the
183
 
            # original exception; the 'mutter' calls above will indicate that
184
 
            # further tries were unsuccessful
185
 
            raise exc_info[0], exc_info[1], exc_info[2]
186
 
 
187
 
    # _coalesce_offsets is a helper for readv, it try to combine ranges without
188
 
    # degrading readv performances. _bytes_to_read_before_seek is the value
189
 
    # used for the limit parameter and has been tuned for other transports. For
190
 
    # HTTP, the name is inappropriate but the parameter is still useful and
191
 
    # helps reduce the number of chunks in the response. The overhead for a
192
 
    # chunk (headers, length, footer around the data itself is variable but
193
 
    # around 50 bytes. We use 128 to reduce the range specifiers that appear in
194
 
    # the header, some servers (notably Apache) enforce a maximum length for a
195
 
    # header and issue a '400: Bad request' error when too much ranges are
196
 
    # specified.
197
 
    _bytes_to_read_before_seek = 128
198
 
    # No limit on the offset number that get combined into one, we are trying
199
 
    # to avoid downloading the whole file.
200
 
    _max_readv_combine = 0
201
 
    # By default Apache has a limit of ~400 ranges before replying with a 400
202
 
    # Bad Request. So we go underneath that amount to be safe.
203
 
    _max_get_ranges = 200
204
 
    # We impose no limit on the range size. But see _pycurl.py for a different
205
 
    # use.
206
 
    _get_max_size = 0
207
 
 
208
 
    def _readv(self, relpath, offsets):
209
 
        """Get parts of the file at the given relative path.
210
 
 
211
 
        :param offsets: A list of (offset, size) tuples.
212
 
        :param return: A list or generator of (offset, data) tuples
213
 
        """
214
 
 
215
 
        # offsets may be a generator, we will iterate it several times, so
216
 
        # build a list
217
 
        offsets = list(offsets)
218
 
 
219
 
        try_again = True
220
 
        retried_offset = None
221
 
        while try_again:
222
 
            try_again = False
223
 
 
224
 
            # Coalesce the offsets to minimize the GET requests issued
225
 
            sorted_offsets = sorted(offsets)
226
 
            coalesced = self._coalesce_offsets(
227
 
                sorted_offsets, limit=self._max_readv_combine,
228
 
                fudge_factor=self._bytes_to_read_before_seek,
229
 
                max_size=self._get_max_size)
230
 
 
231
 
            # Turn it into a list, we will iterate it several times
232
 
            coalesced = list(coalesced)
233
 
            mutter('http readv of %s  offsets => %s collapsed %s',
234
 
                    relpath, len(offsets), len(coalesced))
235
 
 
236
 
            # Cache the data read, but only until it's been used
237
 
            data_map = {}
238
 
            # We will iterate on the data received from the GET requests and
239
 
            # serve the corresponding offsets respecting the initial order. We
240
 
            # need an offset iterator for that.
241
 
            iter_offsets = iter(offsets)
242
 
            cur_offset_and_size = iter_offsets.next()
243
 
 
244
 
            try:
245
 
                for cur_coal, rfile in self._coalesce_readv(relpath, coalesced):
246
 
                    # Split the received chunk
247
 
                    for offset, size in cur_coal.ranges:
248
 
                        start = cur_coal.start + offset
249
 
                        rfile.seek(start, 0)
250
 
                        data = rfile.read(size)
251
 
                        data_len = len(data)
252
 
                        if data_len != size:
253
 
                            raise errors.ShortReadvError(relpath, start, size,
254
 
                                                         actual=data_len)
255
 
                        if (start, size) == cur_offset_and_size:
256
 
                            # The offset requested are sorted as the coalesced
257
 
                            # ones, no need to cache. Win !
258
 
                            yield cur_offset_and_size[0], data
259
 
                            cur_offset_and_size = iter_offsets.next()
260
 
                        else:
261
 
                            # Different sorting. We need to cache.
262
 
                            data_map[(start, size)] = data
263
 
 
264
 
                    # Yield everything we can
265
 
                    while cur_offset_and_size in data_map:
266
 
                        # Clean the cached data since we use it
267
 
                        # XXX: will break if offsets contains duplicates --
268
 
                        # vila20071129
269
 
                        this_data = data_map.pop(cur_offset_and_size)
270
 
                        yield cur_offset_and_size[0], this_data
271
 
                        cur_offset_and_size = iter_offsets.next()
272
 
 
273
 
            except (errors.ShortReadvError, errors.InvalidRange,
274
 
                    errors.InvalidHttpRange), e:
275
 
                mutter('Exception %r: %s during http._readv',e, e)
276
 
                if (not isinstance(e, errors.ShortReadvError)
277
 
                    or retried_offset == cur_offset_and_size):
278
 
                    # We don't degrade the range hint for ShortReadvError since
279
 
                    # they do not indicate a problem with the server ability to
280
 
                    # handle ranges. Except when we fail to get back a required
281
 
                    # offset twice in a row. In that case, falling back to
282
 
                    # single range or whole file should help or end up in a
283
 
                    # fatal exception.
284
 
                    self._degrade_range_hint(relpath, coalesced, sys.exc_info())
285
 
                # Some offsets may have been already processed, so we retry
286
 
                # only the unsuccessful ones.
287
 
                offsets = [cur_offset_and_size] + [o for o in iter_offsets]
288
 
                retried_offset = cur_offset_and_size
289
 
                try_again = True
290
 
 
291
 
    def _coalesce_readv(self, relpath, coalesced):
292
 
        """Issue several GET requests to satisfy the coalesced offsets"""
293
 
 
294
 
        def get_and_yield(relpath, coalesced):
295
 
            if coalesced:
296
 
                # Note that the _get below may raise
297
 
                # errors.InvalidHttpRange. It's the caller's responsibility to
298
 
                # decide how to retry since it may provide different coalesced
299
 
                # offsets.
300
 
                code, rfile = self._get(relpath, coalesced)
301
 
                for coal in coalesced:
302
 
                    yield coal, rfile
303
 
 
304
 
        if self._range_hint is None:
305
 
            # Download whole file
306
 
            for c, rfile in get_and_yield(relpath, coalesced):
307
 
                yield c, rfile
308
 
        else:
309
 
            total = len(coalesced)
310
 
            if self._range_hint == 'multi':
311
 
                max_ranges = self._max_get_ranges
312
 
            elif self._range_hint == 'single':
313
 
                max_ranges = total
314
 
            else:
315
 
                raise AssertionError("Unknown _range_hint %r"
316
 
                                     % (self._range_hint,))
317
 
            # TODO: Some web servers may ignore the range requests and return
318
 
            # the whole file, we may want to detect that and avoid further
319
 
            # requests.
320
 
            # Hint: test_readv_multiple_get_requests will fail once we do that
321
 
            cumul = 0
322
 
            ranges = []
323
 
            for coal in coalesced:
324
 
                if ((self._get_max_size > 0
325
 
                     and cumul + coal.length > self._get_max_size)
326
 
                    or len(ranges) >= max_ranges):
327
 
                    # Get that much and yield
328
 
                    for c, rfile in get_and_yield(relpath, ranges):
329
 
                        yield c, rfile
330
 
                    # Restart with the current offset
331
 
                    ranges = [coal]
332
 
                    cumul = coal.length
333
 
                else:
334
 
                    ranges.append(coal)
335
 
                    cumul += coal.length
336
 
            # Get the rest and yield
337
 
            for c, rfile in get_and_yield(relpath, ranges):
338
 
                yield c, rfile
339
 
 
340
 
    def recommended_page_size(self):
341
 
        """See Transport.recommended_page_size().
342
 
 
343
 
        For HTTP we suggest a large page size to reduce the overhead
344
 
        introduced by latency.
345
 
        """
346
 
        return 64 * 1024
347
 
 
348
 
    def _post(self, body_bytes):
349
 
        """POST body_bytes to .bzr/smart on this transport.
350
 
        
351
 
        :returns: (response code, response body file-like object).
352
 
        """
353
 
        # TODO: Requiring all the body_bytes to be available at the beginning of
354
 
        # the POST may require large client buffers.  It would be nice to have
355
 
        # an interface that allows streaming via POST when possible (and
356
 
        # degrades to a local buffer when not).
357
 
        raise NotImplementedError(self._post)
358
 
 
359
 
    def put_file(self, relpath, f, mode=None):
360
 
        """Copy the file-like object into the location.
 
143
        try:
 
144
            return get_url(self.abspath(relpath))
 
145
        except urllib2.URLError, e:
 
146
            if e.code == 404:
 
147
                raise NoSuchFile(msg = "Error retrieving %s: %s" 
 
148
                                 % (self.abspath(relpath), str(e)),
 
149
                                 orig_error=e)
 
150
            raise
 
151
        except (BzrError, IOError), e:
 
152
            raise NoSuchFile(msg = "Error retrieving %s: %s" 
 
153
                             % (self.abspath(relpath), str(e)),
 
154
                             orig_error=e)
 
155
 
 
156
    def put(self, relpath, f):
 
157
        """Copy the file-like or string object into the location.
361
158
 
362
159
        :param relpath: Location to put the contents, relative to base.
363
 
        :param f:       File-like object.
 
160
        :param f:       File-like or string object.
364
161
        """
365
 
        raise errors.TransportNotPossible('http PUT not supported')
 
162
        raise TransportNotPossible('http PUT not supported')
366
163
 
367
 
    def mkdir(self, relpath, mode=None):
 
164
    def mkdir(self, relpath):
368
165
        """Create a directory at the given path."""
369
 
        raise errors.TransportNotPossible('http does not support mkdir()')
370
 
 
371
 
    def rmdir(self, relpath):
372
 
        """See Transport.rmdir."""
373
 
        raise errors.TransportNotPossible('http does not support rmdir()')
374
 
 
375
 
    def append_file(self, relpath, f, mode=None):
 
166
        raise TransportNotPossible('http does not support mkdir()')
 
167
 
 
168
    def append(self, relpath, f):
376
169
        """Append the text in the file-like object into the final
377
170
        location.
378
171
        """
379
 
        raise errors.TransportNotPossible('http does not support append()')
 
172
        raise TransportNotPossible('http does not support append()')
380
173
 
381
174
    def copy(self, rel_from, rel_to):
382
175
        """Copy the item at rel_from to the location at rel_to"""
383
 
        raise errors.TransportNotPossible('http does not support copy()')
 
176
        raise TransportNotPossible('http does not support copy()')
384
177
 
385
 
    def copy_to(self, relpaths, other, mode=None, pb=None):
 
178
    def copy_to(self, relpaths, other, pb=None):
386
179
        """Copy a set of entries from self into another Transport.
387
180
 
388
181
        :param relpaths: A list/generator of entries to be copied.
393
186
        # At this point HttpTransport might be able to check and see if
394
187
        # the remote location is the same, and rather than download, and
395
188
        # then upload, it could just issue a remote copy_this command.
396
 
        if isinstance(other, HttpTransportBase):
397
 
            raise errors.TransportNotPossible(
398
 
                'http cannot be the target of copy_to()')
 
189
        if isinstance(other, HttpTransport):
 
190
            raise TransportNotPossible('http cannot be the target of copy_to()')
399
191
        else:
400
 
            return super(HttpTransportBase, self).\
401
 
                    copy_to(relpaths, other, mode=mode, pb=pb)
 
192
            return super(HttpTransport, self).copy_to(relpaths, other, pb=pb)
402
193
 
403
194
    def move(self, rel_from, rel_to):
404
195
        """Move the item at rel_from to the location at rel_to"""
405
 
        raise errors.TransportNotPossible('http does not support move()')
 
196
        raise TransportNotPossible('http does not support move()')
406
197
 
407
198
    def delete(self, relpath):
408
199
        """Delete the item at relpath"""
409
 
        raise errors.TransportNotPossible('http does not support delete()')
410
 
 
411
 
    def external_url(self):
412
 
        """See bzrlib.transport.Transport.external_url."""
413
 
        # HTTP URL's are externally usable.
414
 
        return self.base
415
 
 
416
 
    def is_readonly(self):
417
 
        """See Transport.is_readonly."""
418
 
        return True
 
200
        raise TransportNotPossible('http does not support delete()')
419
201
 
420
202
    def listable(self):
421
203
        """See Transport.listable."""
424
206
    def stat(self, relpath):
425
207
        """Return the stat information for a file.
426
208
        """
427
 
        raise errors.TransportNotPossible('http does not support stat()')
 
209
        raise TransportNotPossible('http does not support stat()')
428
210
 
429
211
    def lock_read(self, relpath):
430
212
        """Lock the given file for shared (read) access.
445
227
 
446
228
        :return: A lock object, which should be passed to Transport.unlock()
447
229
        """
448
 
        raise errors.TransportNotPossible('http does not support lock_write()')
449
 
 
450
 
    def clone(self, offset=None):
451
 
        """Return a new HttpTransportBase with root at self.base + offset
452
 
 
453
 
        We leave the daughter classes take advantage of the hint
454
 
        that it's a cloning not a raw creation.
455
 
        """
456
 
        if offset is None:
457
 
            return self.__class__(self.base, self)
458
 
        else:
459
 
            return self.__class__(self.abspath(offset), self)
460
 
 
461
 
    def _attempted_range_header(self, offsets, tail_amount):
462
 
        """Prepare a HTTP Range header at a level the server should accept.
463
 
 
464
 
        :return: the range header representing offsets/tail_amount or None if
465
 
            no header can be built.
466
 
        """
467
 
 
468
 
        if self._range_hint == 'multi':
469
 
            # Generate the header describing all offsets
470
 
            return self._range_header(offsets, tail_amount)
471
 
        elif self._range_hint == 'single':
472
 
            # Combine all the requested ranges into a single
473
 
            # encompassing one
474
 
            if len(offsets) > 0:
475
 
                if tail_amount not in (0, None):
476
 
                    # Nothing we can do here to combine ranges with tail_amount
477
 
                    # in a single range, just returns None. The whole file
478
 
                    # should be downloaded.
479
 
                    return None
480
 
                else:
481
 
                    start = offsets[0].start
482
 
                    last = offsets[-1]
483
 
                    end = last.start + last.length - 1
484
 
                    whole = self._coalesce_offsets([(start, end - start + 1)],
485
 
                                                   limit=0, fudge_factor=0)
486
 
                    return self._range_header(list(whole), 0)
487
 
            else:
488
 
                # Only tail_amount, requested, leave range_header
489
 
                # do its work
490
 
                return self._range_header(offsets, tail_amount)
491
 
        else:
492
 
            return None
493
 
 
494
 
    @staticmethod
495
 
    def _range_header(ranges, tail_amount):
496
 
        """Turn a list of bytes ranges into a HTTP Range header value.
497
 
 
498
 
        :param ranges: A list of _CoalescedOffset
499
 
        :param tail_amount: The amount to get from the end of the file.
500
 
 
501
 
        :return: HTTP range header string.
502
 
 
503
 
        At least a non-empty ranges *or* a tail_amount must be
504
 
        provided.
505
 
        """
506
 
        strings = []
507
 
        for offset in ranges:
508
 
            strings.append('%d-%d' % (offset.start,
509
 
                                      offset.start + offset.length - 1))
510
 
 
511
 
        if tail_amount:
512
 
            strings.append('-%d' % tail_amount)
513
 
 
514
 
        return ','.join(strings)
515
 
 
516
 
    def send_http_smart_request(self, bytes):
517
 
        code, body_filelike = self._post(bytes)
518
 
        assert code == 200, 'unexpected HTTP response code %r' % (code,)
519
 
        return body_filelike
520
 
 
521
 
 
522
 
class SmartClientHTTPMediumRequest(medium.SmartClientMediumRequest):
523
 
    """A SmartClientMediumRequest that works with an HTTP medium."""
524
 
 
525
 
    def __init__(self, client_medium):
526
 
        medium.SmartClientMediumRequest.__init__(self, client_medium)
527
 
        self._buffer = ''
528
 
 
529
 
    def _accept_bytes(self, bytes):
530
 
        self._buffer += bytes
531
 
 
532
 
    def _finished_writing(self):
533
 
        data = self._medium.send_http_smart_request(self._buffer)
534
 
        self._response_body = data
535
 
 
536
 
    def _read_bytes(self, count):
537
 
        return self._response_body.read(count)
538
 
 
539
 
    def _finished_reading(self):
540
 
        """See SmartClientMediumRequest._finished_reading."""
541
 
        pass
 
230
        raise TransportNotPossible('http does not support lock_write()')