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