/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2018.5.157 by Andrew Bennetts
Remove unnecessary trivial divergences from bzr.dev.
1
# Copyright (C) 2006, 2007 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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
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
2664.4.1 by John Arbash Meinel
Add timing information for call/response groups for hpss
23
import time
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
24
2593.3.1 by Andrew Bennetts
Add a -Dhpss debug flag.
25
from bzrlib import debug
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
26
from bzrlib import errors
2018.5.23 by Andrew Bennetts
Use a Registry for smart server command handlers.
27
from bzrlib.smart import 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.
28
from bzrlib.trace import log_exception_quietly, mutter
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
29
30
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
31
# Protocol version strings.  These are sent as prefixes of bzr requests and
32
# responses to identify the protocol version being used. (There are no version
33
# one strings because that version doesn't send any).
34
REQUEST_VERSION_TWO = 'bzr request 2\n'
35
RESPONSE_VERSION_TWO = 'bzr response 2\n'
36
37
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
38
def _recv_tuple(from_file):
39
    req_line = from_file.readline()
40
    return _decode_tuple(req_line)
41
42
43
def _decode_tuple(req_line):
3376.2.11 by Martin Pool
Compare to None using is/is not not ==
44
    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
45
        return None
46
    if req_line[-1] != '\n':
47
        raise errors.SmartProtocolError("request %r not terminated" % req_line)
48
    return tuple(req_line[:-1].split('\x01'))
49
50
51
def _encode_tuple(args):
52
    """Encode the tuple args to a bytestream."""
53
    return '\x01'.join(args) + '\n'
54
55
56
class SmartProtocolBase(object):
57
    """Methods common to client and server"""
58
59
    # TODO: this only actually accomodates a single block; possibly should
60
    # support multiple chunks?
61
    def _encode_bulk_data(self, body):
62
        """Encode body as a bulk data chunk."""
63
        return ''.join(('%d\n' % len(body), body, 'done\n'))
64
65
    def _serialise_offsets(self, offsets):
66
        """Serialise a readv offset list."""
67
        txt = []
68
        for start, length in offsets:
69
            txt.append('%d,%d' % (start, length))
70
        return '\n'.join(txt)
71
        
72
73
class SmartServerRequestProtocolOne(SmartProtocolBase):
74
    """Server-side encoding and decoding logic for smart version 1."""
75
    
2692.1.1 by Andrew Bennetts
Add translate_client_path method to SmartServerRequest.
76
    def __init__(self, backing_transport, write_func, root_client_path='/'):
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
77
        self._backing_transport = backing_transport
2692.1.1 by Andrew Bennetts
Add translate_client_path method to SmartServerRequest.
78
        self._root_client_path = root_client_path
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
79
        self.excess_buffer = ''
80
        self._finished = False
81
        self.in_buffer = ''
82
        self.has_dispatched = False
83
        self.request = None
84
        self._body_decoder = None
2664.4.6 by John Arbash Meinel
Restore a line that shouldn't have been removed
85
        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
86
87
    def accept_bytes(self, bytes):
88
        """Take bytes, and advance the internal state machine appropriately.
89
        
90
        :param bytes: must be a byte string
91
        """
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
92
        if not isinstance(bytes, str):
93
            raise ValueError(bytes)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
94
        self.in_buffer += bytes
95
        if not self.has_dispatched:
96
            if '\n' not in self.in_buffer:
97
                # no command line yet
98
                return
99
            self.has_dispatched = True
100
            try:
101
                first_line, self.in_buffer = self.in_buffer.split('\n', 1)
102
                first_line += '\n'
103
                req_args = _decode_tuple(first_line)
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
104
                self.request = request.SmartServerRequestHandler(
2692.1.1 by Andrew Bennetts
Add translate_client_path method to SmartServerRequest.
105
                    self._backing_transport, commands=request.request_handlers,
106
                    root_client_path=self._root_client_path)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
107
                self.request.dispatch_command(req_args[0], req_args[1:])
108
                if self.request.finished_reading:
109
                    # trivial request
110
                    self.excess_buffer = self.in_buffer
111
                    self.in_buffer = ''
2432.4.3 by Robert Collins
Refactor the HPSS Response code to take SmartServerResponse rather than args and body.
112
                    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
113
            except KeyboardInterrupt:
114
                raise
115
            except Exception, exception:
116
                # 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.
117
                log_exception_quietly()
2432.4.3 by Robert Collins
Refactor the HPSS Response code to take SmartServerResponse rather than args and body.
118
                self._send_response(request.FailedSmartServerResponse(
119
                    ('error', str(exception))))
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
120
                return
121
122
        if self.has_dispatched:
123
            if self._finished:
124
                # nothing to do.XXX: this routine should be a single state 
125
                # machine too.
126
                self.excess_buffer += self.in_buffer
127
                self.in_buffer = ''
128
                return
129
            if self._body_decoder is None:
130
                self._body_decoder = LengthPrefixedBodyDecoder()
131
            self._body_decoder.accept_bytes(self.in_buffer)
132
            self.in_buffer = self._body_decoder.unused_data
133
            body_data = self._body_decoder.read_pending_data()
134
            self.request.accept_body(body_data)
135
            if self._body_decoder.finished_reading:
136
                self.request.end_of_body()
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
137
                if not self.request.finished_reading:
138
                    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
139
            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.
140
                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
141
                self.excess_buffer = self.in_buffer
142
                self.in_buffer = ''
143
            else:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
144
                if self.request.finished_reading:
145
                    raise AssertionError(
146
                        "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
147
2432.4.3 by Robert Collins
Refactor the HPSS Response code to take SmartServerResponse rather than args and body.
148
    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
149
        """Send a smart server response down the output stream."""
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
150
        if self._finished:
151
            raise AssertionError('response already sent')
2432.4.3 by Robert Collins
Refactor the HPSS Response code to take SmartServerResponse rather than args and body.
152
        args = response.args
153
        body = response.body
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
154
        self._finished = True
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
155
        self._write_protocol_version()
2432.4.6 by Robert Collins
Include success/failure feedback in SmartProtocolTwo responses to allow robust handling in the future.
156
        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
157
        self._write_func(_encode_tuple(args))
158
        if body is not None:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
159
            if not isinstance(body, str):
160
                raise ValueError(body)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
161
            bytes = self._encode_bulk_data(body)
162
            self._write_func(bytes)
163
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
164
    def _write_protocol_version(self):
165
        """Write any prefixes this protocol requires.
166
        
167
        Version one doesn't send protocol versions.
168
        """
169
2432.4.6 by Robert Collins
Include success/failure feedback in SmartProtocolTwo responses to allow robust handling in the future.
170
    def _write_success_or_failure_prefix(self, response):
171
        """Write the protocol specific success/failure prefix.
172
173
        For SmartServerRequestProtocolOne this is omitted but we
174
        call is_successful to ensure that the response is valid.
175
        """
176
        response.is_successful()
177
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
178
    def next_read_size(self):
179
        if self._finished:
180
            return 0
181
        if self._body_decoder is None:
182
            return 1
183
        else:
184
            return self._body_decoder.next_read_size()
185
186
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
187
class SmartServerRequestProtocolTwo(SmartServerRequestProtocolOne):
188
    r"""Version two of the server side of the smart protocol.
189
   
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
190
    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.
191
    """
192
2432.4.6 by Robert Collins
Include success/failure feedback in SmartProtocolTwo responses to allow robust handling in the future.
193
    def _write_success_or_failure_prefix(self, response):
194
        """Write the protocol specific success/failure prefix."""
195
        if response.is_successful():
196
            self._write_func('success\n')
197
        else:
198
            self._write_func('failed\n')
199
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
200
    def _write_protocol_version(self):
201
        r"""Write any prefixes this protocol requires.
202
        
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
203
        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.
204
        """
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
205
        self._write_func(RESPONSE_VERSION_TWO)
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
206
2748.4.2 by Andrew Bennetts
Add protocol (version two) support for streaming bodies (using chunking) in responses.
207
    def _send_response(self, response):
208
        """Send a smart server response down the output stream."""
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
209
        if (self._finished):
210
            raise AssertionError('response already sent')
2748.4.2 by Andrew Bennetts
Add protocol (version two) support for streaming bodies (using chunking) in responses.
211
        self._finished = True
212
        self._write_protocol_version()
213
        self._write_success_or_failure_prefix(response)
214
        self._write_func(_encode_tuple(response.args))
215
        if response.body is not None:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
216
            if not isinstance(response.body, str):
217
                raise AssertionError('body must be a str')
218
            if not (response.body_stream is None):
219
                raise AssertionError(
220
                    '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.
221
            bytes = self._encode_bulk_data(response.body)
222
            self._write_func(bytes)
223
        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.
224
            _send_stream(response.body_stream, self._write_func)
225
226
227
def _send_stream(stream, write_func):
2748.4.16 by Andrew Bennetts
Tweaks suggested by review.
228
    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.
229
    _send_chunks(stream, write_func)
230
    write_func('END\n')
2748.4.4 by Andrew Bennetts
Extract a _send_chunks function to make testing easier.
231
232
233
def _send_chunks(stream, write_func):
234
    for chunk in stream:
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
235
        if isinstance(chunk, str):
236
            bytes = "%x\n%s" % (len(chunk), chunk)
237
            write_func(bytes)
238
        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.
239
            write_func('ERR\n')
240
            _send_chunks(chunk.args, write_func)
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
241
            return
242
        else:
2535.4.19 by Andrew Bennetts
Fix some trivial NameErrors in error handling.
243
            raise errors.BzrError(
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
244
                'Chunks must be str or FailedSmartServerResponse, got %r'
2535.4.19 by Andrew Bennetts
Fix some trivial NameErrors in error handling.
245
                % chunk)
2748.4.2 by Andrew Bennetts
Add protocol (version two) support for streaming bodies (using chunking) in responses.
246
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
247
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
248
class _StatefulDecoder(object):
249
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
250
    def __init__(self):
251
        self.finished_reading = False
252
        self.unused_data = ''
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
253
        self.bytes_left = None
254
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
255
    def accept_bytes(self, bytes):
256
        """Decode as much of bytes as possible.
257
258
        If 'bytes' contains too much data it will be appended to
259
        self.unused_data.
260
261
        finished_reading will be set when no more data is required.  Further
262
        data will be appended to self.unused_data.
263
        """
264
        # accept_bytes is allowed to change the state
265
        current_state = self.state_accept
266
        self.state_accept(bytes)
267
        while current_state != self.state_accept:
268
            current_state = self.state_accept
269
            self.state_accept('')
270
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
271
272
class ChunkedBodyDecoder(_StatefulDecoder):
273
    """Decoder for chunked body data.
274
2748.4.9 by Andrew Bennetts
Merge from hpss-protocol-docs.
275
    This is very similar the HTTP's chunked encoding.  See the description of
276
    streamed body data in `doc/developers/network-protocol.txt` for details.
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
277
    """
278
279
    def __init__(self):
280
        _StatefulDecoder.__init__(self)
2748.4.16 by Andrew Bennetts
Tweaks suggested by review.
281
        self.state_accept = self._state_accept_expecting_header
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
282
        self._in_buffer = ''
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
283
        self.chunk_in_progress = None
284
        self.chunks = collections.deque()
2748.4.6 by Andrew Bennetts
Use chunks for stream errors, rather than the response tuple format.
285
        self.error = False
286
        self.error_in_progress = None
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
287
    
288
    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.
289
        # Note: the shortest possible chunk is 2 bytes: '0\n', and the
290
        # end-of-body marker is 4 bytes: 'END\n'.
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
291
        if self.state_accept == self._state_accept_reading_chunk:
292
            # 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.
293
            # the rest of this chunk plus an END chunk.
294
            return self.bytes_left + 4
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
295
        elif self.state_accept == self._state_accept_expecting_length:
296
            if self._in_buffer == '':
297
                # We're expecting a chunk length.  There's at least two bytes
298
                # left: a digit plus '\n'.
299
                return 2
300
            else:
301
                # We're in the middle of reading a chunk length.  So there's at
302
                # least one byte left, the '\n' that terminates the length.
303
                return 1
304
        elif self.state_accept == self._state_accept_reading_unused:
305
            return 1
2748.4.16 by Andrew Bennetts
Tweaks suggested by review.
306
        elif self.state_accept == self._state_accept_expecting_header:
307
            return max(0, len('chunked\n') - len(self._in_buffer))
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
308
        else:
309
            raise AssertionError("Impossible state: %r" % (self.state_accept,))
310
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
311
    def read_next_chunk(self):
312
        try:
313
            return self.chunks.popleft()
314
        except IndexError:
315
            return None
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
316
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
317
    def _extract_line(self):
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
318
        pos = self._in_buffer.find('\n')
319
        if pos == -1:
320
            # We haven't read a complete length prefix yet, so there's nothing
321
            # to do.
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
322
            return None
323
        line = self._in_buffer[:pos]
324
        # Trim the prefix (including '\n' delimiter) from the _in_buffer.
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
325
        self._in_buffer = self._in_buffer[pos+1:]
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
326
        return line
327
328
    def _finished(self):
329
        self.unused_data = self._in_buffer
330
        self._in_buffer = None
331
        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.
332
        if self.error:
333
            error_args = tuple(self.error_in_progress)
334
            self.chunks.append(request.FailedSmartServerResponse(error_args))
335
            self.error_in_progress = None
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
336
        self.finished_reading = True
337
2748.4.16 by Andrew Bennetts
Tweaks suggested by review.
338
    def _state_accept_expecting_header(self, bytes):
339
        self._in_buffer += bytes
340
        prefix = self._extract_line()
341
        if prefix is None:
342
            # We haven't read a complete length prefix yet, so there's nothing
343
            # to do.
344
            return
345
        elif prefix == 'chunked':
346
            self.state_accept = self._state_accept_expecting_length
347
        else:
348
            raise errors.SmartProtocolError(
349
                'Bad chunked body header: "%s"' % (prefix,))
350
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
351
    def _state_accept_expecting_length(self, bytes):
352
        self._in_buffer += bytes
353
        prefix = self._extract_line()
354
        if prefix is None:
355
            # We haven't read a complete length prefix yet, so there's nothing
356
            # to do.
357
            return
358
        elif prefix == 'ERR':
2748.4.6 by Andrew Bennetts
Use chunks for stream errors, rather than the response tuple format.
359
            self.error = True
360
            self.error_in_progress = []
361
            self._state_accept_expecting_length('')
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
362
            return
2748.4.7 by Andrew Bennetts
Change the end-of-body marker to something clearer than a zero-length chunk.
363
        elif prefix == 'END':
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
364
            # We've read the end-of-body marker.
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
365
            # Any further bytes are unused data, including the bytes left in
366
            # the _in_buffer.
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
367
            self._finished()
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
368
            return
2748.4.7 by Andrew Bennetts
Change the end-of-body marker to something clearer than a zero-length chunk.
369
        else:
370
            self.bytes_left = int(prefix, 16)
371
            self.chunk_in_progress = ''
372
            self.state_accept = self._state_accept_reading_chunk
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
373
374
    def _state_accept_reading_chunk(self, bytes):
375
        self._in_buffer += bytes
376
        in_buffer_len = len(self._in_buffer)
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
377
        self.chunk_in_progress += self._in_buffer[:self.bytes_left]
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
378
        self._in_buffer = self._in_buffer[self.bytes_left:]
379
        self.bytes_left -= in_buffer_len
380
        if self.bytes_left <= 0:
381
            # Finished with chunk
382
            self.bytes_left = None
2748.4.6 by Andrew Bennetts
Use chunks for stream errors, rather than the response tuple format.
383
            if self.error:
384
                self.error_in_progress.append(self.chunk_in_progress)
385
            else:
386
                self.chunks.append(self.chunk_in_progress)
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
387
            self.chunk_in_progress = None
2748.4.1 by Andrew Bennetts
Implement a ChunkedBodyDecoder.
388
            self.state_accept = self._state_accept_expecting_length
389
        
390
    def _state_accept_reading_unused(self, bytes):
391
        self.unused_data += bytes
392
393
394
class LengthPrefixedBodyDecoder(_StatefulDecoder):
395
    """Decodes the length-prefixed bulk data."""
396
    
397
    def __init__(self):
398
        _StatefulDecoder.__init__(self)
399
        self.state_accept = self._state_accept_expecting_length
400
        self.state_read = self._state_read_no_data
401
        self._in_buffer = ''
402
        self._trailer_buffer = ''
403
    
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
404
    def next_read_size(self):
405
        if self.bytes_left is not None:
406
            # Ideally we want to read all the remainder of the body and the
407
            # trailer in one go.
408
            return self.bytes_left + 5
409
        elif self.state_accept == self._state_accept_reading_trailer:
410
            # Just the trailer left
411
            return 5 - len(self._trailer_buffer)
412
        elif self.state_accept == self._state_accept_expecting_length:
413
            # There's still at least 6 bytes left ('\n' to end the length, plus
414
            # 'done\n').
415
            return 6
416
        else:
417
            # Reading excess data.  Either way, 1 byte at a time is fine.
418
            return 1
419
        
420
    def read_pending_data(self):
421
        """Return any pending data that has been decoded."""
422
        return self.state_read()
423
424
    def _state_accept_expecting_length(self, bytes):
425
        self._in_buffer += bytes
426
        pos = self._in_buffer.find('\n')
427
        if pos == -1:
428
            return
429
        self.bytes_left = int(self._in_buffer[:pos])
430
        self._in_buffer = self._in_buffer[pos+1:]
431
        self.bytes_left -= len(self._in_buffer)
432
        self.state_accept = self._state_accept_reading_body
433
        self.state_read = self._state_read_in_buffer
434
435
    def _state_accept_reading_body(self, bytes):
436
        self._in_buffer += bytes
437
        self.bytes_left -= len(bytes)
438
        if self.bytes_left <= 0:
439
            # Finished with body
440
            if self.bytes_left != 0:
441
                self._trailer_buffer = self._in_buffer[self.bytes_left:]
442
                self._in_buffer = self._in_buffer[:self.bytes_left]
443
            self.bytes_left = None
444
            self.state_accept = self._state_accept_reading_trailer
445
        
446
    def _state_accept_reading_trailer(self, bytes):
447
        self._trailer_buffer += bytes
448
        # TODO: what if the trailer does not match "done\n"?  Should this raise
449
        # a ProtocolViolation exception?
450
        if self._trailer_buffer.startswith('done\n'):
451
            self.unused_data = self._trailer_buffer[len('done\n'):]
452
            self.state_accept = self._state_accept_reading_unused
453
            self.finished_reading = True
454
    
455
    def _state_accept_reading_unused(self, bytes):
456
        self.unused_data += bytes
457
458
    def _state_read_no_data(self):
459
        return ''
460
461
    def _state_read_in_buffer(self):
462
        result = self._in_buffer
463
        self._in_buffer = ''
464
        return result
465
466
467
class SmartClientRequestProtocolOne(SmartProtocolBase):
468
    """The client-side protocol for smart version 1."""
469
470
    def __init__(self, request):
471
        """Construct a SmartClientRequestProtocolOne.
472
473
        :param request: A SmartClientMediumRequest to serialise onto and
474
            deserialise from.
475
        """
476
        self._request = request
477
        self._body_buffer = None
2664.4.1 by John Arbash Meinel
Add timing information for call/response groups for hpss
478
        self._request_start_time = None
3297.3.1 by Andrew Bennetts
Raise UnknownSmartMethod automatically from read_response_tuple.
479
        self._last_verb = None
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
480
481
    def call(self, *args):
2593.3.1 by Andrew Bennetts
Add a -Dhpss debug flag.
482
        if 'hpss' in debug.debug_flags:
2664.4.3 by John Arbash Meinel
Update to include a bit better formatting
483
            mutter('hpss call:   %s', repr(args)[1:-1])
3104.4.2 by Andrew Bennetts
All tests passing.
484
            if getattr(self._request._medium, 'base', None) is not None:
485
                mutter('             (to %s)', self._request._medium.base)
2664.4.1 by John Arbash Meinel
Add timing information for call/response groups for hpss
486
            self._request_start_time = time.time()
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
487
        self._write_args(args)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
488
        self._request.finished_writing()
3297.3.1 by Andrew Bennetts
Raise UnknownSmartMethod automatically from read_response_tuple.
489
        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
490
491
    def call_with_body_bytes(self, args, body):
492
        """Make a remote call of args with body bytes 'body'.
493
494
        After calling this, call read_response_tuple to find the result out.
495
        """
2593.3.1 by Andrew Bennetts
Add a -Dhpss debug flag.
496
        if 'hpss' in debug.debug_flags:
2664.4.3 by John Arbash Meinel
Update to include a bit better formatting
497
            mutter('hpss call w/body: %s (%r...)', repr(args)[1:-1], body[:20])
3104.4.2 by Andrew Bennetts
All tests passing.
498
            if getattr(self._request._medium, '_path', None) is not None:
499
                mutter('                  (to %s)', self._request._medium._path)
2664.4.4 by John Arbash Meinel
Switch around what bytes get logged.
500
            mutter('              %d bytes', len(body))
2664.4.3 by John Arbash Meinel
Update to include a bit better formatting
501
            self._request_start_time = time.time()
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.
502
            if 'hpssdetail' in debug.debug_flags:
503
                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.
504
        self._write_args(args)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
505
        bytes = self._encode_bulk_data(body)
506
        self._request.accept_bytes(bytes)
507
        self._request.finished_writing()
3297.3.1 by Andrew Bennetts
Raise UnknownSmartMethod automatically from read_response_tuple.
508
        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
509
510
    def call_with_body_readv_array(self, args, body):
511
        """Make a remote call with a readv array.
512
513
        The body is encoded with one line per readv offset pair. The numbers in
514
        each pair are separated by a comma, and no trailing \n is emitted.
515
        """
2593.3.1 by Andrew Bennetts
Add a -Dhpss debug flag.
516
        if 'hpss' in debug.debug_flags:
2664.4.3 by John Arbash Meinel
Update to include a bit better formatting
517
            mutter('hpss call w/readv: %s', repr(args)[1:-1])
3104.4.2 by Andrew Bennetts
All tests passing.
518
            if getattr(self._request._medium, '_path', None) is not None:
519
                mutter('                  (to %s)', self._request._medium._path)
2664.4.3 by John Arbash Meinel
Update to include a bit better formatting
520
            self._request_start_time = time.time()
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
521
        self._write_args(args)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
522
        readv_bytes = self._serialise_offsets(body)
523
        bytes = self._encode_bulk_data(readv_bytes)
524
        self._request.accept_bytes(bytes)
525
        self._request.finished_writing()
2664.4.2 by John Arbash Meinel
Add debug timings for operations that have to send data
526
        if 'hpss' in debug.debug_flags:
2664.4.4 by John Arbash Meinel
Switch around what bytes get logged.
527
            mutter('              %d bytes in readv request', len(readv_bytes))
3297.3.1 by Andrew Bennetts
Raise UnknownSmartMethod automatically from read_response_tuple.
528
        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
529
530
    def cancel_read_body(self):
531
        """After expecting a body, a response code may indicate one otherwise.
532
533
        This method lets the domain client inform the protocol that no body
534
        will be transmitted. This is a terminal method: after calling it the
535
        protocol is not able to be used further.
536
        """
537
        self._request.finished_reading()
538
539
    def read_response_tuple(self, expect_body=False):
540
        """Read a response tuple from the wire.
541
542
        This should only be called once.
543
        """
544
        result = self._recv_tuple()
2593.3.1 by Andrew Bennetts
Add a -Dhpss debug flag.
545
        if 'hpss' in debug.debug_flags:
2664.4.1 by John Arbash Meinel
Add timing information for call/response groups for hpss
546
            if self._request_start_time is not None:
2664.4.3 by John Arbash Meinel
Update to include a bit better formatting
547
                mutter('   result:   %6.3fs  %s',
2664.4.1 by John Arbash Meinel
Add timing information for call/response groups for hpss
548
                       time.time() - self._request_start_time,
2664.4.3 by John Arbash Meinel
Update to include a bit better formatting
549
                       repr(result)[1:-1])
2664.4.1 by John Arbash Meinel
Add timing information for call/response groups for hpss
550
                self._request_start_time = None
551
            else:
2664.4.3 by John Arbash Meinel
Update to include a bit better formatting
552
                mutter('   result:   %s', repr(result)[1:-1])
3297.3.1 by Andrew Bennetts
Raise UnknownSmartMethod automatically from read_response_tuple.
553
        self._response_is_unknown_method(result)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
554
        if not expect_body:
555
            self._request.finished_reading()
556
        return result
557
3297.3.1 by Andrew Bennetts
Raise UnknownSmartMethod automatically from read_response_tuple.
558
    def _response_is_unknown_method(self, result_tuple):
559
        """Raise UnexpectedSmartServerResponse if the response is an 'unknonwn
560
        method' response to the request.
561
        
562
        :param response: The response from a smart client call_expecting_body
563
            call.
564
        :param verb: The verb used in that call.
565
        :raises: UnexpectedSmartServerResponse
566
        """
567
        if (result_tuple == ('error', "Generic bzr smart protocol error: "
568
                "bad request '%s'" % self._last_verb) or
569
              result_tuple == ('error', "Generic bzr smart protocol error: "
570
                "bad request u'%s'" % self._last_verb)):
571
            # The response will have no body, so we've finished reading.
572
            self._request.finished_reading()
573
            raise errors.UnknownSmartMethod(self._last_verb)
574
        
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
575
    def read_body_bytes(self, count=-1):
576
        """Read bytes from the body, decoding into a byte stream.
577
        
578
        We read all bytes at once to ensure we've checked the trailer for 
579
        errors, and then feed the buffer back as read_body_bytes is called.
580
        """
581
        if self._body_buffer is not None:
582
            return self._body_buffer.read(count)
583
        _body_decoder = LengthPrefixedBodyDecoder()
584
3170.5.1 by Andrew Bennetts
Fix the other half of bug #115781: don't read more than 64k at a time either.
585
        # Read no more than 64k at a time so that we don't risk error 10055 (no
586
        # buffer space available) on Windows.
587
        max_read = 64 * 1024
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
588
        while not _body_decoder.finished_reading:
3170.5.1 by Andrew Bennetts
Fix the other half of bug #115781: don't read more than 64k at a time either.
589
            bytes_wanted = min(_body_decoder.next_read_size(), max_read)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
590
            bytes = self._request.read_bytes(bytes_wanted)
591
            _body_decoder.accept_bytes(bytes)
592
        self._request.finished_reading()
593
        self._body_buffer = StringIO(_body_decoder.read_pending_data())
594
        # XXX: TODO check the trailer result.
2664.4.3 by John Arbash Meinel
Update to include a bit better formatting
595
        if 'hpss' in debug.debug_flags:
2664.4.4 by John Arbash Meinel
Switch around what bytes get logged.
596
            mutter('              %d body bytes read',
2664.4.3 by John Arbash Meinel
Update to include a bit better formatting
597
                   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
598
        return self._body_buffer.read(count)
599
600
    def _recv_tuple(self):
601
        """Receive a tuple from the medium request."""
2432.4.6 by Robert Collins
Include success/failure feedback in SmartProtocolTwo responses to allow robust handling in the future.
602
        return _decode_tuple(self._recv_line())
603
604
    def _recv_line(self):
605
        """Read an entire line from the medium request."""
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
606
        line = ''
607
        while not line or line[-1] != '\n':
608
            # TODO: this is inefficient - but tuples are short.
609
            new_char = self._request.read_bytes(1)
2930.1.1 by Ian Clatworthy
error msg instead of assert when connection over bzr+ssh fails (#115601)
610
            if new_char == '':
611
                # end of file encountered reading from server
2930.1.2 by Ian Clatworthy
Review feedback from poolie and spiv
612
                raise errors.ConnectionReset(
613
                    "please check connectivity and permissions",
614
                    "(and try -Dhpss if further diagnosis is required)")
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
615
            line += new_char
2432.4.6 by Robert Collins
Include success/failure feedback in SmartProtocolTwo responses to allow robust handling in the future.
616
        return line
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
617
618
    def query_version(self):
619
        """Return protocol version number of the server."""
620
        self.call('hello')
621
        resp = self.read_response_tuple()
622
        if resp == ('ok', '1'):
623
            return 1
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
624
        elif resp == ('ok', '2'):
625
            return 2
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
626
        else:
627
            raise errors.SmartProtocolError("bad response %r" % (resp,))
628
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
629
    def _write_args(self, args):
630
        self._write_protocol_version()
631
        bytes = _encode_tuple(args)
632
        self._request.accept_bytes(bytes)
633
634
    def _write_protocol_version(self):
635
        """Write any prefixes this protocol requires.
636
        
637
        Version one doesn't send protocol versions.
638
        """
639
640
641
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.
642
    """Version two of the client side of the smart protocol.
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
643
    
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
644
    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.
645
    """
646
647
    def read_response_tuple(self, expect_body=False):
648
        """Read a response tuple from the wire.
649
650
        This should only be called once.
651
        """
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
652
        version = self._request.read_line()
653
        if version != RESPONSE_VERSION_TWO:
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
654
            raise errors.SmartProtocolError('bad protocol marker %r' % version)
2432.4.6 by Robert Collins
Include success/failure feedback in SmartProtocolTwo responses to allow robust handling in the future.
655
        response_status = self._recv_line()
656
        if response_status not in ('success\n', 'failed\n'):
657
            raise errors.SmartProtocolError(
658
                'bad protocol status %r' % response_status)
659
        self.response_status = response_status == 'success\n'
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
660
        return SmartClientRequestProtocolOne.read_response_tuple(self, expect_body)
661
662
    def _write_protocol_version(self):
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
663
        """Write any prefixes this protocol requires.
2432.2.1 by Andrew Bennetts
Add Smart{Client,Server}RequestProtocolTwo, that prefix args tuples with a version marker.
664
        
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
665
        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.
666
        """
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
667
        self._request.accept_bytes(REQUEST_VERSION_TWO)
2018.5.3 by Andrew Bennetts
Split up more smart server code, this time into bzrlib/transport/smart/protocol.py
668
2748.4.2 by Andrew Bennetts
Add protocol (version two) support for streaming bodies (using chunking) in responses.
669
    def read_streamed_body(self):
670
        """Read bytes from the body, decoding into a byte stream.
671
        """
3170.5.1 by Andrew Bennetts
Fix the other half of bug #115781: don't read more than 64k at a time either.
672
        # Read no more than 64k at a time so that we don't risk error 10055 (no
673
        # buffer space available) on Windows.
674
        max_read = 64 * 1024
2748.4.2 by Andrew Bennetts
Add protocol (version two) support for streaming bodies (using chunking) in responses.
675
        _body_decoder = ChunkedBodyDecoder()
676
        while not _body_decoder.finished_reading:
3170.5.1 by Andrew Bennetts
Fix the other half of bug #115781: don't read more than 64k at a time either.
677
            bytes_wanted = min(_body_decoder.next_read_size(), max_read)
2748.4.2 by Andrew Bennetts
Add protocol (version two) support for streaming bodies (using chunking) in responses.
678
            bytes = self._request.read_bytes(bytes_wanted)
679
            _body_decoder.accept_bytes(bytes)
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
680
            for body_bytes in iter(_body_decoder.read_next_chunk, None):
2535.4.3 by Andrew Bennetts
Remove some useless mutters.
681
                if 'hpss' in debug.debug_flags:
2748.4.5 by Andrew Bennetts
Allow an error to interrupt (and terminate) a streamed response body.
682
                    mutter('              %d byte chunk read',
2535.4.3 by Andrew Bennetts
Remove some useless mutters.
683
                           len(body_bytes))
2748.4.2 by Andrew Bennetts
Add protocol (version two) support for streaming bodies (using chunking) in responses.
684
                yield body_bytes
685
        self._request.finished_reading()
686