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