~bzr-pqm/bzr/bzr.dev

4889.4.2 by John Arbash Meinel
Change the amount buffered to be a 'constant' that we can get at.
1
# Copyright (C) 2006, 2007, 2008, 2009 Canonical Ltd
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
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.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
16
2018.5.19 by Andrew Bennetts
Add docstrings to all the new modules, and a few other places.
17
"""Wire-level encoding and decoding of requests and responses for the smart
18
client and server.
19
"""
20
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
21
import collections
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
22
from cStringIO import StringIO
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
23
import struct
3245.4.49 by Andrew Bennetts
Distinguish between errors in decoding a message into message parts from errors in handling decoded message parts, and use that to make sure that entire requests are read even when they result in exceptions.
24
import sys
4913.1.1 by John Arbash Meinel
Switch to using thread.get_ident() which is available on all python versions.
25
import thread
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
26
import threading
2664.4.1 by John Arbash Meinel
Add timing information for call/response groups for hpss
27
import time
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
28
3195.3.13 by Andrew Bennetts
Start writing call* methods for version 3 of the HPSS client protocol.
29
import bzrlib
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
30
from bzrlib import (
31
    debug,
32
    errors,
33
    osutils,
34
    )
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
35
from bzrlib.smart import message, request
2621.3.1 by Andrew Bennetts
Log errors from the smart server in the trace file, to make debugging test failures (and live failures!) easier.
36
from bzrlib.trace import log_exception_quietly, mutter
2694.5.4 by Jelmer Vernooij
Move bzrlib.util.bencode to bzrlib._bencode_py.
37
from bzrlib.bencode import bdecode_as_tuple, bencode
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
38
39
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
40
# Protocol version strings.  These are sent as prefixes of bzr requests and
41
# responses to identify the protocol version being used. (There are no version
42
# one strings because that version doesn't send any).
43
REQUEST_VERSION_TWO = 'bzr request 2\n'
44
RESPONSE_VERSION_TWO = 'bzr response 2\n'
45
3245.4.60 by Andrew Bennetts
Update the protocol v3 version string to say 'bzr 1.6'.
46
MESSAGE_VERSION_THREE = 'bzr message 3 (bzr 1.6)\n'
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
47
RESPONSE_VERSION_THREE = REQUEST_VERSION_THREE = MESSAGE_VERSION_THREE
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
48
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
49
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
50
def _recv_tuple(from_file):
51
    req_line = from_file.readline()
52
    return _decode_tuple(req_line)
53
54
55
def _decode_tuple(req_line):
3376.2.11 by Martin Pool
Compare to None using is/is not not ==
56
    if req_line is None or req_line == '':
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
57
        return None
58
    if req_line[-1] != '\n':
59
        raise errors.SmartProtocolError("request %r not terminated" % req_line)
60
    return tuple(req_line[:-1].split('\x01'))
61
62
63
def _encode_tuple(args):
64
    """Encode the tuple args to a bytestream."""
65
    return '\x01'.join(args) + '\n'
66
67
3245.4.26 by Andrew Bennetts
Rename 'setProtoAndMedium' to more accurate 'setProtoAndMediumRequest', add ABCs for Requesters and ResponseHandlers.
68
class Requester(object):
69
    """Abstract base class for an object that can issue requests on a smart
70
    medium.
71
    """
72
73
    def call(self, *args):
74
        """Make a remote call.
75
76
        :param args: the arguments of this call.
77
        """
78
        raise NotImplementedError(self.call)
79
80
    def call_with_body_bytes(self, args, body):
81
        """Make a remote call with a body.
82
83
        :param args: the arguments of this call.
84
        :type body: str
85
        :param body: the body to send with the request.
86
        """
87
        raise NotImplementedError(self.call_with_body_bytes)
88
89
    def call_with_body_readv_array(self, args, body):
90
        """Make a remote call with a readv array.
91
92
        :param args: the arguments of this call.
93
        :type body: iterable of (start, length) tuples.
94
        :param body: the readv ranges to send with this request.
95
        """
96
        raise NotImplementedError(self.call_with_body_readv_array)
97
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
98
    def set_headers(self, headers):
99
        raise NotImplementedError(self.set_headers)
100
3245.4.26 by Andrew Bennetts
Rename 'setProtoAndMedium' to more accurate 'setProtoAndMediumRequest', add ABCs for Requesters and ResponseHandlers.
101
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
102
class SmartProtocolBase(object):
103
    """Methods common to client and server"""
104
105
    # TODO: this only actually accomodates a single block; possibly should
106
    # support multiple chunks?
107
    def _encode_bulk_data(self, body):
108
        """Encode body as a bulk data chunk."""
109
        return ''.join(('%d\n' % len(body), body, 'done\n'))
110
111
    def _serialise_offsets(self, offsets):
112
        """Serialise a readv offset list."""
113
        txt = []
114
        for start, length in offsets:
115
            txt.append('%d,%d' % (start, length))
116
        return '\n'.join(txt)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
117
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
118
119
class SmartServerRequestProtocolOne(SmartProtocolBase):
120
    """Server-side encoding and decoding logic for smart version 1."""
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
121
4760.1.1 by Andrew Bennetts
Add optional jail_root argument to SmartServerRequest and friends, and use it in the WSGI glue. Allows opening branches in shared repos via bzr+http (assuming the repo should be accessible).
122
    def __init__(self, backing_transport, write_func, root_client_path='/',
123
            jail_root=None):
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
124
        self._backing_transport = backing_transport
2692.1.1 by Andrew Bennetts
Add translate_client_path method to SmartServerRequest.
125
        self._root_client_path = root_client_path
4760.1.1 by Andrew Bennetts
Add optional jail_root argument to SmartServerRequest and friends, and use it in the WSGI glue. Allows opening branches in shared repos via bzr+http (assuming the repo should be accessible).
126
        self._jail_root = jail_root
3245.4.21 by Andrew Bennetts
Remove 'excess_buffer' attribute and another crufty comment.
127
        self.unused_data = ''
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
128
        self._finished = False
129
        self.in_buffer = ''
3245.4.59 by Andrew Bennetts
Various tweaks in response to Martin's review.
130
        self._has_dispatched = False
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
131
        self.request = None
132
        self._body_decoder = None
2664.4.6 by John Arbash Meinel
Restore a line that shouldn't have been removed
133
        self._write_func = write_func
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
134
135
    def accept_bytes(self, bytes):
136
        """Take bytes, and advance the internal state machine appropriately.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
137
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
138
        :param bytes: must be a byte string
139
        """
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
140
        if not isinstance(bytes, str):
141
            raise ValueError(bytes)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
142
        self.in_buffer += bytes
3245.4.59 by Andrew Bennetts
Various tweaks in response to Martin's review.
143
        if not self._has_dispatched:
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
144
            if '\n' not in self.in_buffer:
145
                # no command line yet
146
                return
3245.4.59 by Andrew Bennetts
Various tweaks in response to Martin's review.
147
            self._has_dispatched = True
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
148
            try:
149
                first_line, self.in_buffer = self.in_buffer.split('\n', 1)
150
                first_line += '\n'
151
                req_args = _decode_tuple(first_line)
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
152
                self.request = request.SmartServerRequestHandler(
2692.1.1 by Andrew Bennetts
Add translate_client_path method to SmartServerRequest.
153
                    self._backing_transport, commands=request.request_handlers,
4760.1.1 by Andrew Bennetts
Add optional jail_root argument to SmartServerRequest and friends, and use it in the WSGI glue. Allows opening branches in shared repos via bzr+http (assuming the repo should be accessible).
154
                    root_client_path=self._root_client_path,
155
                    jail_root=self._jail_root)
4634.6.30 by Andrew Bennetts
Remove SmartServerRequest.dispatch_command, fix SmartServerRequest.args_received.
156
                self.request.args_received(req_args)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
157
                if self.request.finished_reading:
158
                    # trivial request
3245.4.21 by Andrew Bennetts
Remove 'excess_buffer' attribute and another crufty comment.
159
                    self.unused_data = self.in_buffer
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
160
                    self.in_buffer = ''
2432.4.3 by Robert Collins
Refactor the HPSS Response code to take SmartServerResponse rather than args and body.
161
                    self._send_response(self.request.response)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
162
            except KeyboardInterrupt:
163
                raise
3245.4.29 by Andrew Bennetts
Add/tidy some comments, remove dud test_errors_are_logged test, add explicit UnknownSmartMethod to v3.
164
            except errors.UnknownSmartMethod, err:
165
                protocol_error = errors.SmartProtocolError(
166
                    "bad request %r" % (err.verb,))
167
                failure = request.FailedSmartServerResponse(
168
                    ('error', str(protocol_error)))
169
                self._send_response(failure)
170
                return
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
171
            except Exception, exception:
172
                # everything else: pass to client, flush, and quit
2621.3.1 by Andrew Bennetts
Log errors from the smart server in the trace file, to make debugging test failures (and live failures!) easier.
173
                log_exception_quietly()
2432.4.3 by Robert Collins
Refactor the HPSS Response code to take SmartServerResponse rather than args and body.
174
                self._send_response(request.FailedSmartServerResponse(
175
                    ('error', str(exception))))
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
176
                return
177
3245.4.59 by Andrew Bennetts
Various tweaks in response to Martin's review.
178
        if self._has_dispatched:
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
179
            if self._finished:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
180
                # nothing to do.XXX: this routine should be a single state
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
181
                # machine too.
3245.4.21 by Andrew Bennetts
Remove 'excess_buffer' attribute and another crufty comment.
182
                self.unused_data += self.in_buffer
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
183
                self.in_buffer = ''
184
                return
185
            if self._body_decoder is None:
186
                self._body_decoder = LengthPrefixedBodyDecoder()
187
            self._body_decoder.accept_bytes(self.in_buffer)
188
            self.in_buffer = self._body_decoder.unused_data
189
            body_data = self._body_decoder.read_pending_data()
190
            self.request.accept_body(body_data)
191
            if self._body_decoder.finished_reading:
192
                self.request.end_of_body()
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
193
                if not self.request.finished_reading:
194
                    raise AssertionError("no more body, request not finished")
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
195
            if self.request.response is not None:
2432.4.3 by Robert Collins
Refactor the HPSS Response code to take SmartServerResponse rather than args and body.
196
                self._send_response(self.request.response)
3245.4.21 by Andrew Bennetts
Remove 'excess_buffer' attribute and another crufty comment.
197
                self.unused_data = self.in_buffer
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
198
                self.in_buffer = ''
199
            else:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
200
                if self.request.finished_reading:
201
                    raise AssertionError(
202
                        "no response and we have finished reading.")
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
203
2432.4.3 by Robert Collins
Refactor the HPSS Response code to take SmartServerResponse rather than args and body.
204
    def _send_response(self, response):
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
205
        """Send a smart server response down the output stream."""
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
206
        if self._finished:
207
            raise AssertionError('response already sent')
2432.4.3 by Robert Collins
Refactor the HPSS Response code to take SmartServerResponse rather than args and body.
208
        args = response.args
209
        body = response.body
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
210
        self._finished = True
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
211
        self._write_protocol_version()
2432.4.6 by Robert Collins
Include success/failure feedback in SmartProtocolTwo responses to allow robust handling in the future.
212
        self._write_success_or_failure_prefix(response)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
213
        self._write_func(_encode_tuple(args))
214
        if body is not None:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
215
            if not isinstance(body, str):
216
                raise ValueError(body)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
217
            bytes = self._encode_bulk_data(body)
218
            self._write_func(bytes)
219
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
220
    def _write_protocol_version(self):
221
        """Write any prefixes this protocol requires.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
222
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
223
        Version one doesn't send protocol versions.
224
        """
225
2432.4.6 by Robert Collins
Include success/failure feedback in SmartProtocolTwo responses to allow robust handling in the future.
226
    def _write_success_or_failure_prefix(self, response):
227
        """Write the protocol specific success/failure prefix.
228
229
        For SmartServerRequestProtocolOne this is omitted but we
230
        call is_successful to ensure that the response is valid.
231
        """
232
        response.is_successful()
233
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
234
    def next_read_size(self):
235
        if self._finished:
236
            return 0
237
        if self._body_decoder is None:
238
            return 1
239
        else:
240
            return self._body_decoder.next_read_size()
241
242
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
243
class SmartServerRequestProtocolTwo(SmartServerRequestProtocolOne):
244
    r"""Version two of the server side of the smart protocol.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
245
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
246
    This prefixes responses with the value of RESPONSE_VERSION_TWO.
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
247
    """
248
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
249
    response_marker = RESPONSE_VERSION_TWO
250
    request_marker = REQUEST_VERSION_TWO
251
2432.4.6 by Robert Collins
Include success/failure feedback in SmartProtocolTwo responses to allow robust handling in the future.
252
    def _write_success_or_failure_prefix(self, response):
253
        """Write the protocol specific success/failure prefix."""
254
        if response.is_successful():
255
            self._write_func('success\n')
256
        else:
257
            self._write_func('failed\n')
258
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
259
    def _write_protocol_version(self):
260
        r"""Write any prefixes this protocol requires.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
261
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
262
        Version two sends the value of RESPONSE_VERSION_TWO.
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
263
        """
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
264
        self._write_func(self.response_marker)
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
265
2748.4.2 by Andrew Bennetts
Add protocol (version two) support for streaming bodies (using chunking) in responses.
266
    def _send_response(self, response):
267
        """Send a smart server response down the output stream."""
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
268
        if (self._finished):
269
            raise AssertionError('response already sent')
2748.4.2 by Andrew Bennetts
Add protocol (version two) support for streaming bodies (using chunking) in responses.
270
        self._finished = True
271
        self._write_protocol_version()
272
        self._write_success_or_failure_prefix(response)
273
        self._write_func(_encode_tuple(response.args))
274
        if response.body is not None:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
275
            if not isinstance(response.body, str):
276
                raise AssertionError('body must be a str')
277
            if not (response.body_stream is None):
278
                raise AssertionError(
279
                    'body_stream and body cannot both be set')
2748.4.2 by Andrew Bennetts
Add protocol (version two) support for streaming bodies (using chunking) in responses.
280
            bytes = self._encode_bulk_data(response.body)
281
            self._write_func(bytes)
282
        elif response.body_stream is not None:
2748.4.10 by Andrew Bennetts
Fix chunking serialisation to be current with the latest changes to the protocol, and improve the tests to make it harder to have them desynchronised.
283
            _send_stream(response.body_stream, self._write_func)
284
285
286
def _send_stream(stream, write_func):
2748.4.16 by Andrew Bennetts
Tweaks suggested by review.
287
    write_func('chunked\n')
2748.4.10 by Andrew Bennetts
Fix chunking serialisation to be current with the latest changes to the protocol, and improve the tests to make it harder to have them desynchronised.
288
    _send_chunks(stream, write_func)
289
    write_func('END\n')
2748.4.4 by Andrew Bennetts
Extract a _send_chunks function to make testing easier.
290
291
292
def _send_chunks(stream, write_func):
293
    for chunk in stream:
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
294
        if isinstance(chunk, str):
295
            bytes = "%x\n%s" % (len(chunk), chunk)
296
            write_func(bytes)
297
        elif isinstance(chunk, request.FailedSmartServerResponse):
2748.4.10 by Andrew Bennetts
Fix chunking serialisation to be current with the latest changes to the protocol, and improve the tests to make it harder to have them desynchronised.
298
            write_func('ERR\n')
299
            _send_chunks(chunk.args, write_func)
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
300
            return
301
        else:
2535.4.19 by Andrew Bennetts
Fix some trivial NameErrors in error handling.
302
            raise errors.BzrError(
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
303
                'Chunks must be str or FailedSmartServerResponse, got %r'
2535.4.19 by Andrew Bennetts
Fix some trivial NameErrors in error handling.
304
                % chunk)
2748.4.2 by Andrew Bennetts
Add protocol (version two) support for streaming bodies (using chunking) in responses.
305
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
306
3195.3.7 by Andrew Bennetts
Make the '_extract_* helpers more robust by adding a _NeedMoreBytes exception to _StatefulDecoder.
307
class _NeedMoreBytes(Exception):
308
    """Raise this inside a _StatefulDecoder to stop decoding until more bytes
309
    have been received.
310
    """
311
3195.3.18 by Andrew Bennetts
call_with_body_bytes now works with v3 (e.g. test_copy_content_remote_to_local passes). Lots of debugging cruft, though.
312
    def __init__(self, count=None):
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
313
        """Constructor.
314
315
        :param count: the total number of bytes needed by the current state.
316
            May be None if the number of bytes needed is unknown.
317
        """
3195.3.18 by Andrew Bennetts
call_with_body_bytes now works with v3 (e.g. test_copy_content_remote_to_local passes). Lots of debugging cruft, though.
318
        self.count = count
319
3195.3.7 by Andrew Bennetts
Make the '_extract_* helpers more robust by adding a _NeedMoreBytes exception to _StatefulDecoder.
320
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
321
class _StatefulDecoder(object):
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
322
    """Base class for writing state machines to decode byte streams.
323
324
    Subclasses should provide a self.state_accept attribute that accepts bytes
325
    and, if appropriate, updates self.state_accept to a different function.
326
    accept_bytes will call state_accept as often as necessary to make sure the
327
    state machine has progressed as far as possible before it returns.
328
329
    See ProtocolThreeDecoder for an example subclass.
330
    """
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
331
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
332
    def __init__(self):
333
        self.finished_reading = False
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
334
        self._in_buffer_list = []
335
        self._in_buffer_len = 0
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
336
        self.unused_data = ''
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
337
        self.bytes_left = None
3195.3.22 by Andrew Bennetts
Fix more tests.
338
        self._number_needed_bytes = None
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
339
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
340
    def _get_in_buffer(self):
341
        if len(self._in_buffer_list) == 1:
342
            return self._in_buffer_list[0]
343
        in_buffer = ''.join(self._in_buffer_list)
3649.5.5 by John Arbash Meinel
Fix the test suite.
344
        if len(in_buffer) != self._in_buffer_len:
345
            raise AssertionError(
346
                "Length of buffer did not match expected value: %s != %s"
347
                % self._in_buffer_len, len(in_buffer))
3649.5.2 by John Arbash Meinel
When we are waiting on a big stream, allow
348
        self._in_buffer_list = [in_buffer]
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
349
        return in_buffer
350
3649.5.2 by John Arbash Meinel
When we are waiting on a big stream, allow
351
    def _get_in_bytes(self, count):
352
        """Grab X bytes from the input_buffer.
353
354
        Callers should have already checked that self._in_buffer_len is >
355
        count. Note, this does not consume the bytes from the buffer. The
356
        caller will still need to call _get_in_buffer() and then
357
        _set_in_buffer() if they actually need to consume the bytes.
358
        """
359
        # check if we can yield the bytes from just the first entry in our list
3649.5.5 by John Arbash Meinel
Fix the test suite.
360
        if len(self._in_buffer_list) == 0:
361
            raise AssertionError('Callers must be sure we have buffered bytes'
362
                ' before calling _get_in_bytes')
3649.5.2 by John Arbash Meinel
When we are waiting on a big stream, allow
363
        if len(self._in_buffer_list[0]) > count:
364
            return self._in_buffer_list[0][:count]
365
        # We can't yield it from the first buffer, so collapse all buffers, and
366
        # yield it from that
367
        in_buf = self._get_in_buffer()
368
        return in_buf[:count]
369
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
370
    def _set_in_buffer(self, new_buf):
371
        if new_buf is not None:
372
            self._in_buffer_list = [new_buf]
373
            self._in_buffer_len = len(new_buf)
374
        else:
375
            self._in_buffer_list = []
376
            self._in_buffer_len = 0
377
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
378
    def accept_bytes(self, bytes):
379
        """Decode as much of bytes as possible.
380
381
        If 'bytes' contains too much data it will be appended to
382
        self.unused_data.
383
384
        finished_reading will be set when no more data is required.  Further
385
        data will be appended to self.unused_data.
386
        """
387
        # accept_bytes is allowed to change the state
3195.3.22 by Andrew Bennetts
Fix more tests.
388
        self._number_needed_bytes = None
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
389
        # lsprof puts a very large amount of time on this specific call for
390
        # large readv arrays
391
        self._in_buffer_list.append(bytes)
392
        self._in_buffer_len += len(bytes)
3195.3.7 by Andrew Bennetts
Make the '_extract_* helpers more robust by adding a _NeedMoreBytes exception to _StatefulDecoder.
393
        try:
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
394
            # Run the function for the current state.
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
395
            current_state = self.state_accept
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
396
            self.state_accept()
3195.3.7 by Andrew Bennetts
Make the '_extract_* helpers more robust by adding a _NeedMoreBytes exception to _StatefulDecoder.
397
            while current_state != self.state_accept:
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
398
                # The current state has changed.  Run the function for the new
399
                # current state, so that it can:
400
                #   - decode any unconsumed bytes left in a buffer, and
401
                #   - signal how many more bytes are expected (via raising
402
                #     _NeedMoreBytes).
3195.3.7 by Andrew Bennetts
Make the '_extract_* helpers more robust by adding a _NeedMoreBytes exception to _StatefulDecoder.
403
                current_state = self.state_accept
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
404
                self.state_accept()
3195.3.22 by Andrew Bennetts
Fix more tests.
405
        except _NeedMoreBytes, e:
406
            self._number_needed_bytes = e.count
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
407
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
408
409
class ChunkedBodyDecoder(_StatefulDecoder):
410
    """Decoder for chunked body data.
411
2748.4.9 by Andrew Bennetts
Merge from hpss-protocol-docs.
412
    This is very similar the HTTP's chunked encoding.  See the description of
413
    streamed body data in `doc/developers/network-protocol.txt` for details.
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
414
    """
415
416
    def __init__(self):
417
        _StatefulDecoder.__init__(self)
2748.4.16 by Andrew Bennetts
Tweaks suggested by review.
418
        self.state_accept = self._state_accept_expecting_header
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
419
        self.chunk_in_progress = None
420
        self.chunks = collections.deque()
2748.4.6 by Andrew Bennetts
Use chunks for stream errors, rather than the response tuple format.
421
        self.error = False
422
        self.error_in_progress = None
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
423
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
424
    def next_read_size(self):
2748.4.7 by Andrew Bennetts
Change the end-of-body marker to something clearer than a zero-length chunk.
425
        # Note: the shortest possible chunk is 2 bytes: '0\n', and the
426
        # end-of-body marker is 4 bytes: 'END\n'.
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
427
        if self.state_accept == self._state_accept_reading_chunk:
428
            # We're expecting more chunk content.  So we're expecting at least
2748.4.7 by Andrew Bennetts
Change the end-of-body marker to something clearer than a zero-length chunk.
429
            # the rest of this chunk plus an END chunk.
430
            return self.bytes_left + 4
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
431
        elif self.state_accept == self._state_accept_expecting_length:
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
432
            if self._in_buffer_len == 0:
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
433
                # We're expecting a chunk length.  There's at least two bytes
434
                # left: a digit plus '\n'.
435
                return 2
436
            else:
437
                # We're in the middle of reading a chunk length.  So there's at
438
                # least one byte left, the '\n' that terminates the length.
439
                return 1
440
        elif self.state_accept == self._state_accept_reading_unused:
441
            return 1
2748.4.16 by Andrew Bennetts
Tweaks suggested by review.
442
        elif self.state_accept == self._state_accept_expecting_header:
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
443
            return max(0, len('chunked\n') - self._in_buffer_len)
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
444
        else:
445
            raise AssertionError("Impossible state: %r" % (self.state_accept,))
446
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
447
    def read_next_chunk(self):
448
        try:
449
            return self.chunks.popleft()
450
        except IndexError:
451
            return None
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
452
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
453
    def _extract_line(self):
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
454
        in_buf = self._get_in_buffer()
455
        pos = in_buf.find('\n')
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
456
        if pos == -1:
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
457
            # We haven't read a complete line yet, so request more bytes before
458
            # we continue.
3245.4.29 by Andrew Bennetts
Add/tidy some comments, remove dud test_errors_are_logged test, add explicit UnknownSmartMethod to v3.
459
            raise _NeedMoreBytes(1)
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
460
        line = in_buf[:pos]
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
461
        # Trim the prefix (including '\n' delimiter) from the _in_buffer.
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
462
        self._set_in_buffer(in_buf[pos+1:])
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
463
        return line
464
465
    def _finished(self):
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
466
        self.unused_data = self._get_in_buffer()
467
        self._in_buffer_list = []
468
        self._in_buffer_len = 0
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
469
        self.state_accept = self._state_accept_reading_unused
2748.4.6 by Andrew Bennetts
Use chunks for stream errors, rather than the response tuple format.
470
        if self.error:
471
            error_args = tuple(self.error_in_progress)
472
            self.chunks.append(request.FailedSmartServerResponse(error_args))
473
            self.error_in_progress = None
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
474
        self.finished_reading = True
475
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
476
    def _state_accept_expecting_header(self):
2748.4.16 by Andrew Bennetts
Tweaks suggested by review.
477
        prefix = self._extract_line()
3195.3.8 by Andrew Bennetts
Use _NeedMoreBytes to improve earlier protocol implementations a little, and make test_errors_are_logged pass.
478
        if prefix == 'chunked':
2748.4.16 by Andrew Bennetts
Tweaks suggested by review.
479
            self.state_accept = self._state_accept_expecting_length
480
        else:
481
            raise errors.SmartProtocolError(
482
                'Bad chunked body header: "%s"' % (prefix,))
483
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
484
    def _state_accept_expecting_length(self):
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
485
        prefix = self._extract_line()
3195.3.8 by Andrew Bennetts
Use _NeedMoreBytes to improve earlier protocol implementations a little, and make test_errors_are_logged pass.
486
        if prefix == 'ERR':
2748.4.6 by Andrew Bennetts
Use chunks for stream errors, rather than the response tuple format.
487
            self.error = True
488
            self.error_in_progress = []
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
489
            self._state_accept_expecting_length()
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
490
            return
2748.4.7 by Andrew Bennetts
Change the end-of-body marker to something clearer than a zero-length chunk.
491
        elif prefix == 'END':
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
492
            # We've read the end-of-body marker.
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
493
            # Any further bytes are unused data, including the bytes left in
494
            # the _in_buffer.
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
495
            self._finished()
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
496
            return
2748.4.7 by Andrew Bennetts
Change the end-of-body marker to something clearer than a zero-length chunk.
497
        else:
498
            self.bytes_left = int(prefix, 16)
499
            self.chunk_in_progress = ''
500
            self.state_accept = self._state_accept_reading_chunk
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
501
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
502
    def _state_accept_reading_chunk(self):
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
503
        in_buf = self._get_in_buffer()
504
        in_buffer_len = len(in_buf)
505
        self.chunk_in_progress += in_buf[:self.bytes_left]
506
        self._set_in_buffer(in_buf[self.bytes_left:])
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
507
        self.bytes_left -= in_buffer_len
508
        if self.bytes_left <= 0:
509
            # Finished with chunk
510
            self.bytes_left = None
2748.4.6 by Andrew Bennetts
Use chunks for stream errors, rather than the response tuple format.
511
            if self.error:
512
                self.error_in_progress.append(self.chunk_in_progress)
513
            else:
514
                self.chunks.append(self.chunk_in_progress)
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
515
            self.chunk_in_progress = None
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
516
            self.state_accept = self._state_accept_expecting_length
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
517
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
518
    def _state_accept_reading_unused(self):
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
519
        self.unused_data += self._get_in_buffer()
520
        self._in_buffer_list = []
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
521
522
523
class LengthPrefixedBodyDecoder(_StatefulDecoder):
524
    """Decodes the length-prefixed bulk data."""
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
525
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
526
    def __init__(self):
527
        _StatefulDecoder.__init__(self)
528
        self.state_accept = self._state_accept_expecting_length
529
        self.state_read = self._state_read_no_data
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
530
        self._body = ''
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
531
        self._trailer_buffer = ''
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
532
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
533
    def next_read_size(self):
534
        if self.bytes_left is not None:
535
            # Ideally we want to read all the remainder of the body and the
536
            # trailer in one go.
537
            return self.bytes_left + 5
538
        elif self.state_accept == self._state_accept_reading_trailer:
539
            # Just the trailer left
540
            return 5 - len(self._trailer_buffer)
541
        elif self.state_accept == self._state_accept_expecting_length:
542
            # There's still at least 6 bytes left ('\n' to end the length, plus
543
            # 'done\n').
544
            return 6
545
        else:
546
            # Reading excess data.  Either way, 1 byte at a time is fine.
547
            return 1
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
548
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
549
    def read_pending_data(self):
550
        """Return any pending data that has been decoded."""
551
        return self.state_read()
552
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
553
    def _state_accept_expecting_length(self):
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
554
        in_buf = self._get_in_buffer()
555
        pos = in_buf.find('\n')
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
556
        if pos == -1:
557
            return
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
558
        self.bytes_left = int(in_buf[:pos])
559
        self._set_in_buffer(in_buf[pos+1:])
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
560
        self.state_accept = self._state_accept_reading_body
561
        self.state_read = self._state_read_body_buffer
562
563
    def _state_accept_reading_body(self):
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
564
        in_buf = self._get_in_buffer()
565
        self._body += in_buf
566
        self.bytes_left -= len(in_buf)
567
        self._set_in_buffer(None)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
568
        if self.bytes_left <= 0:
569
            # Finished with body
570
            if self.bytes_left != 0:
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
571
                self._trailer_buffer = self._body[self.bytes_left:]
572
                self._body = self._body[:self.bytes_left]
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
573
            self.bytes_left = None
574
            self.state_accept = self._state_accept_reading_trailer
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
575
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
576
    def _state_accept_reading_trailer(self):
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
577
        self._trailer_buffer += self._get_in_buffer()
578
        self._set_in_buffer(None)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
579
        # TODO: what if the trailer does not match "done\n"?  Should this raise
580
        # a ProtocolViolation exception?
581
        if self._trailer_buffer.startswith('done\n'):
582
            self.unused_data = self._trailer_buffer[len('done\n'):]
583
            self.state_accept = self._state_accept_reading_unused
584
            self.finished_reading = True
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
585
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
586
    def _state_accept_reading_unused(self):
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
587
        self.unused_data += self._get_in_buffer()
588
        self._set_in_buffer(None)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
589
590
    def _state_read_no_data(self):
591
        return ''
592
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
593
    def _state_read_body_buffer(self):
594
        result = self._body
595
        self._body = ''
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
596
        return result
597
598
3245.4.26 by Andrew Bennetts
Rename 'setProtoAndMedium' to more accurate 'setProtoAndMediumRequest', add ABCs for Requesters and ResponseHandlers.
599
class SmartClientRequestProtocolOne(SmartProtocolBase, Requester,
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
600
                                    message.ResponseHandler):
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
601
    """The client-side protocol for smart version 1."""
602
603
    def __init__(self, request):
604
        """Construct a SmartClientRequestProtocolOne.
605
606
        :param request: A SmartClientMediumRequest to serialise onto and
607
            deserialise from.
608
        """
609
        self._request = request
610
        self._body_buffer = None
2664.4.1 by John Arbash Meinel
Add timing information for call/response groups for hpss
611
        self._request_start_time = None
3297.3.1 by Andrew Bennetts
Raise UnknownSmartMethod automatically from read_response_tuple.
612
        self._last_verb = None
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
613
        self._headers = None
614
615
    def set_headers(self, headers):
616
        self._headers = dict(headers)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
617
618
    def call(self, *args):
2593.3.1 by Andrew Bennetts
Add a -Dhpss debug flag.
619
        if 'hpss' in debug.debug_flags:
2664.4.3 by John Arbash Meinel
Update to include a bit better formatting
620
            mutter('hpss call:   %s', repr(args)[1:-1])
3104.4.2 by Andrew Bennetts
All tests passing.
621
            if getattr(self._request._medium, 'base', None) is not None:
622
                mutter('             (to %s)', self._request._medium.base)
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
623
            self._request_start_time = osutils.timer_func()
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
624
        self._write_args(args)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
625
        self._request.finished_writing()
3297.3.1 by Andrew Bennetts
Raise UnknownSmartMethod automatically from read_response_tuple.
626
        self._last_verb = args[0]
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
627
628
    def call_with_body_bytes(self, args, body):
629
        """Make a remote call of args with body bytes 'body'.
630
631
        After calling this, call read_response_tuple to find the result out.
632
        """
2593.3.1 by Andrew Bennetts
Add a -Dhpss debug flag.
633
        if 'hpss' in debug.debug_flags:
2664.4.3 by John Arbash Meinel
Update to include a bit better formatting
634
            mutter('hpss call w/body: %s (%r...)', repr(args)[1:-1], body[:20])
3104.4.2 by Andrew Bennetts
All tests passing.
635
            if getattr(self._request._medium, '_path', None) is not None:
636
                mutter('                  (to %s)', self._request._medium._path)
2664.4.4 by John Arbash Meinel
Switch around what bytes get logged.
637
            mutter('              %d bytes', len(body))
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
638
            self._request_start_time = osutils.timer_func()
3211.5.1 by Robert Collins
Change the smart server get_parents method to take a graph search to exclude already recieved parents from. This prevents history shortcuts causing huge numbers of duplicates.
639
            if 'hpssdetail' in debug.debug_flags:
640
                mutter('hpss body content: %s', body)
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
641
        self._write_args(args)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
642
        bytes = self._encode_bulk_data(body)
643
        self._request.accept_bytes(bytes)
644
        self._request.finished_writing()
3297.3.1 by Andrew Bennetts
Raise UnknownSmartMethod automatically from read_response_tuple.
645
        self._last_verb = args[0]
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
646
647
    def call_with_body_readv_array(self, args, body):
648
        """Make a remote call with a readv array.
649
650
        The body is encoded with one line per readv offset pair. The numbers in
651
        each pair are separated by a comma, and no trailing \n is emitted.
652
        """
2593.3.1 by Andrew Bennetts
Add a -Dhpss debug flag.
653
        if 'hpss' in debug.debug_flags:
2664.4.3 by John Arbash Meinel
Update to include a bit better formatting
654
            mutter('hpss call w/readv: %s', repr(args)[1:-1])
3104.4.2 by Andrew Bennetts
All tests passing.
655
            if getattr(self._request._medium, '_path', None) is not None:
656
                mutter('                  (to %s)', self._request._medium._path)
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
657
            self._request_start_time = osutils.timer_func()
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
658
        self._write_args(args)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
659
        readv_bytes = self._serialise_offsets(body)
660
        bytes = self._encode_bulk_data(readv_bytes)
661
        self._request.accept_bytes(bytes)
662
        self._request.finished_writing()
2664.4.2 by John Arbash Meinel
Add debug timings for operations that have to send data
663
        if 'hpss' in debug.debug_flags:
2664.4.4 by John Arbash Meinel
Switch around what bytes get logged.
664
            mutter('              %d bytes in readv request', len(readv_bytes))
3297.3.1 by Andrew Bennetts
Raise UnknownSmartMethod automatically from read_response_tuple.
665
        self._last_verb = args[0]
4032.1.2 by John Arbash Meinel
Track down a few more files that have trailing whitespace.
666
3842.3.5 by Andrew Bennetts
Remove some debugging cruft, make more tests pass.
667
    def call_with_body_stream(self, args, stream):
668
        # Protocols v1 and v2 don't support body streams.  So it's safe to
669
        # assume that a v1/v2 server doesn't support whatever method we're
670
        # trying to call with a body stream.
3842.3.7 by Andrew Bennetts
Implement a simple fallback (that buffers the whole record stream) for dealing with older servers.
671
        self._request.finished_writing()
672
        self._request.finished_reading()
3842.3.5 by Andrew Bennetts
Remove some debugging cruft, make more tests pass.
673
        raise errors.UnknownSmartMethod(args[0])
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
674
675
    def cancel_read_body(self):
676
        """After expecting a body, a response code may indicate one otherwise.
677
678
        This method lets the domain client inform the protocol that no body
679
        will be transmitted. This is a terminal method: after calling it the
680
        protocol is not able to be used further.
681
        """
682
        self._request.finished_reading()
683
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
684
    def _read_response_tuple(self):
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
685
        result = self._recv_tuple()
2593.3.1 by Andrew Bennetts
Add a -Dhpss debug flag.
686
        if 'hpss' in debug.debug_flags:
2664.4.1 by John Arbash Meinel
Add timing information for call/response groups for hpss
687
            if self._request_start_time is not None:
2664.4.3 by John Arbash Meinel
Update to include a bit better formatting
688
                mutter('   result:   %6.3fs  %s',
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
689
                       osutils.timer_func() - self._request_start_time,
2664.4.3 by John Arbash Meinel
Update to include a bit better formatting
690
                       repr(result)[1:-1])
2664.4.1 by John Arbash Meinel
Add timing information for call/response groups for hpss
691
                self._request_start_time = None
692
            else:
2664.4.3 by John Arbash Meinel
Update to include a bit better formatting
693
                mutter('   result:   %s', repr(result)[1:-1])
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
694
        return result
695
696
    def read_response_tuple(self, expect_body=False):
697
        """Read a response tuple from the wire.
698
699
        This should only be called once.
700
        """
701
        result = self._read_response_tuple()
3297.3.1 by Andrew Bennetts
Raise UnknownSmartMethod automatically from read_response_tuple.
702
        self._response_is_unknown_method(result)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
703
        self._raise_args_if_error(result)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
704
        if not expect_body:
705
            self._request.finished_reading()
706
        return result
707
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
708
    def _raise_args_if_error(self, result_tuple):
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
709
        # Later protocol versions have an explicit flag in the protocol to say
710
        # if an error response is "failed" or not.  In version 1 we don't have
711
        # that luxury.  So here is a complete list of errors that can be
712
        # returned in response to existing version 1 smart requests.  Responses
713
        # starting with these codes are always "failed" responses.
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
714
        v1_error_codes = [
715
            'norepository',
716
            'NoSuchFile',
717
            'FileExists',
718
            'DirectoryNotEmpty',
719
            'ShortReadvError',
720
            'UnicodeEncodeError',
721
            'UnicodeDecodeError',
722
            'ReadOnlyError',
723
            'nobranch',
724
            'NoSuchRevision',
725
            'nosuchrevision',
726
            'LockContention',
727
            'UnlockableTransport',
728
            'LockFailed',
729
            'TokenMismatch',
730
            'ReadError',
731
            'PermissionDenied',
732
            ]
733
        if result_tuple[0] in v1_error_codes:
734
            self._request.finished_reading()
735
            raise errors.ErrorFromSmartServer(result_tuple)
736
3297.3.1 by Andrew Bennetts
Raise UnknownSmartMethod automatically from read_response_tuple.
737
    def _response_is_unknown_method(self, result_tuple):
738
        """Raise UnexpectedSmartServerResponse if the response is an 'unknonwn
739
        method' response to the request.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
740
3297.3.1 by Andrew Bennetts
Raise UnknownSmartMethod automatically from read_response_tuple.
741
        :param response: The response from a smart client call_expecting_body
742
            call.
743
        :param verb: The verb used in that call.
744
        :raises: UnexpectedSmartServerResponse
745
        """
746
        if (result_tuple == ('error', "Generic bzr smart protocol error: "
747
                "bad request '%s'" % self._last_verb) or
748
              result_tuple == ('error', "Generic bzr smart protocol error: "
749
                "bad request u'%s'" % self._last_verb)):
750
            # The response will have no body, so we've finished reading.
751
            self._request.finished_reading()
752
            raise errors.UnknownSmartMethod(self._last_verb)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
753
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
754
    def read_body_bytes(self, count=-1):
755
        """Read bytes from the body, decoding into a byte stream.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
756
757
        We read all bytes at once to ensure we've checked the trailer for
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
758
        errors, and then feed the buffer back as read_body_bytes is called.
759
        """
760
        if self._body_buffer is not None:
761
            return self._body_buffer.read(count)
762
        _body_decoder = LengthPrefixedBodyDecoder()
763
764
        while not _body_decoder.finished_reading:
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
765
            bytes = self._request.read_bytes(_body_decoder.next_read_size())
3464.4.1 by Andrew Bennetts
Fix infinite busy-loop caused by connection loss during read of response body in HPSS v1 and v2.
766
            if bytes == '':
767
                # end of file encountered reading from server
768
                raise errors.ConnectionReset(
769
                    "Connection lost while reading response body.")
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
770
            _body_decoder.accept_bytes(bytes)
771
        self._request.finished_reading()
772
        self._body_buffer = StringIO(_body_decoder.read_pending_data())
773
        # XXX: TODO check the trailer result.
2664.4.3 by John Arbash Meinel
Update to include a bit better formatting
774
        if 'hpss' in debug.debug_flags:
2664.4.4 by John Arbash Meinel
Switch around what bytes get logged.
775
            mutter('              %d body bytes read',
2664.4.3 by John Arbash Meinel
Update to include a bit better formatting
776
                   len(self._body_buffer.getvalue()))
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
777
        return self._body_buffer.read(count)
778
779
    def _recv_tuple(self):
780
        """Receive a tuple from the medium request."""
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
781
        return _decode_tuple(self._request.read_line())
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
782
783
    def query_version(self):
784
        """Return protocol version number of the server."""
785
        self.call('hello')
786
        resp = self.read_response_tuple()
787
        if resp == ('ok', '1'):
788
            return 1
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
789
        elif resp == ('ok', '2'):
790
            return 2
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
791
        else:
792
            raise errors.SmartProtocolError("bad response %r" % (resp,))
793
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
794
    def _write_args(self, args):
795
        self._write_protocol_version()
796
        bytes = _encode_tuple(args)
797
        self._request.accept_bytes(bytes)
798
799
    def _write_protocol_version(self):
800
        """Write any prefixes this protocol requires.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
801
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
802
        Version one doesn't send protocol versions.
803
        """
804
805
806
class SmartClientRequestProtocolTwo(SmartClientRequestProtocolOne):
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
807
    """Version two of the client side of the smart protocol.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
808
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
809
    This prefixes the request with the value of REQUEST_VERSION_TWO.
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
810
    """
811
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
812
    response_marker = RESPONSE_VERSION_TWO
813
    request_marker = REQUEST_VERSION_TWO
814
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
815
    def read_response_tuple(self, expect_body=False):
816
        """Read a response tuple from the wire.
817
818
        This should only be called once.
819
        """
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
820
        version = self._request.read_line()
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
821
        if version != self.response_marker:
3245.4.47 by Andrew Bennetts
Don't automatically send 'hello' requests from RemoteBzrDirFormat.probe_transport unless we have to (i.e. the transport is HTTP).
822
            self._request.finished_reading()
3245.4.43 by Andrew Bennetts
Improve tests for automatic detection of protocol version.
823
            raise errors.UnexpectedProtocolVersionMarker(version)
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
824
        response_status = self._request.read_line()
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
825
        result = SmartClientRequestProtocolOne._read_response_tuple(self)
3245.4.55 by Andrew Bennetts
Test improvements suggested by John's review.
826
        self._response_is_unknown_method(result)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
827
        if response_status == 'success\n':
828
            self.response_status = True
829
            if not expect_body:
830
                self._request.finished_reading()
831
            return result
832
        elif response_status == 'failed\n':
833
            self.response_status = False
834
            self._request.finished_reading()
835
            raise errors.ErrorFromSmartServer(result)
836
        else:
2432.4.6 by Robert Collins
Include success/failure feedback in SmartProtocolTwo responses to allow robust handling in the future.
837
            raise errors.SmartProtocolError(
838
                'bad protocol status %r' % response_status)
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
839
840
    def _write_protocol_version(self):
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
841
        """Write any prefixes this protocol requires.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
842
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
843
        Version two sends the value of REQUEST_VERSION_TWO.
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
844
        """
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
845
        self._request.accept_bytes(self.request_marker)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
846
2748.4.2 by Andrew Bennetts
Add protocol (version two) support for streaming bodies (using chunking) in responses.
847
    def read_streamed_body(self):
848
        """Read bytes from the body, decoding into a byte stream.
849
        """
3170.5.1 by Andrew Bennetts
Fix the other half of bug #115781: don't read more than 64k at a time either.
850
        # Read no more than 64k at a time so that we don't risk error 10055 (no
851
        # buffer space available) on Windows.
2748.4.2 by Andrew Bennetts
Add protocol (version two) support for streaming bodies (using chunking) in responses.
852
        _body_decoder = ChunkedBodyDecoder()
853
        while not _body_decoder.finished_reading:
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
854
            bytes = self._request.read_bytes(_body_decoder.next_read_size())
3464.4.1 by Andrew Bennetts
Fix infinite busy-loop caused by connection loss during read of response body in HPSS v1 and v2.
855
            if bytes == '':
856
                # end of file encountered reading from server
857
                raise errors.ConnectionReset(
858
                    "Connection lost while reading streamed body.")
2748.4.2 by Andrew Bennetts
Add protocol (version two) support for streaming bodies (using chunking) in responses.
859
            _body_decoder.accept_bytes(bytes)
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
860
            for body_bytes in iter(_body_decoder.read_next_chunk, None):
3245.4.18 by Andrew Bennetts
Remove a bunch of cruft, especially the SmartClientRequestProtocolThree class.
861
                if 'hpss' in debug.debug_flags and type(body_bytes) is str:
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
862
                    mutter('              %d byte chunk read',
2535.4.3 by Andrew Bennetts
Remove some useless mutters.
863
                           len(body_bytes))
2748.4.2 by Andrew Bennetts
Add protocol (version two) support for streaming bodies (using chunking) in responses.
864
                yield body_bytes
865
        self._request.finished_reading()
866
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
867
3245.4.14 by Andrew Bennetts
Merge from bzr.dev (via loom thread).
868
def build_server_protocol_three(backing_transport, write_func,
4760.1.1 by Andrew Bennetts
Add optional jail_root argument to SmartServerRequest and friends, and use it in the WSGI glue. Allows opening branches in shared repos via bzr+http (assuming the repo should be accessible).
869
                                root_client_path, jail_root=None):
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
870
    request_handler = request.SmartServerRequestHandler(
3245.4.14 by Andrew Bennetts
Merge from bzr.dev (via loom thread).
871
        backing_transport, commands=request.request_handlers,
4760.1.1 by Andrew Bennetts
Add optional jail_root argument to SmartServerRequest and friends, and use it in the WSGI glue. Allows opening branches in shared repos via bzr+http (assuming the repo should be accessible).
872
        root_client_path=root_client_path, jail_root=jail_root)
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
873
    responder = ProtocolThreeResponder(write_func)
874
    message_handler = message.ConventionalRequestHandler(request_handler, responder)
3245.4.7 by Andrew Bennetts
Rename _ProtocolThreeBase to ProtocolThreeDecoder, remove SmartServerRequestProtocolThree.
875
    return ProtocolThreeDecoder(message_handler)
876
877
878
class ProtocolThreeDecoder(_StatefulDecoder):
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
879
880
    response_marker = RESPONSE_VERSION_THREE
881
    request_marker = REQUEST_VERSION_THREE
882
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
883
    def __init__(self, message_handler, expect_version_marker=False):
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
884
        _StatefulDecoder.__init__(self)
3245.4.59 by Andrew Bennetts
Various tweaks in response to Martin's review.
885
        self._has_dispatched = False
3195.3.5 by Andrew Bennetts
Start writing the client-side protocol logic for HPSS v3.
886
        # Initial state
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
887
        if expect_version_marker:
888
            self.state_accept = self._state_accept_expecting_protocol_version
889
            # We're expecting at least the protocol version marker + some
890
            # headers.
891
            self._number_needed_bytes = len(MESSAGE_VERSION_THREE) + 4
892
        else:
893
            self.state_accept = self._state_accept_expecting_headers
894
            self._number_needed_bytes = 4
3245.4.49 by Andrew Bennetts
Distinguish between errors in decoding a message into message parts from errors in handling decoded message parts, and use that to make sure that entire requests are read even when they result in exceptions.
895
        self.decoding_failed = False
3195.3.16 by Andrew Bennetts
Update tests for revised v3 spec.
896
        self.request_handler = self.message_handler = message_handler
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
897
3195.3.8 by Andrew Bennetts
Use _NeedMoreBytes to improve earlier protocol implementations a little, and make test_errors_are_logged pass.
898
    def accept_bytes(self, bytes):
3195.3.18 by Andrew Bennetts
call_with_body_bytes now works with v3 (e.g. test_copy_content_remote_to_local passes). Lots of debugging cruft, though.
899
        self._number_needed_bytes = None
3195.3.8 by Andrew Bennetts
Use _NeedMoreBytes to improve earlier protocol implementations a little, and make test_errors_are_logged pass.
900
        try:
901
            _StatefulDecoder.accept_bytes(self, bytes)
902
        except KeyboardInterrupt:
903
            raise
3245.4.49 by Andrew Bennetts
Distinguish between errors in decoding a message into message parts from errors in handling decoded message parts, and use that to make sure that entire requests are read even when they result in exceptions.
904
        except errors.SmartMessageHandlerError, exception:
905
            # We do *not* set self.decoding_failed here.  The message handler
906
            # has raised an error, but the decoder is still able to parse bytes
907
            # and determine when this message ends.
4475.2.1 by Andrew Bennetts
Don't log UnknownSmartMethod errors on the server.
908
            if not isinstance(exception.exc_value, errors.UnknownSmartMethod):
909
                log_exception_quietly()
3245.4.49 by Andrew Bennetts
Distinguish between errors in decoding a message into message parts from errors in handling decoded message parts, and use that to make sure that entire requests are read even when they result in exceptions.
910
            self.message_handler.protocol_error(exception.exc_value)
911
            # The state machine is ready to continue decoding, but the
912
            # exception has interrupted the loop that runs the state machine.
913
            # So we call accept_bytes again to restart it.
914
            self.accept_bytes('')
3195.3.8 by Andrew Bennetts
Use _NeedMoreBytes to improve earlier protocol implementations a little, and make test_errors_are_logged pass.
915
        except Exception, exception:
3245.4.50 by Andrew Bennetts
Clarify the code a little.
916
            # The decoder itself has raised an exception.  We cannot continue
917
            # decoding.
3245.4.49 by Andrew Bennetts
Distinguish between errors in decoding a message into message parts from errors in handling decoded message parts, and use that to make sure that entire requests are read even when they result in exceptions.
918
            self.decoding_failed = True
3245.4.47 by Andrew Bennetts
Don't automatically send 'hello' requests from RemoteBzrDirFormat.probe_transport unless we have to (i.e. the transport is HTTP).
919
            if isinstance(exception, errors.UnexpectedProtocolVersionMarker):
920
                # This happens during normal operation when the client tries a
921
                # protocol version the server doesn't understand, so no need to
922
                # log a traceback every time.
3245.4.51 by Andrew Bennetts
Add another comment.
923
                # Note that this can only happen when
924
                # expect_version_marker=True, which is only the case on the
925
                # client side.
3245.4.47 by Andrew Bennetts
Don't automatically send 'hello' requests from RemoteBzrDirFormat.probe_transport unless we have to (i.e. the transport is HTTP).
926
                pass
927
            else:
928
                log_exception_quietly()
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
929
            self.message_handler.protocol_error(exception)
3195.3.8 by Andrew Bennetts
Use _NeedMoreBytes to improve earlier protocol implementations a little, and make test_errors_are_logged pass.
930
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
931
    def _extract_length_prefixed_bytes(self):
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
932
        if self._in_buffer_len < 4:
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
933
            # A length prefix by itself is 4 bytes, and we don't even have that
934
            # many yet.
3195.3.18 by Andrew Bennetts
call_with_body_bytes now works with v3 (e.g. test_copy_content_remote_to_local passes). Lots of debugging cruft, though.
935
            raise _NeedMoreBytes(4)
3649.5.2 by John Arbash Meinel
When we are waiting on a big stream, allow
936
        (length,) = struct.unpack('!L', self._get_in_bytes(4))
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
937
        end_of_bytes = 4 + length
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
938
        if self._in_buffer_len < end_of_bytes:
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
939
            # We haven't yet read as many bytes as the length-prefix says there
940
            # are.
3195.3.18 by Andrew Bennetts
call_with_body_bytes now works with v3 (e.g. test_copy_content_remote_to_local passes). Lots of debugging cruft, though.
941
            raise _NeedMoreBytes(end_of_bytes)
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
942
        # Extract the bytes from the buffer.
3649.5.2 by John Arbash Meinel
When we are waiting on a big stream, allow
943
        in_buf = self._get_in_buffer()
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
944
        bytes = in_buf[4:end_of_bytes]
945
        self._set_in_buffer(in_buf[end_of_bytes:])
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
946
        return bytes
947
948
    def _extract_prefixed_bencoded_data(self):
949
        prefixed_bytes = self._extract_length_prefixed_bytes()
950
        try:
3842.3.21 by Andrew Bennetts
Merge bzr.dev.
951
            decoded = bdecode_as_tuple(prefixed_bytes)
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
952
        except ValueError:
953
            raise errors.SmartProtocolError(
954
                'Bytes %r not bencoded' % (prefixed_bytes,))
955
        return decoded
956
3195.3.7 by Andrew Bennetts
Make the '_extract_* helpers more robust by adding a _NeedMoreBytes exception to _StatefulDecoder.
957
    def _extract_single_byte(self):
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
958
        if self._in_buffer_len == 0:
3195.3.7 by Andrew Bennetts
Make the '_extract_* helpers more robust by adding a _NeedMoreBytes exception to _StatefulDecoder.
959
            # The buffer is empty
3245.4.28 by Andrew Bennetts
Remove another XXX, and include test ID in smart server thread names.
960
            raise _NeedMoreBytes(1)
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
961
        in_buf = self._get_in_buffer()
962
        one_byte = in_buf[0]
963
        self._set_in_buffer(in_buf[1:])
3195.3.7 by Andrew Bennetts
Make the '_extract_* helpers more robust by adding a _NeedMoreBytes exception to _StatefulDecoder.
964
        return one_byte
965
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
966
    def _state_accept_expecting_protocol_version(self):
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
967
        needed_bytes = len(MESSAGE_VERSION_THREE) - self._in_buffer_len
968
        in_buf = self._get_in_buffer()
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
969
        if needed_bytes > 0:
3245.4.46 by Andrew Bennetts
Apply John's review comments.
970
            # We don't have enough bytes to check if the protocol version
971
            # marker is right.  But we can check if it is already wrong by
972
            # checking that the start of MESSAGE_VERSION_THREE matches what
973
            # we've read so far.
974
            # [In fact, if the remote end isn't bzr we might never receive
975
            # len(MESSAGE_VERSION_THREE) bytes.  So if the bytes we have so far
976
            # are wrong then we should just raise immediately rather than
977
            # stall.]
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
978
            if not MESSAGE_VERSION_THREE.startswith(in_buf):
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
979
                # We have enough bytes to know the protocol version is wrong
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
980
                raise errors.UnexpectedProtocolVersionMarker(in_buf)
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
981
            raise _NeedMoreBytes(len(MESSAGE_VERSION_THREE))
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
982
        if not in_buf.startswith(MESSAGE_VERSION_THREE):
983
            raise errors.UnexpectedProtocolVersionMarker(in_buf)
984
        self._set_in_buffer(in_buf[len(MESSAGE_VERSION_THREE):])
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
985
        self.state_accept = self._state_accept_expecting_headers
986
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
987
    def _state_accept_expecting_headers(self):
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
988
        decoded = self._extract_prefixed_bencoded_data()
989
        if type(decoded) is not dict:
990
            raise errors.SmartProtocolError(
991
                'Header object %r is not a dict' % (decoded,))
3195.3.16 by Andrew Bennetts
Update tests for revised v3 spec.
992
        self.state_accept = self._state_accept_expecting_message_part
3245.4.49 by Andrew Bennetts
Distinguish between errors in decoding a message into message parts from errors in handling decoded message parts, and use that to make sure that entire requests are read even when they result in exceptions.
993
        try:
994
            self.message_handler.headers_received(decoded)
995
        except:
996
            raise errors.SmartMessageHandlerError(sys.exc_info())
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
997
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
998
    def _state_accept_expecting_message_part(self):
3195.3.16 by Andrew Bennetts
Update tests for revised v3 spec.
999
        message_part_kind = self._extract_single_byte()
1000
        if message_part_kind == 'o':
1001
            self.state_accept = self._state_accept_expecting_one_byte
1002
        elif message_part_kind == 's':
1003
            self.state_accept = self._state_accept_expecting_structure
1004
        elif message_part_kind == 'b':
1005
            self.state_accept = self._state_accept_expecting_bytes
1006
        elif message_part_kind == 'e':
1007
            self.done()
1008
        else:
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
1009
            raise errors.SmartProtocolError(
3195.3.16 by Andrew Bennetts
Update tests for revised v3 spec.
1010
                'Bad message kind byte: %r' % (message_part_kind,))
1011
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
1012
    def _state_accept_expecting_one_byte(self):
3195.3.16 by Andrew Bennetts
Update tests for revised v3 spec.
1013
        byte = self._extract_single_byte()
1014
        self.state_accept = self._state_accept_expecting_message_part
3245.4.49 by Andrew Bennetts
Distinguish between errors in decoding a message into message parts from errors in handling decoded message parts, and use that to make sure that entire requests are read even when they result in exceptions.
1015
        try:
1016
            self.message_handler.byte_part_received(byte)
1017
        except:
1018
            raise errors.SmartMessageHandlerError(sys.exc_info())
3195.3.16 by Andrew Bennetts
Update tests for revised v3 spec.
1019
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
1020
    def _state_accept_expecting_bytes(self):
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1021
        # XXX: this should not buffer whole message part, but instead deliver
1022
        # the bytes as they arrive.
3195.3.18 by Andrew Bennetts
call_with_body_bytes now works with v3 (e.g. test_copy_content_remote_to_local passes). Lots of debugging cruft, though.
1023
        prefixed_bytes = self._extract_length_prefixed_bytes()
3195.3.16 by Andrew Bennetts
Update tests for revised v3 spec.
1024
        self.state_accept = self._state_accept_expecting_message_part
3245.4.49 by Andrew Bennetts
Distinguish between errors in decoding a message into message parts from errors in handling decoded message parts, and use that to make sure that entire requests are read even when they result in exceptions.
1025
        try:
1026
            self.message_handler.bytes_part_received(prefixed_bytes)
1027
        except:
1028
            raise errors.SmartMessageHandlerError(sys.exc_info())
3195.3.16 by Andrew Bennetts
Update tests for revised v3 spec.
1029
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
1030
    def _state_accept_expecting_structure(self):
3195.3.16 by Andrew Bennetts
Update tests for revised v3 spec.
1031
        structure = self._extract_prefixed_bencoded_data()
1032
        self.state_accept = self._state_accept_expecting_message_part
3245.4.49 by Andrew Bennetts
Distinguish between errors in decoding a message into message parts from errors in handling decoded message parts, and use that to make sure that entire requests are read even when they result in exceptions.
1033
        try:
1034
            self.message_handler.structure_part_received(structure)
1035
        except:
1036
            raise errors.SmartMessageHandlerError(sys.exc_info())
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
1037
1038
    def done(self):
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
1039
        self.unused_data = self._get_in_buffer()
1040
        self._set_in_buffer(None)
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
1041
        self.state_accept = self._state_accept_reading_unused
3245.4.49 by Andrew Bennetts
Distinguish between errors in decoding a message into message parts from errors in handling decoded message parts, and use that to make sure that entire requests are read even when they result in exceptions.
1042
        try:
1043
            self.message_handler.end_received()
1044
        except:
1045
            raise errors.SmartMessageHandlerError(sys.exc_info())
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
1046
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
1047
    def _state_accept_reading_unused(self):
4515.1.1 by Andrew Bennetts
Fix bug in HPSS v3 decoder when receiving multiple lots of excess bytes.
1048
        self.unused_data += self._get_in_buffer()
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
1049
        self._set_in_buffer(None)
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
1050
1051
    def next_read_size(self):
1052
        if self.state_accept == self._state_accept_reading_unused:
1053
            return 0
3245.4.49 by Andrew Bennetts
Distinguish between errors in decoding a message into message parts from errors in handling decoded message parts, and use that to make sure that entire requests are read even when they result in exceptions.
1054
        elif self.decoding_failed:
3245.4.29 by Andrew Bennetts
Add/tidy some comments, remove dud test_errors_are_logged test, add explicit UnknownSmartMethod to v3.
1055
            # An exception occured while processing this message, probably from
1056
            # self.message_handler.  We're not sure that this state machine is
1057
            # in a consistent state, so just signal that we're done (i.e. give
1058
            # up).
3245.4.28 by Andrew Bennetts
Remove another XXX, and include test ID in smart server thread names.
1059
            return 0
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
1060
        else:
3195.3.18 by Andrew Bennetts
call_with_body_bytes now works with v3 (e.g. test_copy_content_remote_to_local passes). Lots of debugging cruft, though.
1061
            if self._number_needed_bytes is not None:
3649.5.1 by John Arbash Meinel
Change _StatefulDecoder._in_bytes into a _in_bytes_list
1062
                return self._number_needed_bytes - self._in_buffer_len
3195.3.18 by Andrew Bennetts
call_with_body_bytes now works with v3 (e.g. test_copy_content_remote_to_local passes). Lots of debugging cruft, though.
1063
            else:
3245.4.28 by Andrew Bennetts
Remove another XXX, and include test ID in smart server thread names.
1064
                raise AssertionError("don't know how many bytes are expected!")
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
1065
1066
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1067
class _ProtocolThreeEncoder(object):
1068
3245.4.18 by Andrew Bennetts
Remove a bunch of cruft, especially the SmartClientRequestProtocolThree class.
1069
    response_marker = request_marker = MESSAGE_VERSION_THREE
4889.4.2 by John Arbash Meinel
Change the amount buffered to be a 'constant' that we can get at.
1070
    BUFFER_SIZE = 1024*1024 # 1 MiB buffer before flushing
3245.4.18 by Andrew Bennetts
Remove a bunch of cruft, especially the SmartClientRequestProtocolThree class.
1071
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1072
    def __init__(self, write_func):
4078.1.1 by Andrew Bennetts
Slightly better buffering logic when generating protocol v3 messages, especially during streamed bodies.
1073
        self._buf = []
4889.4.1 by John Arbash Meinel
Change the buffering algorithm for ProtocolThree.
1074
        self._buf_len = 0
3441.3.1 by Andrew Bennetts
Buffer encoding of v3 messages to minimise write/send calls. Doubles the speed of pushing over TCP with 500ms latency loopback.
1075
        self._real_write_func = write_func
1076
1077
    def _write_func(self, bytes):
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
1078
        # TODO: It is probably more appropriate to use sum(map(len, _buf))
1079
        #       for total number of bytes to write, rather than buffer based on
1080
        #       the number of write() calls
1081
        # TODO: Another possibility would be to turn this into an async model.
1082
        #       Where we let another thread know that we have some bytes if
1083
        #       they want it, but we don't actually block for it
1084
        #       Note that osutils.send_all always sends 64kB chunks anyway, so
1085
        #       we might just push out smaller bits at a time?
4078.1.1 by Andrew Bennetts
Slightly better buffering logic when generating protocol v3 messages, especially during streamed bodies.
1086
        self._buf.append(bytes)
4889.4.1 by John Arbash Meinel
Change the buffering algorithm for ProtocolThree.
1087
        self._buf_len += len(bytes)
4889.4.2 by John Arbash Meinel
Change the amount buffered to be a 'constant' that we can get at.
1088
        if self._buf_len > self.BUFFER_SIZE:
4078.1.1 by Andrew Bennetts
Slightly better buffering logic when generating protocol v3 messages, especially during streamed bodies.
1089
            self.flush()
3441.3.1 by Andrew Bennetts
Buffer encoding of v3 messages to minimise write/send calls. Doubles the speed of pushing over TCP with 500ms latency loopback.
1090
1091
    def flush(self):
1092
        if self._buf:
4078.1.1 by Andrew Bennetts
Slightly better buffering logic when generating protocol v3 messages, especially during streamed bodies.
1093
            self._real_write_func(''.join(self._buf))
1094
            del self._buf[:]
4889.4.1 by John Arbash Meinel
Change the buffering algorithm for ProtocolThree.
1095
            self._buf_len = 0
3441.3.1 by Andrew Bennetts
Buffer encoding of v3 messages to minimise write/send calls. Doubles the speed of pushing over TCP with 500ms latency loopback.
1096
3245.4.18 by Andrew Bennetts
Remove a bunch of cruft, especially the SmartClientRequestProtocolThree class.
1097
    def _serialise_offsets(self, offsets):
1098
        """Serialise a readv offset list."""
1099
        txt = []
1100
        for start, length in offsets:
1101
            txt.append('%d,%d' % (start, length))
1102
        return '\n'.join(txt)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1103
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1104
    def _write_protocol_version(self):
1105
        self._write_func(MESSAGE_VERSION_THREE)
1106
1107
    def _write_prefixed_bencode(self, structure):
1108
        bytes = bencode(structure)
1109
        self._write_func(struct.pack('!L', len(bytes)))
1110
        self._write_func(bytes)
1111
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
1112
    def _write_headers(self, headers):
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1113
        self._write_prefixed_bencode(headers)
1114
1115
    def _write_structure(self, args):
1116
        self._write_func('s')
3195.3.23 by Andrew Bennetts
Improve the error handling, fixing more tests.
1117
        utf8_args = []
1118
        for arg in args:
1119
            if type(arg) is unicode:
1120
                utf8_args.append(arg.encode('utf8'))
1121
            else:
1122
                utf8_args.append(arg)
1123
        self._write_prefixed_bencode(utf8_args)
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1124
1125
    def _write_end(self):
1126
        self._write_func('e')
3441.3.2 by Andrew Bennetts
Simplify buffering logic in _ProtocolThreeEncoder.
1127
        self.flush()
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1128
1129
    def _write_prefixed_body(self, bytes):
1130
        self._write_func('b')
1131
        self._write_func(struct.pack('!L', len(bytes)))
1132
        self._write_func(bytes)
1133
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.
1134
    def _write_chunked_body_start(self):
1135
        self._write_func('oC')
1136
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1137
    def _write_error_status(self):
1138
        self._write_func('oE')
1139
1140
    def _write_success_status(self):
1141
        self._write_func('oS')
1142
1143
1144
class ProtocolThreeResponder(_ProtocolThreeEncoder):
1145
1146
    def __init__(self, write_func):
1147
        _ProtocolThreeEncoder.__init__(self, write_func)
1148
        self.response_sent = False
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
1149
        self._headers = {'Software version': bzrlib.__version__}
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
1150
        if 'hpss' in debug.debug_flags:
4913.1.1 by John Arbash Meinel
Switch to using thread.get_ident() which is available on all python versions.
1151
            self._thread_id = thread.get_ident()
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
1152
            self._response_start_time = None
1153
4889.2.4 by John Arbash Meinel
Clean up some bits, we don't really need the time reported except for end time.
1154
    def _trace(self, action, message, extra_bytes=None, include_time=False):
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
1155
        if self._response_start_time is None:
1156
            self._response_start_time = osutils.timer_func()
4889.2.4 by John Arbash Meinel
Clean up some bits, we don't really need the time reported except for end time.
1157
        if include_time:
1158
            t = '%5.3fs ' % (time.clock() - self._response_start_time)
1159
        else:
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
1160
            t = ''
1161
        if extra_bytes is None:
1162
            extra = ''
1163
        else:
1164
            extra = ' ' + repr(extra_bytes[:40])
1165
            if len(extra) > 33:
1166
                extra = extra[:29] + extra[-1] + '...'
4889.2.3 by John Arbash Meinel
Get rid of -Dhpssthread, just always include it.
1167
        mutter('%12s: [%s] %s%s%s'
1168
               % (action, self._thread_id, t, message, extra))
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1169
1170
    def send_error(self, exception):
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
1171
        if self.response_sent:
1172
            raise AssertionError(
1173
                "send_error(%s) called, but response already sent."
1174
                % (exception,))
3245.4.29 by Andrew Bennetts
Add/tidy some comments, remove dud test_errors_are_logged test, add explicit UnknownSmartMethod to v3.
1175
        if isinstance(exception, errors.UnknownSmartMethod):
3245.4.37 by Andrew Bennetts
Add test for sending ProtocolThreeResponder.send_error(UnknownSmartMethod(...)).
1176
            failure = request.FailedSmartServerResponse(
1177
                ('UnknownMethod', exception.verb))
3245.4.29 by Andrew Bennetts
Add/tidy some comments, remove dud test_errors_are_logged test, add explicit UnknownSmartMethod to v3.
1178
            self.send_response(failure)
1179
            return
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
1180
        if 'hpss' in debug.debug_flags:
1181
            self._trace('error', str(exception))
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1182
        self.response_sent = True
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
1183
        self._write_protocol_version()
1184
        self._write_headers(self._headers)
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1185
        self._write_error_status()
1186
        self._write_structure(('error', str(exception)))
1187
        self._write_end()
1188
1189
    def send_response(self, response):
3245.4.54 by Andrew Bennetts
Improve _StatefulDecoder after John's review.
1190
        if self.response_sent:
1191
            raise AssertionError(
1192
                "send_response(%r) called, but response already sent."
1193
                % (response,))
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1194
        self.response_sent = True
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
1195
        self._write_protocol_version()
1196
        self._write_headers(self._headers)
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1197
        if response.is_successful():
1198
            self._write_success_status()
1199
        else:
1200
            self._write_error_status()
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
1201
        if 'hpss' in debug.debug_flags:
4889.2.4 by John Arbash Meinel
Clean up some bits, we don't really need the time reported except for end time.
1202
            self._trace('response', repr(response.args))
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1203
        self._write_structure(response.args)
1204
        if response.body is not None:
1205
            self._write_prefixed_body(response.body)
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
1206
            if 'hpss' in debug.debug_flags:
1207
                self._trace('body', '%d bytes' % (len(response.body),),
4889.2.4 by John Arbash Meinel
Clean up some bits, we don't really need the time reported except for end time.
1208
                            response.body, include_time=True)
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1209
        elif response.body_stream is not None:
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
1210
            count = num_bytes = 0
1211
            first_chunk = None
4064.1.3 by Andrew Bennetts
Fix bug in _iter_with_errors; it should not report StopIteration as an exception.
1212
            for exc_info, chunk in _iter_with_errors(response.body_stream):
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
1213
                count += 1
4064.1.3 by Andrew Bennetts
Fix bug in _iter_with_errors; it should not report StopIteration as an exception.
1214
                if exc_info is not None:
4064.1.1 by Andrew Bennetts
Add TestResponseEncodingProtocolThree.test_send_broken_body_stream, and make it pass.
1215
                    self._write_error_status()
4064.1.3 by Andrew Bennetts
Fix bug in _iter_with_errors; it should not report StopIteration as an exception.
1216
                    error_struct = request._translate_error(exc_info[1])
4064.1.1 by Andrew Bennetts
Add TestResponseEncodingProtocolThree.test_send_broken_body_stream, and make it pass.
1217
                    self._write_structure(error_struct)
1218
                    break
1219
                else:
4070.9.2 by Andrew Bennetts
Rough prototype of allowing a SearchResult to be passed to fetch, and using that to improve network conversations.
1220
                    if isinstance(chunk, request.FailedSmartServerResponse):
1221
                        self._write_error_status()
1222
                        self._write_structure(chunk.args)
1223
                        break
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
1224
                    num_bytes += len(chunk)
1225
                    if first_chunk is None:
1226
                        first_chunk = chunk
4064.1.1 by Andrew Bennetts
Add TestResponseEncodingProtocolThree.test_send_broken_body_stream, and make it pass.
1227
                    self._write_prefixed_body(chunk)
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
1228
                    if 'hpssdetail' in debug.debug_flags:
1229
                        # Not worth timing separately, as _write_func is
1230
                        # actually buffered
1231
                        self._trace('body chunk',
1232
                                    '%d bytes' % (len(chunk),),
1233
                                    chunk, suppress_time=True)
1234
            if 'hpss' in debug.debug_flags:
4889.2.4 by John Arbash Meinel
Clean up some bits, we don't really need the time reported except for end time.
1235
                self._trace('body stream',
1236
                            '%d bytes %d chunks' % (num_bytes, count),
1237
                            first_chunk)
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1238
        self._write_end()
4889.2.4 by John Arbash Meinel
Clean up some bits, we don't really need the time reported except for end time.
1239
        if 'hpss' in debug.debug_flags:
1240
            self._trace('response end', '', include_time=True)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1241
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1242
4064.1.2 by Andrew Bennetts
Refactor server-side error translation, improve tests.
1243
def _iter_with_errors(iterable):
1244
    """Handle errors from iterable.next().
1245
1246
    Use like::
1247
1248
        for exc_info, value in _iter_with_errors(iterable):
1249
            ...
1250
1251
    This is a safer alternative to::
1252
1253
        try:
1254
            for value in iterable:
1255
               ...
1256
        except:
1257
            ...
1258
1259
    Because the latter will catch errors from the for-loop body, not just
1260
    iterable.next()
1261
1262
    If an error occurs, exc_info will be a exc_info tuple, and the generator
1263
    will terminate.  Otherwise exc_info will be None, and value will be the
1264
    value from iterable.next().  Note that KeyboardInterrupt and SystemExit
1265
    will not be itercepted.
1266
    """
4064.1.1 by Andrew Bennetts
Add TestResponseEncodingProtocolThree.test_send_broken_body_stream, and make it pass.
1267
    iterator = iter(iterable)
1268
    while True:
1269
        try:
1270
            yield None, iterator.next()
4064.1.3 by Andrew Bennetts
Fix bug in _iter_with_errors; it should not report StopIteration as an exception.
1271
        except StopIteration:
1272
            return
4064.1.2 by Andrew Bennetts
Refactor server-side error translation, improve tests.
1273
        except (KeyboardInterrupt, SystemExit):
1274
            raise
1275
        except Exception:
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
1276
            mutter('_iter_with_errors caught error')
1277
            log_exception_quietly()
4064.1.1 by Andrew Bennetts
Add TestResponseEncodingProtocolThree.test_send_broken_body_stream, and make it pass.
1278
            yield sys.exc_info(), None
1279
            return
1280
1281
3245.4.26 by Andrew Bennetts
Rename 'setProtoAndMedium' to more accurate 'setProtoAndMediumRequest', add ABCs for Requesters and ResponseHandlers.
1282
class ProtocolThreeRequester(_ProtocolThreeEncoder, Requester):
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1283
1284
    def __init__(self, medium_request):
1285
        _ProtocolThreeEncoder.__init__(self, medium_request.accept_bytes)
1286
        self._medium_request = medium_request
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
1287
        self._headers = {}
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1288
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
1289
    def set_headers(self, headers):
3245.4.46 by Andrew Bennetts
Apply John's review comments.
1290
        self._headers = headers.copy()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1291
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
1292
    def call(self, *args):
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1293
        if 'hpss' in debug.debug_flags:
1294
            mutter('hpss call:   %s', repr(args)[1:-1])
1295
            base = getattr(self._medium_request._medium, 'base', None)
1296
            if base is not None:
1297
                mutter('             (to %s)', base)
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
1298
            self._request_start_time = osutils.timer_func()
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1299
        self._write_protocol_version()
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
1300
        self._write_headers(self._headers)
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1301
        self._write_structure(args)
1302
        self._write_end()
1303
        self._medium_request.finished_writing()
1304
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
1305
    def call_with_body_bytes(self, args, body):
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1306
        """Make a remote call of args with body bytes 'body'.
1307
1308
        After calling this, call read_response_tuple to find the result out.
1309
        """
1310
        if 'hpss' in debug.debug_flags:
3842.3.2 by Andrew Bennetts
Revert the RemoteVersionedFiles.get_parent_map implementation, leaving just the skeleton of RemoteVersionedFiles.
1311
            mutter('hpss call w/body: %s (%r...)', repr(args)[1:-1], body[:20])
3245.4.3 by Andrew Bennetts
Fix crash in -Dhpss.
1312
            path = getattr(self._medium_request._medium, '_path', None)
1313
            if path is not None:
1314
                mutter('                  (to %s)', path)
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1315
            mutter('              %d bytes', len(body))
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
1316
            self._request_start_time = osutils.timer_func()
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1317
        self._write_protocol_version()
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
1318
        self._write_headers(self._headers)
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1319
        self._write_structure(args)
1320
        self._write_prefixed_body(body)
1321
        self._write_end()
3195.3.18 by Andrew Bennetts
call_with_body_bytes now works with v3 (e.g. test_copy_content_remote_to_local passes). Lots of debugging cruft, though.
1322
        self._medium_request.finished_writing()
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1323
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
1324
    def call_with_body_readv_array(self, args, body):
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1325
        """Make a remote call with a readv array.
1326
1327
        The body is encoded with one line per readv offset pair. The numbers in
1328
        each pair are separated by a comma, and no trailing \n is emitted.
1329
        """
1330
        if 'hpss' in debug.debug_flags:
1331
            mutter('hpss call w/readv: %s', repr(args)[1:-1])
3245.4.3 by Andrew Bennetts
Fix crash in -Dhpss.
1332
            path = getattr(self._medium_request._medium, '_path', None)
1333
            if path is not None:
1334
                mutter('                  (to %s)', path)
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
1335
            self._request_start_time = osutils.timer_func()
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1336
        self._write_protocol_version()
3245.4.42 by Andrew Bennetts
Make _SmartClient automatically detect and use the highest protocol version compatible with the server.
1337
        self._write_headers(self._headers)
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1338
        self._write_structure(args)
1339
        readv_bytes = self._serialise_offsets(body)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1340
        if 'hpss' in debug.debug_flags:
1341
            mutter('              %d bytes in readv request', len(readv_bytes))
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1342
        self._write_prefixed_body(readv_bytes)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1343
        self._write_end()
1344
        self._medium_request.finished_writing()
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
1345
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.
1346
    def call_with_body_stream(self, args, stream):
1347
        if 'hpss' in debug.debug_flags:
1348
            mutter('hpss call w/body stream: %r', args)
1349
            path = getattr(self._medium_request._medium, '_path', None)
1350
            if path is not None:
1351
                mutter('                  (to %s)', path)
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
1352
            self._request_start_time = osutils.timer_func()
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.
1353
        self._write_protocol_version()
1354
        self._write_headers(self._headers)
1355
        self._write_structure(args)
3923.5.5 by Andrew Bennetts
Cleanly abort the request if an error occurs while iterating a body stream.
1356
        # TODO: notice if the server has sent an early error reply before we
1357
        #       have finished sending the stream.  We would notice at the end
1358
        #       anyway, but if the medium can deliver it early then it's good
1359
        #       to short-circuit the whole request...
4064.1.3 by Andrew Bennetts
Fix bug in _iter_with_errors; it should not report StopIteration as an exception.
1360
        for exc_info, part in _iter_with_errors(stream):
1361
            if exc_info is not None:
1362
                # Iterating the stream failed.  Cleanly abort the request.
1363
                self._write_error_status()
1364
                # Currently the client unconditionally sends ('error',) as the
1365
                # error args.
1366
                self._write_structure(('error',))
1367
                self._write_end()
1368
                self._medium_request.finished_writing()
1369
                raise exc_info[0], exc_info[1], exc_info[2]
1370
            else:
3923.5.5 by Andrew Bennetts
Cleanly abort the request if an error occurs while iterating a body stream.
1371
                self._write_prefixed_body(part)
1372
                self.flush()
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.
1373
        self._write_end()
1374
        self._medium_request.finished_writing()
1375