~bzr-pqm/bzr/bzr.dev

4763.2.4 by John Arbash Meinel
merge bzr.2.1 in preparation for NEWS entry.
1
# Copyright (C) 2006-2010 Canonical Ltd
2018.5.26 by Andrew Bennetts
Extract a simple SmartClient class from RemoteTransport, and a hack to avoid VFS operations when probing for a bzrdir over a smart transport.
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2018.5.26 by Andrew Bennetts
Extract a simple SmartClient class from RemoteTransport, and a hack to avoid VFS operations when probing for a bzrdir over a smart transport.
16
6379.6.3 by Jelmer Vernooij
Use absolute_import.
17
from __future__ import absolute_import
18
4797.85.35 by John Arbash Meinel
Do a lookup in 'request.request_handlers', to figure out if a request can be retried.
19
from bzrlib import lazy_import
20
lazy_import.lazy_import(globals(), """
21
from bzrlib.smart import request as _mod_request
22
""")
23
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
24
import bzrlib
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
25
from bzrlib.smart import message, protocol
3703.3.3 by Andrew Bennetts
Neater effort tests for push by using a _SmartClient.hooks['call'] hook.
26
from bzrlib import (
4797.91.5 by John Arbash Meinel
Add -Dnoretry as a way to disable all retrying code.
27
    debug,
3703.3.3 by Andrew Bennetts
Neater effort tests for push by using a _SmartClient.hooks['call'] hook.
28
    errors,
29
    hooks,
4797.85.18 by John Arbash Meinel
Start trying to reconnect to the server if we get a ConnectionReset during the transmission.
30
    trace,
3703.3.3 by Andrew Bennetts
Neater effort tests for push by using a _SmartClient.hooks['call'] hook.
31
    )
2018.5.26 by Andrew Bennetts
Extract a simple SmartClient class from RemoteTransport, and a hack to avoid VFS operations when probing for a bzrdir over a smart transport.
32
33
2414.1.4 by Andrew Bennetts
Rename SmartClient to _SmartClient.
34
class _SmartClient(object):
2018.5.26 by Andrew Bennetts
Extract a simple SmartClient class from RemoteTransport, and a hack to avoid VFS operations when probing for a bzrdir over a smart transport.
35
3431.3.2 by Andrew Bennetts
Remove 'base' from _SmartClient entirely, now that the medium has it.
36
    def __init__(self, medium, headers=None):
3104.4.4 by Andrew Bennetts
Rename parameter to _SmartClient.__init__ to be less confusing.
37
        """Constructor.
38
3313.2.1 by Andrew Bennetts
Change _SmartClient's API to accept a medium and a base, rather than a _SharedConnection.
39
        :param medium: a SmartClientMedium
3104.4.4 by Andrew Bennetts
Rename parameter to _SmartClient.__init__ to be less confusing.
40
        """
3313.2.1 by Andrew Bennetts
Change _SmartClient's API to accept a medium and a base, rather than a _SharedConnection.
41
        self._medium = medium
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
42
        if headers is None:
43
            self._headers = {'Software version': bzrlib.__version__}
44
        else:
45
            self._headers = dict(headers)
46
4964.2.2 by Martin Pool
Add SmartClient repr
47
    def __repr__(self):
48
        return '%s(%r)' % (self.__class__.__name__, self._medium)
49
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
50
    def _call_and_read_response(self, method, args, body=None, readv_body=None,
3842.3.4 by Andrew Bennetts
TestStacking.test_fetch_copies_from_stacked_on now passes using the VersionedFile.insert_record_stream RPC; lots of debugging cruft needs removal though.
51
            body_stream=None, expect_response_body=True):
4797.85.27 by John Arbash Meinel
I've started passing around too many parameters to too many functions.
52
        request = _SmartClientRequest(self, method, args, body=body,
53
            readv_body=readv_body, body_stream=body_stream,
54
            expect_response_body=expect_response_body)
55
        return request.call_and_read_response()
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
56
2018.5.26 by Andrew Bennetts
Extract a simple SmartClient class from RemoteTransport, and a hack to avoid VFS operations when probing for a bzrdir over a smart transport.
57
    def call(self, method, *args):
58
        """Call a method on the remote server."""
2414.1.2 by Andrew Bennetts
Deal with review comments.
59
        result, protocol = self.call_expecting_body(method, *args)
2414.1.1 by Andrew Bennetts
Add some unicode-related tests from the hpss branch, and a few other nits (also from the hpss branch).
60
        protocol.cancel_read_body()
61
        return result
62
2414.1.2 by Andrew Bennetts
Deal with review comments.
63
    def call_expecting_body(self, method, *args):
64
        """Call a method and return the result and the protocol object.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
65
2414.1.2 by Andrew Bennetts
Deal with review comments.
66
        The body can be read like so::
67
68
            result, smart_protocol = smart_client.call_expecting_body(...)
69
            body = smart_protocol.read_body_bytes()
70
        """
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
71
        return self._call_and_read_response(
72
            method, args, expect_response_body=True)
2018.5.26 by Andrew Bennetts
Extract a simple SmartClient class from RemoteTransport, and a hack to avoid VFS operations when probing for a bzrdir over a smart transport.
73
74
    def call_with_body_bytes(self, method, args, body):
75
        """Call a method on the remote server with body bytes."""
2018.5.131 by Andrew Bennetts
Be strict about unicode passed to transport.put_{bytes,file} and SmartClient.call_with_body_bytes, fixing part of TestLockableFiles_RemoteLockDir.test_read_write.
76
        if type(method) is not str:
77
            raise TypeError('method must be a byte string, not %r' % (method,))
78
        for arg in args:
79
            if type(arg) is not str:
80
                raise TypeError('args must be byte strings, not %r' % (args,))
81
        if type(body) is not str:
82
            raise TypeError('body must be byte string, not %r' % (body,))
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
83
        response, response_handler = self._call_and_read_response(
84
            method, args, body=body, expect_response_body=False)
85
        return response
2414.1.1 by Andrew Bennetts
Add some unicode-related tests from the hpss branch, and a few other nits (also from the hpss branch).
86
3184.1.10 by Robert Collins
Change the smart server verb for Repository.stream_revisions_chunked to use SearchResults as the request mechanism for downloads.
87
    def call_with_body_bytes_expecting_body(self, method, args, body):
88
        """Call a method on the remote server with body bytes."""
89
        if type(method) is not str:
90
            raise TypeError('method must be a byte string, not %r' % (method,))
3842.3.2 by Andrew Bennetts
Revert the RemoteVersionedFiles.get_parent_map implementation, leaving just the skeleton of RemoteVersionedFiles.
91
        for arg in args:
92
            if type(arg) is not str:
93
                raise TypeError('args must be byte strings, not %r' % (args,))
3184.1.10 by Robert Collins
Change the smart server verb for Repository.stream_revisions_chunked to use SearchResults as the request mechanism for downloads.
94
        if type(body) is not str:
95
            raise TypeError('body must be byte string, not %r' % (body,))
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
96
        response, response_handler = self._call_and_read_response(
97
            method, args, body=body, expect_response_body=True)
98
        return (response, response_handler)
3184.1.10 by Robert Collins
Change the smart server verb for Repository.stream_revisions_chunked to use SearchResults as the request mechanism for downloads.
99
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
100
    def call_with_body_readv_array(self, args, body):
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
101
        response, response_handler = self._call_and_read_response(
102
                args[0], args[1:], readv_body=body, expect_response_body=True)
103
        return (response, response_handler)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
104
3842.3.4 by Andrew Bennetts
TestStacking.test_fetch_copies_from_stacked_on now passes using the VersionedFile.insert_record_stream RPC; lots of debugging cruft needs removal though.
105
    def call_with_body_stream(self, args, stream):
106
        response, response_handler = self._call_and_read_response(
107
                args[0], args[1:], body_stream=stream,
108
                expect_response_body=False)
109
        return (response, response_handler)
110
2414.1.1 by Andrew Bennetts
Add some unicode-related tests from the hpss branch, and a few other nits (also from the hpss branch).
111
    def remote_path_from_transport(self, transport):
2414.1.2 by Andrew Bennetts
Deal with review comments.
112
        """Convert transport into a path suitable for using in a request.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
113
2414.1.2 by Andrew Bennetts
Deal with review comments.
114
        Note that the resulting remote path doesn't encode the host name or
115
        anything but path, so it is only safe to use it in requests sent over
116
        the medium from the matching transport.
117
        """
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
118
        return self._medium.remote_path_from_transport(transport)
3297.3.1 by Andrew Bennetts
Raise UnknownSmartMethod automatically from read_response_tuple.
119
3703.3.3 by Andrew Bennetts
Neater effort tests for push by using a _SmartClient.hooks['call'] hook.
120
4797.85.27 by John Arbash Meinel
I've started passing around too many parameters to too many functions.
121
class _SmartClientRequest(object):
4797.85.30 by John Arbash Meinel
Document the functions in the new class.
122
    """Encapsulate the logic for a single request.
123
124
    This class handles things like reconnecting and sending the request a
125
    second time when the connection is reset in the middle. It also handles the
126
    multiple requests that get made if we don't know what protocol the server
127
    supports yet.
128
129
    Generally, you build up one of these objects, passing in the arguments that
130
    you want to send to the server, and then use 'call_and_read_response' to
131
    get the response from the server.
132
    """
4797.85.27 by John Arbash Meinel
I've started passing around too many parameters to too many functions.
133
134
    def __init__(self, client, method, args, body=None, readv_body=None,
135
                 body_stream=None, expect_response_body=True):
136
        self.client = client
137
        self.method = method
138
        self.args = args
139
        self.body = body
140
        self.readv_body = readv_body
141
        self.body_stream = body_stream
142
        self.expect_response_body = expect_response_body
143
144
    def call_and_read_response(self):
4797.85.30 by John Arbash Meinel
Document the functions in the new class.
145
        """Send the request to the server, and read the initial response.
146
147
        This doesn't read all of the body content of the response, instead it
148
        returns (response_tuple, response_handler). response_tuple is the 'ok',
149
        or 'error' information, and 'response_handler' can be used to get the
150
        content stream out.
151
        """
4797.85.29 by John Arbash Meinel
Move the hooks code over as well.
152
        self._run_call_hooks()
4797.85.30 by John Arbash Meinel
Document the functions in the new class.
153
        protocol_version = self.client._medium._protocol_version
154
        if protocol_version is None:
4797.85.27 by John Arbash Meinel
I've started passing around too many parameters to too many functions.
155
            return self._call_determining_protocol_version()
156
        else:
4797.85.30 by John Arbash Meinel
Document the functions in the new class.
157
            return self._call(protocol_version)
4797.85.27 by John Arbash Meinel
I've started passing around too many parameters to too many functions.
158
4797.85.35 by John Arbash Meinel
Do a lookup in 'request.request_handlers', to figure out if a request can be retried.
159
    def _is_safe_to_send_twice(self):
160
        """Check if the current method is re-entrant safe."""
4797.85.37 by John Arbash Meinel
We should refuse to retry on read for -Dnoretry as well.
161
        if self.body_stream is not None or 'noretry' in debug.debug_flags:
4797.85.35 by John Arbash Meinel
Do a lookup in 'request.request_handlers', to figure out if a request can be retried.
162
            # We can't restart a body stream that has already been consumed.
163
            return False
164
        request_type = _mod_request.request_handlers.get_info(self.method)
165
        if request_type in ('read', 'idem', 'semi'):
166
            return True
167
        # If we have gotten this far, 'stream' cannot be retried, because we
168
        # already consumed the local stream.
169
        if request_type in ('semivfs', 'mutate', 'stream'):
170
            return False
171
        trace.mutter('Unknown request type: %s for method %s'
172
                     % (request_type, self.method))
173
        return False
174
4797.85.29 by John Arbash Meinel
Move the hooks code over as well.
175
    def _run_call_hooks(self):
176
        if not _SmartClient.hooks['call']:
177
            return
178
        params = CallHookParams(self.method, self.args, self.body,
179
                                self.readv_body, self.client._medium)
180
        for hook in _SmartClient.hooks['call']:
181
            hook(params)
182
4797.85.30 by John Arbash Meinel
Document the functions in the new class.
183
    def _call(self, protocol_version):
184
        """We know the protocol version.
4797.85.29 by John Arbash Meinel
Move the hooks code over as well.
185
4797.85.30 by John Arbash Meinel
Document the functions in the new class.
186
        So this just sends the request, and then reads the response. This is
187
        where the code will be to retry requests if the connection is closed.
188
        """
189
        response_handler = self._send(protocol_version)
4797.85.34 by John Arbash Meinel
Start implementing retry during read.
190
        try:
191
            response_tuple = response_handler.read_response_tuple(
192
                expect_body=self.expect_response_body)
193
        except errors.ConnectionReset, e:
194
            self.client._medium.reset()
4797.85.35 by John Arbash Meinel
Do a lookup in 'request.request_handlers', to figure out if a request can be retried.
195
            if not self._is_safe_to_send_twice():
196
                raise
4797.85.34 by John Arbash Meinel
Start implementing retry during read.
197
            trace.warning('ConnectionReset reading response for %r, retrying'
198
                          % (self.method,))
199
            trace.log_exception_quietly()
4797.85.38 by John Arbash Meinel
Use the raw _send_no_retry when retrying from a read.
200
            encoder, response_handler = self._construct_protocol(
201
                protocol_version)
202
            self._send_no_retry(encoder)
4797.85.34 by John Arbash Meinel
Start implementing retry during read.
203
            response_tuple = response_handler.read_response_tuple(
204
                expect_body=self.expect_response_body)
4797.85.27 by John Arbash Meinel
I've started passing around too many parameters to too many functions.
205
        return (response_tuple, response_handler)
206
207
    def _call_determining_protocol_version(self):
4797.85.30 by John Arbash Meinel
Document the functions in the new class.
208
        """Determine what protocol the remote server supports.
209
210
        We do this by placing a request in the most recent protocol, and
211
        handling the UnexpectedProtocolVersionMarker from the server.
212
        """
4797.85.27 by John Arbash Meinel
I've started passing around too many parameters to too many functions.
213
        for protocol_version in [3, 2]:
214
            if protocol_version == 2:
215
                # If v3 doesn't work, the remote side is older than 1.6.
216
                self.client._medium._remember_remote_is_before((1, 6))
217
            try:
4797.85.30 by John Arbash Meinel
Document the functions in the new class.
218
                response_tuple, response_handler = self._call(protocol_version)
4797.85.27 by John Arbash Meinel
I've started passing around too many parameters to too many functions.
219
            except errors.UnexpectedProtocolVersionMarker, err:
220
                # TODO: We could recover from this without disconnecting if
221
                # we recognise the protocol version.
4797.85.30 by John Arbash Meinel
Document the functions in the new class.
222
                trace.warning(
4797.85.27 by John Arbash Meinel
I've started passing around too many parameters to too many functions.
223
                    'Server does not understand Bazaar network protocol %d,'
224
                    ' reconnecting.  (Upgrade the server to avoid this.)'
225
                    % (protocol_version,))
226
                self.client._medium.disconnect()
227
                continue
228
            except errors.ErrorFromSmartServer:
229
                # If we received an error reply from the server, then it
230
                # must be ok with this protocol version.
231
                self.client._medium._protocol_version = protocol_version
232
                raise
233
            else:
234
                self.client._medium._protocol_version = protocol_version
235
                return response_tuple, response_handler
236
        raise errors.SmartProtocolError(
237
            'Server is not a Bazaar server: ' + str(err))
238
4797.85.28 by John Arbash Meinel
Move all of the send logic into the _SmartClientRequest class.
239
    def _construct_protocol(self, version):
4797.85.30 by John Arbash Meinel
Document the functions in the new class.
240
        """Build the encoding stack for a given protocol version."""
4797.85.28 by John Arbash Meinel
Move all of the send logic into the _SmartClientRequest class.
241
        request = self.client._medium.get_request()
242
        if version == 3:
243
            request_encoder = protocol.ProtocolThreeRequester(request)
244
            response_handler = message.ConventionalResponseHandler()
245
            response_proto = protocol.ProtocolThreeDecoder(
246
                response_handler, expect_version_marker=True)
247
            response_handler.setProtoAndMediumRequest(response_proto, request)
248
        elif version == 2:
249
            request_encoder = protocol.SmartClientRequestProtocolTwo(request)
250
            response_handler = request_encoder
251
        else:
252
            request_encoder = protocol.SmartClientRequestProtocolOne(request)
253
            response_handler = request_encoder
254
        return request_encoder, response_handler
255
256
    def _send(self, protocol_version):
4797.85.30 by John Arbash Meinel
Document the functions in the new class.
257
        """Encode the request, and send it to the server.
258
259
        This will retry a request if we get a ConnectionReset while sending the
260
        request to the server. (Unless we have a body_stream that we have
261
        already started consuming, since we can't restart body_streams)
262
263
        :return: response_handler as defined by _construct_protocol
264
        """
4797.85.28 by John Arbash Meinel
Move all of the send logic into the _SmartClientRequest class.
265
        encoder, response_handler = self._construct_protocol(protocol_version)
266
        try:
267
            self._send_no_retry(encoder)
268
        except errors.ConnectionReset, e:
269
            # If we fail during the _send_no_retry phase, then we can
270
            # be confident that the server did not get our request, because we
271
            # haven't started waiting for the reply yet. So try the request
272
            # again. We only issue a single retry, because if the connection
273
            # really is down, there is no reason to loop endlessly.
274
275
            # Connection is dead, so close our end of it.
276
            self.client._medium.reset()
4797.91.5 by John Arbash Meinel
Add -Dnoretry as a way to disable all retrying code.
277
            if (('noretry' in debug.debug_flags)
4797.93.4 by John Arbash Meinel
Merge in the debug flag updates.
278
                or (self.body_stream is not None
279
                    and encoder.body_stream_started)):
4797.85.30 by John Arbash Meinel
Document the functions in the new class.
280
                # We can't restart a body_stream that has been partially
281
                # consumed, so we don't retry.
4797.93.2 by John Arbash Meinel
Merge the refactored SmartClientRequest code, and update to match it.
282
                # Note: We don't have to worry about
283
                #   SmartClientRequestProtocolOne or Two, because they don't
284
                #   support client-side body streams.
4797.85.28 by John Arbash Meinel
Move all of the send logic into the _SmartClientRequest class.
285
                raise
4797.91.4 by John Arbash Meinel
Clean up the logging slightly.
286
            trace.warning('ConnectionReset calling %r, retrying'
287
                          % (self.method,))
4797.85.28 by John Arbash Meinel
Move all of the send logic into the _SmartClientRequest class.
288
            trace.log_exception_quietly()
289
            encoder, response_handler = self._construct_protocol(
290
                protocol_version)
291
            self._send_no_retry(encoder)
292
        return response_handler
293
294
    def _send_no_retry(self, encoder):
4797.85.30 by John Arbash Meinel
Document the functions in the new class.
295
        """Just encode the request and try to send it."""
4797.85.28 by John Arbash Meinel
Move all of the send logic into the _SmartClientRequest class.
296
        encoder.set_headers(self.client._headers)
297
        if self.body is not None:
298
            if self.readv_body is not None:
299
                raise AssertionError(
300
                    "body and readv_body are mutually exclusive.")
301
            if self.body_stream is not None:
302
                raise AssertionError(
303
                    "body and body_stream are mutually exclusive.")
304
            encoder.call_with_body_bytes((self.method, ) + self.args, self.body)
305
        elif self.readv_body is not None:
306
            if self.body_stream is not None:
307
                raise AssertionError(
308
                    "readv_body and body_stream are mutually exclusive.")
309
            encoder.call_with_body_readv_array((self.method, ) + self.args,
310
                                               self.readv_body)
311
        elif self.body_stream is not None:
312
            encoder.call_with_body_stream((self.method, ) + self.args,
313
                                          self.body_stream)
314
        else:
315
            encoder.call(self.method, *self.args)
316
4797.85.27 by John Arbash Meinel
I've started passing around too many parameters to too many functions.
317
3703.3.3 by Andrew Bennetts
Neater effort tests for push by using a _SmartClient.hooks['call'] hook.
318
class SmartClientHooks(hooks.Hooks):
319
5622.3.10 by Jelmer Vernooij
Don't require arguments to hooks.
320
    def __init__(self):
321
        hooks.Hooks.__init__(self, "bzrlib.smart.client", "_SmartClient.hooks")
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
322
        self.add_hook('call',
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
323
            "Called when the smart client is submitting a request to the "
324
            "smart server. Called with a bzrlib.smart.client.CallHookParams "
325
            "object. Streaming request bodies, and responses, are not "
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
326
            "accessible.", None)
327
328
5622.3.10 by Jelmer Vernooij
Don't require arguments to hooks.
329
_SmartClient.hooks = SmartClientHooks()
3703.3.3 by Andrew Bennetts
Neater effort tests for push by using a _SmartClient.hooks['call'] hook.
330
331
332
class CallHookParams(object):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
333
3731.2.1 by Andrew Bennetts
Show total HPSS calls (if any) on stderr when -Dhpss is active.
334
    def __init__(self, method, args, body, readv_body, medium):
3703.3.3 by Andrew Bennetts
Neater effort tests for push by using a _SmartClient.hooks['call'] hook.
335
        self.method = method
336
        self.args = args
337
        self.body = body
338
        self.readv_body = readv_body
3731.2.1 by Andrew Bennetts
Show total HPSS calls (if any) on stderr when -Dhpss is active.
339
        self.medium = medium
3703.3.3 by Andrew Bennetts
Neater effort tests for push by using a _SmartClient.hooks['call'] hook.
340
341
    def __repr__(self):
342
        attrs = dict((k, v) for (k, v) in self.__dict__.iteritems()
343
                     if v is not None)
344
        return '<%s %r>' % (self.__class__.__name__, attrs)
345
346
    def __eq__(self, other):
347
        if type(other) is not type(self):
348
            return NotImplemented
349
        return self.__dict__ == other.__dict__
350
351
    def __ne__(self, other):
352
        return not self == other