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