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