~bzr-pqm/bzr/bzr.dev

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