246
150
return self._body_decoder.next_read_size()
249
class SmartServerRequestProtocolTwo(SmartServerRequestProtocolOne):
250
r"""Version two of the server side of the smart protocol.
252
This prefixes responses with the value of RESPONSE_VERSION_TWO.
255
response_marker = RESPONSE_VERSION_TWO
256
request_marker = REQUEST_VERSION_TWO
258
def _write_success_or_failure_prefix(self, response):
259
"""Write the protocol specific success/failure prefix."""
260
if response.is_successful():
261
self._write_func(b'success\n')
263
self._write_func(b'failed\n')
265
def _write_protocol_version(self):
266
r"""Write any prefixes this protocol requires.
268
Version two sends the value of RESPONSE_VERSION_TWO.
270
self._write_func(self.response_marker)
272
def _send_response(self, response):
273
"""Send a smart server response down the output stream."""
275
raise AssertionError('response already sent')
276
self._finished = True
277
self._write_protocol_version()
278
self._write_success_or_failure_prefix(response)
279
self._write_func(_encode_tuple(response.args))
280
if response.body is not None:
281
if not isinstance(response.body, bytes):
282
raise AssertionError('body must be bytes')
283
if not (response.body_stream is None):
284
raise AssertionError(
285
'body_stream and body cannot both be set')
286
data = self._encode_bulk_data(response.body)
287
self._write_func(data)
288
elif response.body_stream is not None:
289
_send_stream(response.body_stream, self._write_func)
292
def _send_stream(stream, write_func):
293
write_func(b'chunked\n')
294
_send_chunks(stream, write_func)
298
def _send_chunks(stream, write_func):
300
if isinstance(chunk, bytes):
301
data = ("%x\n" % len(chunk)).encode('ascii') + chunk
303
elif isinstance(chunk, request.FailedSmartServerResponse):
305
_send_chunks(chunk.args, write_func)
308
raise errors.BzrError(
309
'Chunks must be str or FailedSmartServerResponse, got %r'
313
class _NeedMoreBytes(Exception):
314
"""Raise this inside a _StatefulDecoder to stop decoding until more bytes
318
def __init__(self, count=None):
321
:param count: the total number of bytes needed by the current state.
322
May be None if the number of bytes needed is unknown.
327
class _StatefulDecoder(object):
328
"""Base class for writing state machines to decode byte streams.
330
Subclasses should provide a self.state_accept attribute that accepts bytes
331
and, if appropriate, updates self.state_accept to a different function.
332
accept_bytes will call state_accept as often as necessary to make sure the
333
state machine has progressed as far as possible before it returns.
335
See ProtocolThreeDecoder for an example subclass.
153
class LengthPrefixedBodyDecoder(object):
154
"""Decodes the length-prefixed bulk data."""
338
156
def __init__(self):
157
self.bytes_left = None
339
158
self.finished_reading = False
340
self._in_buffer_list = []
341
self._in_buffer_len = 0
342
self.unused_data = b''
343
self.bytes_left = None
344
self._number_needed_bytes = None
346
def _get_in_buffer(self):
347
if len(self._in_buffer_list) == 1:
348
return self._in_buffer_list[0]
349
in_buffer = b''.join(self._in_buffer_list)
350
if len(in_buffer) != self._in_buffer_len:
351
raise AssertionError(
352
"Length of buffer did not match expected value: %s != %s"
353
% self._in_buffer_len, len(in_buffer))
354
self._in_buffer_list = [in_buffer]
357
def _get_in_bytes(self, count):
358
"""Grab X bytes from the input_buffer.
360
Callers should have already checked that self._in_buffer_len is >
361
count. Note, this does not consume the bytes from the buffer. The
362
caller will still need to call _get_in_buffer() and then
363
_set_in_buffer() if they actually need to consume the bytes.
365
# check if we can yield the bytes from just the first entry in our list
366
if len(self._in_buffer_list) == 0:
367
raise AssertionError('Callers must be sure we have buffered bytes'
368
' before calling _get_in_bytes')
369
if len(self._in_buffer_list[0]) > count:
370
return self._in_buffer_list[0][:count]
371
# We can't yield it from the first buffer, so collapse all buffers, and
373
in_buf = self._get_in_buffer()
374
return in_buf[:count]
376
def _set_in_buffer(self, new_buf):
377
if new_buf is not None:
378
if not isinstance(new_buf, bytes):
379
raise TypeError(new_buf)
380
self._in_buffer_list = [new_buf]
381
self._in_buffer_len = len(new_buf)
383
self._in_buffer_list = []
384
self._in_buffer_len = 0
386
def accept_bytes(self, new_buf):
159
self.unused_data = ''
160
self.state_accept = self._state_accept_expecting_length
161
self.state_read = self._state_read_no_data
163
self._trailer_buffer = ''
165
def accept_bytes(self, bytes):
387
166
"""Decode as much of bytes as possible.
389
If 'new_buf' contains too much data it will be appended to
168
If 'bytes' contains too much data it will be appended to
390
169
self.unused_data.
392
171
finished_reading will be set when no more data is required. Further
393
172
data will be appended to self.unused_data.
395
if not isinstance(new_buf, bytes):
396
raise TypeError(new_buf)
397
174
# accept_bytes is allowed to change the state
398
self._number_needed_bytes = None
399
# lsprof puts a very large amount of time on this specific call for
401
self._in_buffer_list.append(new_buf)
402
self._in_buffer_len += len(new_buf)
404
# Run the function for the current state.
175
current_state = self.state_accept
176
self.state_accept(bytes)
177
while current_state != self.state_accept:
405
178
current_state = self.state_accept
407
while current_state != self.state_accept:
408
# The current state has changed. Run the function for the new
409
# current state, so that it can:
410
# - decode any unconsumed bytes left in a buffer, and
411
# - signal how many more bytes are expected (via raising
413
current_state = self.state_accept
415
except _NeedMoreBytes as e:
416
self._number_needed_bytes = e.count
419
class ChunkedBodyDecoder(_StatefulDecoder):
420
"""Decoder for chunked body data.
422
This is very similar the HTTP's chunked encoding. See the description of
423
streamed body data in `doc/developers/network-protocol.txt` for details.
427
_StatefulDecoder.__init__(self)
428
self.state_accept = self._state_accept_expecting_header
429
self.chunk_in_progress = None
430
self.chunks = deque()
432
self.error_in_progress = None
434
def next_read_size(self):
435
# Note: the shortest possible chunk is 2 bytes: '0\n', and the
436
# end-of-body marker is 4 bytes: 'END\n'.
437
if self.state_accept == self._state_accept_reading_chunk:
438
# We're expecting more chunk content. So we're expecting at least
439
# the rest of this chunk plus an END chunk.
440
return self.bytes_left + 4
441
elif self.state_accept == self._state_accept_expecting_length:
442
if self._in_buffer_len == 0:
443
# We're expecting a chunk length. There's at least two bytes
444
# left: a digit plus '\n'.
447
# We're in the middle of reading a chunk length. So there's at
448
# least one byte left, the '\n' that terminates the length.
450
elif self.state_accept == self._state_accept_reading_unused:
452
elif self.state_accept == self._state_accept_expecting_header:
453
return max(0, len('chunked\n') - self._in_buffer_len)
455
raise AssertionError("Impossible state: %r" % (self.state_accept,))
457
def read_next_chunk(self):
459
return self.chunks.popleft()
463
def _extract_line(self):
464
in_buf = self._get_in_buffer()
465
pos = in_buf.find(b'\n')
467
# We haven't read a complete line yet, so request more bytes before
469
raise _NeedMoreBytes(1)
471
# Trim the prefix (including '\n' delimiter) from the _in_buffer.
472
self._set_in_buffer(in_buf[pos + 1:])
476
self.unused_data = self._get_in_buffer()
477
self._in_buffer_list = []
478
self._in_buffer_len = 0
479
self.state_accept = self._state_accept_reading_unused
481
error_args = tuple(self.error_in_progress)
482
self.chunks.append(request.FailedSmartServerResponse(error_args))
483
self.error_in_progress = None
484
self.finished_reading = True
486
def _state_accept_expecting_header(self):
487
prefix = self._extract_line()
488
if prefix == b'chunked':
489
self.state_accept = self._state_accept_expecting_length
491
raise errors.SmartProtocolError(
492
'Bad chunked body header: "%s"' % (prefix,))
494
def _state_accept_expecting_length(self):
495
prefix = self._extract_line()
498
self.error_in_progress = []
499
self._state_accept_expecting_length()
501
elif prefix == b'END':
502
# We've read the end-of-body marker.
503
# Any further bytes are unused data, including the bytes left in
508
self.bytes_left = int(prefix, 16)
509
self.chunk_in_progress = b''
510
self.state_accept = self._state_accept_reading_chunk
512
def _state_accept_reading_chunk(self):
513
in_buf = self._get_in_buffer()
514
in_buffer_len = len(in_buf)
515
self.chunk_in_progress += in_buf[:self.bytes_left]
516
self._set_in_buffer(in_buf[self.bytes_left:])
517
self.bytes_left -= in_buffer_len
518
if self.bytes_left <= 0:
519
# Finished with chunk
520
self.bytes_left = None
522
self.error_in_progress.append(self.chunk_in_progress)
524
self.chunks.append(self.chunk_in_progress)
525
self.chunk_in_progress = None
526
self.state_accept = self._state_accept_expecting_length
528
def _state_accept_reading_unused(self):
529
self.unused_data += self._get_in_buffer()
530
self._in_buffer_list = []
533
class LengthPrefixedBodyDecoder(_StatefulDecoder):
534
"""Decodes the length-prefixed bulk data."""
537
_StatefulDecoder.__init__(self)
538
self.state_accept = self._state_accept_expecting_length
539
self.state_read = self._state_read_no_data
541
self._trailer_buffer = b''
179
self.state_accept('')
543
181
def next_read_size(self):
544
182
if self.bytes_left is not None:
774
312
_body_decoder = LengthPrefixedBodyDecoder()
776
314
while not _body_decoder.finished_reading:
777
bytes = self._request.read_bytes(_body_decoder.next_read_size())
779
# end of file encountered reading from server
780
raise errors.ConnectionReset(
781
"Connection lost while reading response body.")
315
bytes_wanted = _body_decoder.next_read_size()
316
bytes = self._request.read_bytes(bytes_wanted)
782
317
_body_decoder.accept_bytes(bytes)
783
318
self._request.finished_reading()
784
self._body_buffer = BytesIO(_body_decoder.read_pending_data())
319
self._body_buffer = StringIO(_body_decoder.read_pending_data())
785
320
# XXX: TODO check the trailer result.
786
if 'hpss' in debug.debug_flags:
787
mutter(' %d body bytes read',
788
len(self._body_buffer.getvalue()))
789
321
return self._body_buffer.read(count)
791
323
def _recv_tuple(self):
792
324
"""Receive a tuple from the medium request."""
793
return _decode_tuple(self._request.read_line())
326
while not line or line[-1] != '\n':
327
# TODO: this is inefficient - but tuples are short.
328
new_char = self._request.read_bytes(1)
330
assert new_char != '', "end of file reading from server."
331
return _decode_tuple(line)
795
333
def query_version(self):
796
334
"""Return protocol version number of the server."""
798
336
resp = self.read_response_tuple()
799
if resp == (b'ok', b'1'):
337
if resp == ('ok', '1'):
801
elif resp == (b'ok', b'2'):
804
340
raise errors.SmartProtocolError("bad response %r" % (resp,))
806
def _write_args(self, args):
807
self._write_protocol_version()
808
bytes = _encode_tuple(args)
809
self._request.accept_bytes(bytes)
811
def _write_protocol_version(self):
812
"""Write any prefixes this protocol requires.
814
Version one doesn't send protocol versions.
818
class SmartClientRequestProtocolTwo(SmartClientRequestProtocolOne):
819
"""Version two of the client side of the smart protocol.
821
This prefixes the request with the value of REQUEST_VERSION_TWO.
824
response_marker = RESPONSE_VERSION_TWO
825
request_marker = REQUEST_VERSION_TWO
827
def read_response_tuple(self, expect_body=False):
828
"""Read a response tuple from the wire.
830
This should only be called once.
832
version = self._request.read_line()
833
if version != self.response_marker:
834
self._request.finished_reading()
835
raise errors.UnexpectedProtocolVersionMarker(version)
836
response_status = self._request.read_line()
837
result = SmartClientRequestProtocolOne._read_response_tuple(self)
838
self._response_is_unknown_method(result)
839
if response_status == b'success\n':
840
self.response_status = True
842
self._request.finished_reading()
844
elif response_status == b'failed\n':
845
self.response_status = False
846
self._request.finished_reading()
847
raise errors.ErrorFromSmartServer(result)
849
raise errors.SmartProtocolError(
850
'bad protocol status %r' % response_status)
852
def _write_protocol_version(self):
853
"""Write any prefixes this protocol requires.
855
Version two sends the value of REQUEST_VERSION_TWO.
857
self._request.accept_bytes(self.request_marker)
859
def read_streamed_body(self):
860
"""Read bytes from the body, decoding into a byte stream.
862
# Read no more than 64k at a time so that we don't risk error 10055 (no
863
# buffer space available) on Windows.
864
_body_decoder = ChunkedBodyDecoder()
865
while not _body_decoder.finished_reading:
866
bytes = self._request.read_bytes(_body_decoder.next_read_size())
868
# end of file encountered reading from server
869
raise errors.ConnectionReset(
870
"Connection lost while reading streamed body.")
871
_body_decoder.accept_bytes(bytes)
872
for body_bytes in iter(_body_decoder.read_next_chunk, None):
873
if 'hpss' in debug.debug_flags and isinstance(body_bytes, str):
874
mutter(' %d byte chunk read',
877
self._request.finished_reading()
880
def build_server_protocol_three(backing_transport, write_func,
881
root_client_path, jail_root=None):
882
request_handler = request.SmartServerRequestHandler(
883
backing_transport, commands=request.request_handlers,
884
root_client_path=root_client_path, jail_root=jail_root)
885
responder = ProtocolThreeResponder(write_func)
886
message_handler = message.ConventionalRequestHandler(
887
request_handler, responder)
888
return ProtocolThreeDecoder(message_handler)
891
class ProtocolThreeDecoder(_StatefulDecoder):
893
response_marker = RESPONSE_VERSION_THREE
894
request_marker = REQUEST_VERSION_THREE
896
def __init__(self, message_handler, expect_version_marker=False):
897
_StatefulDecoder.__init__(self)
898
self._has_dispatched = False
900
if expect_version_marker:
901
self.state_accept = self._state_accept_expecting_protocol_version
902
# We're expecting at least the protocol version marker + some
904
self._number_needed_bytes = len(MESSAGE_VERSION_THREE) + 4
906
self.state_accept = self._state_accept_expecting_headers
907
self._number_needed_bytes = 4
908
self.decoding_failed = False
909
self.request_handler = self.message_handler = message_handler
911
def accept_bytes(self, bytes):
912
self._number_needed_bytes = None
914
_StatefulDecoder.accept_bytes(self, bytes)
915
except KeyboardInterrupt:
917
except errors.SmartMessageHandlerError as exception:
918
# We do *not* set self.decoding_failed here. The message handler
919
# has raised an error, but the decoder is still able to parse bytes
920
# and determine when this message ends.
921
if not isinstance(exception.exc_value, errors.UnknownSmartMethod):
922
log_exception_quietly()
923
self.message_handler.protocol_error(exception.exc_value)
924
# The state machine is ready to continue decoding, but the
925
# exception has interrupted the loop that runs the state machine.
926
# So we call accept_bytes again to restart it.
927
self.accept_bytes(b'')
928
except Exception as exception:
929
# The decoder itself has raised an exception. We cannot continue
931
self.decoding_failed = True
932
if isinstance(exception, errors.UnexpectedProtocolVersionMarker):
933
# This happens during normal operation when the client tries a
934
# protocol version the server doesn't understand, so no need to
935
# log a traceback every time.
936
# Note that this can only happen when
937
# expect_version_marker=True, which is only the case on the
941
log_exception_quietly()
942
self.message_handler.protocol_error(exception)
944
def _extract_length_prefixed_bytes(self):
945
if self._in_buffer_len < 4:
946
# A length prefix by itself is 4 bytes, and we don't even have that
948
raise _NeedMoreBytes(4)
949
(length,) = struct.unpack('!L', self._get_in_bytes(4))
950
end_of_bytes = 4 + length
951
if self._in_buffer_len < end_of_bytes:
952
# We haven't yet read as many bytes as the length-prefix says there
954
raise _NeedMoreBytes(end_of_bytes)
955
# Extract the bytes from the buffer.
956
in_buf = self._get_in_buffer()
957
bytes = in_buf[4:end_of_bytes]
958
self._set_in_buffer(in_buf[end_of_bytes:])
961
def _extract_prefixed_bencoded_data(self):
962
prefixed_bytes = self._extract_length_prefixed_bytes()
964
decoded = bdecode_as_tuple(prefixed_bytes)
966
raise errors.SmartProtocolError(
967
'Bytes %r not bencoded' % (prefixed_bytes,))
970
def _extract_single_byte(self):
971
if self._in_buffer_len == 0:
972
# The buffer is empty
973
raise _NeedMoreBytes(1)
974
in_buf = self._get_in_buffer()
975
one_byte = in_buf[0:1]
976
self._set_in_buffer(in_buf[1:])
979
def _state_accept_expecting_protocol_version(self):
980
needed_bytes = len(MESSAGE_VERSION_THREE) - self._in_buffer_len
981
in_buf = self._get_in_buffer()
983
# We don't have enough bytes to check if the protocol version
984
# marker is right. But we can check if it is already wrong by
985
# checking that the start of MESSAGE_VERSION_THREE matches what
987
# [In fact, if the remote end isn't bzr we might never receive
988
# len(MESSAGE_VERSION_THREE) bytes. So if the bytes we have so far
989
# are wrong then we should just raise immediately rather than
991
if not MESSAGE_VERSION_THREE.startswith(in_buf):
992
# We have enough bytes to know the protocol version is wrong
993
raise errors.UnexpectedProtocolVersionMarker(in_buf)
994
raise _NeedMoreBytes(len(MESSAGE_VERSION_THREE))
995
if not in_buf.startswith(MESSAGE_VERSION_THREE):
996
raise errors.UnexpectedProtocolVersionMarker(in_buf)
997
self._set_in_buffer(in_buf[len(MESSAGE_VERSION_THREE):])
998
self.state_accept = self._state_accept_expecting_headers
1000
def _state_accept_expecting_headers(self):
1001
decoded = self._extract_prefixed_bencoded_data()
1002
if not isinstance(decoded, dict):
1003
raise errors.SmartProtocolError(
1004
'Header object %r is not a dict' % (decoded,))
1005
self.state_accept = self._state_accept_expecting_message_part
1007
self.message_handler.headers_received(decoded)
1009
raise errors.SmartMessageHandlerError(sys.exc_info())
1011
def _state_accept_expecting_message_part(self):
1012
message_part_kind = self._extract_single_byte()
1013
if message_part_kind == b'o':
1014
self.state_accept = self._state_accept_expecting_one_byte
1015
elif message_part_kind == b's':
1016
self.state_accept = self._state_accept_expecting_structure
1017
elif message_part_kind == b'b':
1018
self.state_accept = self._state_accept_expecting_bytes
1019
elif message_part_kind == b'e':
1022
raise errors.SmartProtocolError(
1023
'Bad message kind byte: %r' % (message_part_kind,))
1025
def _state_accept_expecting_one_byte(self):
1026
byte = self._extract_single_byte()
1027
self.state_accept = self._state_accept_expecting_message_part
1029
self.message_handler.byte_part_received(byte)
1031
raise errors.SmartMessageHandlerError(sys.exc_info())
1033
def _state_accept_expecting_bytes(self):
1034
# XXX: this should not buffer whole message part, but instead deliver
1035
# the bytes as they arrive.
1036
prefixed_bytes = self._extract_length_prefixed_bytes()
1037
self.state_accept = self._state_accept_expecting_message_part
1039
self.message_handler.bytes_part_received(prefixed_bytes)
1041
raise errors.SmartMessageHandlerError(sys.exc_info())
1043
def _state_accept_expecting_structure(self):
1044
structure = self._extract_prefixed_bencoded_data()
1045
self.state_accept = self._state_accept_expecting_message_part
1047
self.message_handler.structure_part_received(structure)
1049
raise errors.SmartMessageHandlerError(sys.exc_info())
1052
self.unused_data = self._get_in_buffer()
1053
self._set_in_buffer(None)
1054
self.state_accept = self._state_accept_reading_unused
1056
self.message_handler.end_received()
1058
raise errors.SmartMessageHandlerError(sys.exc_info())
1060
def _state_accept_reading_unused(self):
1061
self.unused_data += self._get_in_buffer()
1062
self._set_in_buffer(None)
1064
def next_read_size(self):
1065
if self.state_accept == self._state_accept_reading_unused:
1067
elif self.decoding_failed:
1068
# An exception occured while processing this message, probably from
1069
# self.message_handler. We're not sure that this state machine is
1070
# in a consistent state, so just signal that we're done (i.e. give
1074
if self._number_needed_bytes is not None:
1075
return self._number_needed_bytes - self._in_buffer_len
1077
raise AssertionError("don't know how many bytes are expected!")
1080
class _ProtocolThreeEncoder(object):
1082
response_marker = request_marker = MESSAGE_VERSION_THREE
1083
BUFFER_SIZE = 1024 * 1024 # 1 MiB buffer before flushing
1085
def __init__(self, write_func):
1088
self._real_write_func = write_func
1090
def _write_func(self, bytes):
1091
# TODO: Another possibility would be to turn this into an async model.
1092
# Where we let another thread know that we have some bytes if
1093
# they want it, but we don't actually block for it
1094
# Note that osutils.send_all always sends 64kB chunks anyway, so
1095
# we might just push out smaller bits at a time?
1096
self._buf.append(bytes)
1097
self._buf_len += len(bytes)
1098
if self._buf_len > self.BUFFER_SIZE:
1103
self._real_write_func(b''.join(self._buf))
1107
def _serialise_offsets(self, offsets):
1108
"""Serialise a readv offset list."""
1110
for start, length in offsets:
1111
txt.append(b'%d,%d' % (start, length))
1112
return b'\n'.join(txt)
1114
def _write_protocol_version(self):
1115
self._write_func(MESSAGE_VERSION_THREE)
1117
def _write_prefixed_bencode(self, structure):
1118
bytes = bencode(structure)
1119
self._write_func(struct.pack('!L', len(bytes)))
1120
self._write_func(bytes)
1122
def _write_headers(self, headers):
1123
self._write_prefixed_bencode(headers)
1125
def _write_structure(self, args):
1126
self._write_func(b's')
1129
if isinstance(arg, str):
1130
utf8_args.append(arg.encode('utf8'))
1132
utf8_args.append(arg)
1133
self._write_prefixed_bencode(utf8_args)
1135
def _write_end(self):
1136
self._write_func(b'e')
1139
def _write_prefixed_body(self, bytes):
1140
self._write_func(b'b')
1141
self._write_func(struct.pack('!L', len(bytes)))
1142
self._write_func(bytes)
1144
def _write_chunked_body_start(self):
1145
self._write_func(b'oC')
1147
def _write_error_status(self):
1148
self._write_func(b'oE')
1150
def _write_success_status(self):
1151
self._write_func(b'oS')
1154
class ProtocolThreeResponder(_ProtocolThreeEncoder):
1156
def __init__(self, write_func):
1157
_ProtocolThreeEncoder.__init__(self, write_func)
1158
self.response_sent = False
1160
b'Software version': breezy.__version__.encode('utf-8')}
1161
if 'hpss' in debug.debug_flags:
1162
self._thread_id = _thread.get_ident()
1163
self._response_start_time = None
1165
def _trace(self, action, message, extra_bytes=None, include_time=False):
1166
if self._response_start_time is None:
1167
self._response_start_time = osutils.perf_counter()
1169
t = '%5.3fs ' % (osutils.perf_counter() - self._response_start_time)
1172
if extra_bytes is None:
1175
extra = ' ' + repr(extra_bytes[:40])
1177
extra = extra[:29] + extra[-1] + '...'
1178
mutter('%12s: [%s] %s%s%s'
1179
% (action, self._thread_id, t, message, extra))
1181
def send_error(self, exception):
1182
if self.response_sent:
1183
raise AssertionError(
1184
"send_error(%s) called, but response already sent."
1186
if isinstance(exception, errors.UnknownSmartMethod):
1187
failure = request.FailedSmartServerResponse(
1188
(b'UnknownMethod', exception.verb))
1189
self.send_response(failure)
1191
if 'hpss' in debug.debug_flags:
1192
self._trace('error', str(exception))
1193
self.response_sent = True
1194
self._write_protocol_version()
1195
self._write_headers(self._headers)
1196
self._write_error_status()
1197
self._write_structure(
1198
(b'error', str(exception).encode('utf-8', 'replace')))
1201
def send_response(self, response):
1202
if self.response_sent:
1203
raise AssertionError(
1204
"send_response(%r) called, but response already sent."
1206
self.response_sent = True
1207
self._write_protocol_version()
1208
self._write_headers(self._headers)
1209
if response.is_successful():
1210
self._write_success_status()
1212
self._write_error_status()
1213
if 'hpss' in debug.debug_flags:
1214
self._trace('response', repr(response.args))
1215
self._write_structure(response.args)
1216
if response.body is not None:
1217
self._write_prefixed_body(response.body)
1218
if 'hpss' in debug.debug_flags:
1219
self._trace('body', '%d bytes' % (len(response.body),),
1220
response.body, include_time=True)
1221
elif response.body_stream is not None:
1222
count = num_bytes = 0
1224
for exc_info, chunk in _iter_with_errors(response.body_stream):
1226
if exc_info is not None:
1227
self._write_error_status()
1228
error_struct = request._translate_error(exc_info[1])
1229
self._write_structure(error_struct)
1232
if isinstance(chunk, request.FailedSmartServerResponse):
1233
self._write_error_status()
1234
self._write_structure(chunk.args)
1236
num_bytes += len(chunk)
1237
if first_chunk is None:
1239
self._write_prefixed_body(chunk)
1241
if 'hpssdetail' in debug.debug_flags:
1242
# Not worth timing separately, as _write_func is
1244
self._trace('body chunk',
1245
'%d bytes' % (len(chunk),),
1246
chunk, suppress_time=True)
1247
if 'hpss' in debug.debug_flags:
1248
self._trace('body stream',
1249
'%d bytes %d chunks' % (num_bytes, count),
1252
if 'hpss' in debug.debug_flags:
1253
self._trace('response end', '', include_time=True)
1256
def _iter_with_errors(iterable):
1257
"""Handle errors from iterable.next().
1261
for exc_info, value in _iter_with_errors(iterable):
1264
This is a safer alternative to::
1267
for value in iterable:
1272
Because the latter will catch errors from the for-loop body, not just
1275
If an error occurs, exc_info will be a exc_info tuple, and the generator
1276
will terminate. Otherwise exc_info will be None, and value will be the
1277
value from iterable.next(). Note that KeyboardInterrupt and SystemExit
1278
will not be itercepted.
1280
iterator = iter(iterable)
1283
yield None, next(iterator)
1284
except StopIteration:
1286
except (KeyboardInterrupt, SystemExit):
1289
mutter('_iter_with_errors caught error')
1290
log_exception_quietly()
1291
yield sys.exc_info(), None
1295
class ProtocolThreeRequester(_ProtocolThreeEncoder, Requester):
1297
def __init__(self, medium_request):
1298
_ProtocolThreeEncoder.__init__(self, medium_request.accept_bytes)
1299
self._medium_request = medium_request
1301
self.body_stream_started = None
1303
def set_headers(self, headers):
1304
self._headers = headers.copy()
1306
def call(self, *args):
1307
if 'hpss' in debug.debug_flags:
1308
mutter('hpss call: %s', repr(args)[1:-1])
1309
base = getattr(self._medium_request._medium, 'base', None)
1310
if base is not None:
1311
mutter(' (to %s)', base)
1312
self._request_start_time = osutils.perf_counter()
1313
self._write_protocol_version()
1314
self._write_headers(self._headers)
1315
self._write_structure(args)
1317
self._medium_request.finished_writing()
1319
def call_with_body_bytes(self, args, body):
1320
"""Make a remote call of args with body bytes 'body'.
1322
After calling this, call read_response_tuple to find the result out.
1324
if 'hpss' in debug.debug_flags:
1325
mutter('hpss call w/body: %s (%r...)', repr(args)[1:-1], body[:20])
1326
path = getattr(self._medium_request._medium, '_path', None)
1327
if path is not None:
1328
mutter(' (to %s)', path)
1329
mutter(' %d bytes', len(body))
1330
self._request_start_time = osutils.perf_counter()
1331
self._write_protocol_version()
1332
self._write_headers(self._headers)
1333
self._write_structure(args)
1334
self._write_prefixed_body(body)
1336
self._medium_request.finished_writing()
1338
def call_with_body_readv_array(self, args, body):
1339
"""Make a remote call with a readv array.
1341
The body is encoded with one line per readv offset pair. The numbers in
1342
each pair are separated by a comma, and no trailing \\n is emitted.
1344
if 'hpss' in debug.debug_flags:
1345
mutter('hpss call w/readv: %s', repr(args)[1:-1])
1346
path = getattr(self._medium_request._medium, '_path', None)
1347
if path is not None:
1348
mutter(' (to %s)', path)
1349
self._request_start_time = osutils.perf_counter()
1350
self._write_protocol_version()
1351
self._write_headers(self._headers)
1352
self._write_structure(args)
1353
readv_bytes = self._serialise_offsets(body)
1354
if 'hpss' in debug.debug_flags:
1355
mutter(' %d bytes in readv request', len(readv_bytes))
1356
self._write_prefixed_body(readv_bytes)
1358
self._medium_request.finished_writing()
1360
def call_with_body_stream(self, args, stream):
1361
if 'hpss' in debug.debug_flags:
1362
mutter('hpss call w/body stream: %r', args)
1363
path = getattr(self._medium_request._medium, '_path', None)
1364
if path is not None:
1365
mutter(' (to %s)', path)
1366
self._request_start_time = osutils.perf_counter()
1367
self.body_stream_started = False
1368
self._write_protocol_version()
1369
self._write_headers(self._headers)
1370
self._write_structure(args)
1371
# TODO: notice if the server has sent an early error reply before we
1372
# have finished sending the stream. We would notice at the end
1373
# anyway, but if the medium can deliver it early then it's good
1374
# to short-circuit the whole request...
1375
# Provoke any ConnectionReset failures before we start the body stream.
1377
self.body_stream_started = True
1378
for exc_info, part in _iter_with_errors(stream):
1379
if exc_info is not None:
1380
# Iterating the stream failed. Cleanly abort the request.
1381
self._write_error_status()
1382
# Currently the client unconditionally sends ('error',) as the
1384
self._write_structure((b'error',))
1386
self._medium_request.finished_writing()
1387
(exc_type, exc_val, exc_tb) = exc_info
1393
self._write_prefixed_body(part)
1396
self._medium_request.finished_writing()