1
# Copyright (C) 2006, 2007 Canonical Ltd
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.
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.
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
17
"""Wire-level encoding and decoding of requests and responses for the smart
22
from cStringIO import StringIO
25
from bzrlib import debug
26
from bzrlib import errors
27
from bzrlib.smart import request
28
from bzrlib.trace import log_exception_quietly, mutter
31
# Protocol version strings. These are sent as prefixes of bzr requests and
32
# responses to identify the protocol version being used. (There are no version
33
# one strings because that version doesn't send any).
34
REQUEST_VERSION_TWO = 'bzr request 2\n'
35
RESPONSE_VERSION_TWO = 'bzr response 2\n'
38
def _recv_tuple(from_file):
39
req_line = from_file.readline()
40
return _decode_tuple(req_line)
43
def _decode_tuple(req_line):
44
if req_line == None or req_line == '':
46
if req_line[-1] != '\n':
47
raise errors.SmartProtocolError("request %r not terminated" % req_line)
48
return tuple(req_line[:-1].split('\x01'))
51
def _encode_tuple(args):
52
"""Encode the tuple args to a bytestream."""
53
return '\x01'.join(args) + '\n'
56
class SmartProtocolBase(object):
57
"""Methods common to client and server"""
59
# TODO: this only actually accomodates a single block; possibly should
60
# support multiple chunks?
61
def _encode_bulk_data(self, body):
62
"""Encode body as a bulk data chunk."""
63
return ''.join(('%d\n' % len(body), body, 'done\n'))
65
def _serialise_offsets(self, offsets):
66
"""Serialise a readv offset list."""
68
for start, length in offsets:
69
txt.append('%d,%d' % (start, length))
73
class SmartServerRequestProtocolOne(SmartProtocolBase):
74
"""Server-side encoding and decoding logic for smart version 1."""
76
def __init__(self, backing_transport, write_func, root_client_path='/'):
77
self._backing_transport = backing_transport
78
self._root_client_path = root_client_path
79
self.excess_buffer = ''
80
self._finished = False
82
self.has_dispatched = False
84
self._body_decoder = None
85
self._write_func = write_func
87
def accept_bytes(self, bytes):
88
"""Take bytes, and advance the internal state machine appropriately.
90
:param bytes: must be a byte string
92
assert isinstance(bytes, str)
93
self.in_buffer += bytes
94
if not self.has_dispatched:
95
if '\n' not in self.in_buffer:
98
self.has_dispatched = True
100
first_line, self.in_buffer = self.in_buffer.split('\n', 1)
102
req_args = _decode_tuple(first_line)
103
self.request = request.SmartServerRequestHandler(
104
self._backing_transport, commands=request.request_handlers,
105
root_client_path=self._root_client_path)
106
self.request.dispatch_command(req_args[0], req_args[1:])
107
if self.request.finished_reading:
109
self.excess_buffer = self.in_buffer
111
self._send_response(self.request.response)
112
except KeyboardInterrupt:
114
except Exception, exception:
115
# everything else: pass to client, flush, and quit
116
log_exception_quietly()
117
self._send_response(request.FailedSmartServerResponse(
118
('error', str(exception))))
121
if self.has_dispatched:
123
# nothing to do.XXX: this routine should be a single state
125
self.excess_buffer += self.in_buffer
128
if self._body_decoder is None:
129
self._body_decoder = LengthPrefixedBodyDecoder()
130
self._body_decoder.accept_bytes(self.in_buffer)
131
self.in_buffer = self._body_decoder.unused_data
132
body_data = self._body_decoder.read_pending_data()
133
self.request.accept_body(body_data)
134
if self._body_decoder.finished_reading:
135
self.request.end_of_body()
136
assert self.request.finished_reading, \
137
"no more body, request not finished"
138
if self.request.response is not None:
139
self._send_response(self.request.response)
140
self.excess_buffer = self.in_buffer
143
assert not self.request.finished_reading, \
144
"no response and we have finished reading."
146
def _send_response(self, response):
147
"""Send a smart server response down the output stream."""
148
assert not self._finished, 'response already sent'
151
self._finished = True
152
self._write_protocol_version()
153
self._write_success_or_failure_prefix(response)
154
self._write_func(_encode_tuple(args))
156
assert isinstance(body, str), 'body must be a str'
157
bytes = self._encode_bulk_data(body)
158
self._write_func(bytes)
160
def _write_protocol_version(self):
161
"""Write any prefixes this protocol requires.
163
Version one doesn't send protocol versions.
166
def _write_success_or_failure_prefix(self, response):
167
"""Write the protocol specific success/failure prefix.
169
For SmartServerRequestProtocolOne this is omitted but we
170
call is_successful to ensure that the response is valid.
172
response.is_successful()
174
def next_read_size(self):
177
if self._body_decoder is None:
180
return self._body_decoder.next_read_size()
183
class SmartServerRequestProtocolTwo(SmartServerRequestProtocolOne):
184
r"""Version two of the server side of the smart protocol.
186
This prefixes responses with the value of RESPONSE_VERSION_TWO.
189
def _write_success_or_failure_prefix(self, response):
190
"""Write the protocol specific success/failure prefix."""
191
if response.is_successful():
192
self._write_func('success\n')
194
self._write_func('failed\n')
196
def _write_protocol_version(self):
197
r"""Write any prefixes this protocol requires.
199
Version two sends the value of RESPONSE_VERSION_TWO.
201
self._write_func(RESPONSE_VERSION_TWO)
203
def _send_response(self, response):
204
"""Send a smart server response down the output stream."""
205
assert not self._finished, 'response already sent'
206
self._finished = True
207
self._write_protocol_version()
208
self._write_success_or_failure_prefix(response)
209
self._write_func(_encode_tuple(response.args))
210
if response.body is not None:
211
assert isinstance(response.body, str), 'body must be a str'
212
assert response.body_stream is None, (
213
'body_stream and body cannot both be set')
214
bytes = self._encode_bulk_data(response.body)
215
self._write_func(bytes)
216
elif response.body_stream is not None:
217
_send_stream(response.body_stream, self._write_func)
220
def _send_stream(stream, write_func):
221
write_func('chunked\n')
222
_send_chunks(stream, write_func)
226
def _send_chunks(stream, write_func):
228
if isinstance(chunk, str):
229
bytes = "%x\n%s" % (len(chunk), chunk)
231
elif isinstance(chunk, request.FailedSmartServerResponse):
233
_send_chunks(chunk.args, write_func)
236
raise errors.BzrError(
237
'Chunks must be str or FailedSmartServerResponse, got %r'
241
class _StatefulDecoder(object):
244
self.finished_reading = False
245
self.unused_data = ''
246
self.bytes_left = None
248
def accept_bytes(self, bytes):
249
"""Decode as much of bytes as possible.
251
If 'bytes' contains too much data it will be appended to
254
finished_reading will be set when no more data is required. Further
255
data will be appended to self.unused_data.
257
# accept_bytes is allowed to change the state
258
current_state = self.state_accept
259
self.state_accept(bytes)
260
while current_state != self.state_accept:
261
current_state = self.state_accept
262
self.state_accept('')
265
class ChunkedBodyDecoder(_StatefulDecoder):
266
"""Decoder for chunked body data.
268
This is very similar the HTTP's chunked encoding. See the description of
269
streamed body data in `doc/developers/network-protocol.txt` for details.
273
_StatefulDecoder.__init__(self)
274
self.state_accept = self._state_accept_expecting_header
276
self.chunk_in_progress = None
277
self.chunks = collections.deque()
279
self.error_in_progress = None
281
def next_read_size(self):
282
# Note: the shortest possible chunk is 2 bytes: '0\n', and the
283
# end-of-body marker is 4 bytes: 'END\n'.
284
if self.state_accept == self._state_accept_reading_chunk:
285
# We're expecting more chunk content. So we're expecting at least
286
# the rest of this chunk plus an END chunk.
287
return self.bytes_left + 4
288
elif self.state_accept == self._state_accept_expecting_length:
289
if self._in_buffer == '':
290
# We're expecting a chunk length. There's at least two bytes
291
# left: a digit plus '\n'.
294
# We're in the middle of reading a chunk length. So there's at
295
# least one byte left, the '\n' that terminates the length.
297
elif self.state_accept == self._state_accept_reading_unused:
299
elif self.state_accept == self._state_accept_expecting_header:
300
return max(0, len('chunked\n') - len(self._in_buffer))
302
raise AssertionError("Impossible state: %r" % (self.state_accept,))
304
def read_next_chunk(self):
306
return self.chunks.popleft()
310
def _extract_line(self):
311
pos = self._in_buffer.find('\n')
313
# We haven't read a complete length prefix yet, so there's nothing
316
line = self._in_buffer[:pos]
317
# Trim the prefix (including '\n' delimiter) from the _in_buffer.
318
self._in_buffer = self._in_buffer[pos+1:]
322
self.unused_data = self._in_buffer
323
self._in_buffer = None
324
self.state_accept = self._state_accept_reading_unused
326
error_args = tuple(self.error_in_progress)
327
self.chunks.append(request.FailedSmartServerResponse(error_args))
328
self.error_in_progress = None
329
self.finished_reading = True
331
def _state_accept_expecting_header(self, bytes):
332
self._in_buffer += bytes
333
prefix = self._extract_line()
335
# We haven't read a complete length prefix yet, so there's nothing
338
elif prefix == 'chunked':
339
self.state_accept = self._state_accept_expecting_length
341
raise errors.SmartProtocolError(
342
'Bad chunked body header: "%s"' % (prefix,))
344
def _state_accept_expecting_length(self, bytes):
345
self._in_buffer += bytes
346
prefix = self._extract_line()
348
# We haven't read a complete length prefix yet, so there's nothing
351
elif prefix == 'ERR':
353
self.error_in_progress = []
354
self._state_accept_expecting_length('')
356
elif prefix == 'END':
357
# We've read the end-of-body marker.
358
# Any further bytes are unused data, including the bytes left in
363
self.bytes_left = int(prefix, 16)
364
self.chunk_in_progress = ''
365
self.state_accept = self._state_accept_reading_chunk
367
def _state_accept_reading_chunk(self, bytes):
368
self._in_buffer += bytes
369
in_buffer_len = len(self._in_buffer)
370
self.chunk_in_progress += self._in_buffer[:self.bytes_left]
371
self._in_buffer = self._in_buffer[self.bytes_left:]
372
self.bytes_left -= in_buffer_len
373
if self.bytes_left <= 0:
374
# Finished with chunk
375
self.bytes_left = None
377
self.error_in_progress.append(self.chunk_in_progress)
379
self.chunks.append(self.chunk_in_progress)
380
self.chunk_in_progress = None
381
self.state_accept = self._state_accept_expecting_length
383
def _state_accept_reading_unused(self, bytes):
384
self.unused_data += bytes
387
class LengthPrefixedBodyDecoder(_StatefulDecoder):
388
"""Decodes the length-prefixed bulk data."""
391
_StatefulDecoder.__init__(self)
392
self.state_accept = self._state_accept_expecting_length
393
self.state_read = self._state_read_no_data
395
self._trailer_buffer = ''
397
def next_read_size(self):
398
if self.bytes_left is not None:
399
# Ideally we want to read all the remainder of the body and the
401
return self.bytes_left + 5
402
elif self.state_accept == self._state_accept_reading_trailer:
403
# Just the trailer left
404
return 5 - len(self._trailer_buffer)
405
elif self.state_accept == self._state_accept_expecting_length:
406
# There's still at least 6 bytes left ('\n' to end the length, plus
410
# Reading excess data. Either way, 1 byte at a time is fine.
413
def read_pending_data(self):
414
"""Return any pending data that has been decoded."""
415
return self.state_read()
417
def _state_accept_expecting_length(self, bytes):
418
self._in_buffer += bytes
419
pos = self._in_buffer.find('\n')
422
self.bytes_left = int(self._in_buffer[:pos])
423
self._in_buffer = self._in_buffer[pos+1:]
424
self.bytes_left -= len(self._in_buffer)
425
self.state_accept = self._state_accept_reading_body
426
self.state_read = self._state_read_in_buffer
428
def _state_accept_reading_body(self, bytes):
429
self._in_buffer += bytes
430
self.bytes_left -= len(bytes)
431
if self.bytes_left <= 0:
433
if self.bytes_left != 0:
434
self._trailer_buffer = self._in_buffer[self.bytes_left:]
435
self._in_buffer = self._in_buffer[:self.bytes_left]
436
self.bytes_left = None
437
self.state_accept = self._state_accept_reading_trailer
439
def _state_accept_reading_trailer(self, bytes):
440
self._trailer_buffer += bytes
441
# TODO: what if the trailer does not match "done\n"? Should this raise
442
# a ProtocolViolation exception?
443
if self._trailer_buffer.startswith('done\n'):
444
self.unused_data = self._trailer_buffer[len('done\n'):]
445
self.state_accept = self._state_accept_reading_unused
446
self.finished_reading = True
448
def _state_accept_reading_unused(self, bytes):
449
self.unused_data += bytes
451
def _state_read_no_data(self):
454
def _state_read_in_buffer(self):
455
result = self._in_buffer
460
class SmartClientRequestProtocolOne(SmartProtocolBase):
461
"""The client-side protocol for smart version 1."""
463
def __init__(self, request):
464
"""Construct a SmartClientRequestProtocolOne.
466
:param request: A SmartClientMediumRequest to serialise onto and
469
self._request = request
470
self._body_buffer = None
471
self._request_start_time = None
473
def call(self, *args):
474
if 'hpss' in debug.debug_flags:
475
mutter('hpss call: %s', repr(args)[1:-1])
476
if getattr(self._request._medium, 'base', None) is not None:
477
mutter(' (to %s)', self._request._medium.base)
478
self._request_start_time = time.time()
479
self._write_args(args)
480
self._request.finished_writing()
482
def call_with_body_bytes(self, args, body):
483
"""Make a remote call of args with body bytes 'body'.
485
After calling this, call read_response_tuple to find the result out.
487
if 'hpss' in debug.debug_flags:
488
mutter('hpss call w/body: %s (%r...)', repr(args)[1:-1], body[:20])
489
if getattr(self._request._medium, '_path', None) is not None:
490
mutter(' (to %s)', self._request._medium._path)
491
mutter(' %d bytes', len(body))
492
self._request_start_time = time.time()
493
if 'hpssdetail' in debug.debug_flags:
494
mutter('hpss body content: %s', body)
495
self._write_args(args)
496
bytes = self._encode_bulk_data(body)
497
self._request.accept_bytes(bytes)
498
self._request.finished_writing()
500
def call_with_body_readv_array(self, args, body):
501
"""Make a remote call with a readv array.
503
The body is encoded with one line per readv offset pair. The numbers in
504
each pair are separated by a comma, and no trailing \n is emitted.
506
if 'hpss' in debug.debug_flags:
507
mutter('hpss call w/readv: %s', repr(args)[1:-1])
508
if getattr(self._request._medium, '_path', None) is not None:
509
mutter(' (to %s)', self._request._medium._path)
510
self._request_start_time = time.time()
511
self._write_args(args)
512
readv_bytes = self._serialise_offsets(body)
513
bytes = self._encode_bulk_data(readv_bytes)
514
self._request.accept_bytes(bytes)
515
self._request.finished_writing()
516
if 'hpss' in debug.debug_flags:
517
mutter(' %d bytes in readv request', len(readv_bytes))
519
def cancel_read_body(self):
520
"""After expecting a body, a response code may indicate one otherwise.
522
This method lets the domain client inform the protocol that no body
523
will be transmitted. This is a terminal method: after calling it the
524
protocol is not able to be used further.
526
self._request.finished_reading()
528
def read_response_tuple(self, expect_body=False):
529
"""Read a response tuple from the wire.
531
This should only be called once.
533
result = self._recv_tuple()
534
if 'hpss' in debug.debug_flags:
535
if self._request_start_time is not None:
536
mutter(' result: %6.3fs %s',
537
time.time() - self._request_start_time,
539
self._request_start_time = None
541
mutter(' result: %s', repr(result)[1:-1])
543
self._request.finished_reading()
546
def read_body_bytes(self, count=-1):
547
"""Read bytes from the body, decoding into a byte stream.
549
We read all bytes at once to ensure we've checked the trailer for
550
errors, and then feed the buffer back as read_body_bytes is called.
552
if self._body_buffer is not None:
553
return self._body_buffer.read(count)
554
_body_decoder = LengthPrefixedBodyDecoder()
556
# Read no more than 64k at a time so that we don't risk error 10055 (no
557
# buffer space available) on Windows.
559
while not _body_decoder.finished_reading:
560
bytes_wanted = min(_body_decoder.next_read_size(), max_read)
561
bytes = self._request.read_bytes(bytes_wanted)
562
_body_decoder.accept_bytes(bytes)
563
self._request.finished_reading()
564
self._body_buffer = StringIO(_body_decoder.read_pending_data())
565
# XXX: TODO check the trailer result.
566
if 'hpss' in debug.debug_flags:
567
mutter(' %d body bytes read',
568
len(self._body_buffer.getvalue()))
569
return self._body_buffer.read(count)
571
def _recv_tuple(self):
572
"""Receive a tuple from the medium request."""
573
return _decode_tuple(self._recv_line())
575
def _recv_line(self):
576
"""Read an entire line from the medium request."""
578
while not line or line[-1] != '\n':
579
# TODO: this is inefficient - but tuples are short.
580
new_char = self._request.read_bytes(1)
582
# end of file encountered reading from server
583
raise errors.ConnectionReset(
584
"please check connectivity and permissions",
585
"(and try -Dhpss if further diagnosis is required)")
589
def query_version(self):
590
"""Return protocol version number of the server."""
592
resp = self.read_response_tuple()
593
if resp == ('ok', '1'):
595
elif resp == ('ok', '2'):
598
raise errors.SmartProtocolError("bad response %r" % (resp,))
600
def _write_args(self, args):
601
self._write_protocol_version()
602
bytes = _encode_tuple(args)
603
self._request.accept_bytes(bytes)
605
def _write_protocol_version(self):
606
"""Write any prefixes this protocol requires.
608
Version one doesn't send protocol versions.
612
class SmartClientRequestProtocolTwo(SmartClientRequestProtocolOne):
613
"""Version two of the client side of the smart protocol.
615
This prefixes the request with the value of REQUEST_VERSION_TWO.
618
def read_response_tuple(self, expect_body=False):
619
"""Read a response tuple from the wire.
621
This should only be called once.
623
version = self._request.read_line()
624
if version != RESPONSE_VERSION_TWO:
625
raise errors.SmartProtocolError('bad protocol marker %r' % version)
626
response_status = self._recv_line()
627
if response_status not in ('success\n', 'failed\n'):
628
raise errors.SmartProtocolError(
629
'bad protocol status %r' % response_status)
630
self.response_status = response_status == 'success\n'
631
return SmartClientRequestProtocolOne.read_response_tuple(self, expect_body)
633
def _write_protocol_version(self):
634
"""Write any prefixes this protocol requires.
636
Version two sends the value of REQUEST_VERSION_TWO.
638
self._request.accept_bytes(REQUEST_VERSION_TWO)
640
def read_streamed_body(self):
641
"""Read bytes from the body, decoding into a byte stream.
643
# Read no more than 64k at a time so that we don't risk error 10055 (no
644
# buffer space available) on Windows.
646
_body_decoder = ChunkedBodyDecoder()
647
while not _body_decoder.finished_reading:
648
bytes_wanted = min(_body_decoder.next_read_size(), max_read)
649
bytes = self._request.read_bytes(bytes_wanted)
650
_body_decoder.accept_bytes(bytes)
651
for body_bytes in iter(_body_decoder.read_next_chunk, None):
652
if 'hpss' in debug.debug_flags:
653
mutter(' %d byte chunk read',
656
self._request.finished_reading()