1
# Copyright (C) 2006 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
"""The 'medium' layer for the smart servers and clients.
19
"Medium" here is the noun meaning "a means of transmission", not the adjective
20
for "the quality between big and small."
22
Media carry the bytes of the requests somehow (e.g. via TCP, wrapped in HTTP, or
23
over SSH), and pass them to and from the protocol logic. See the overview in
24
bzrlib/transport/smart/__init__.py.
33
from bzrlib.lazy_import import lazy_import
34
lazy_import(globals(), """
42
from bzrlib.smart import client, protocol
43
from bzrlib.transport import ssh
47
# We must not read any more than 64k at a time so we don't risk "no buffer
48
# space available" errors on some platforms. Windows in particular is likely
49
# to give error 10053 or 10055 if we read more than 64k from a socket.
50
_MAX_READ_SIZE = 64 * 1024
53
def _get_protocol_factory_for_bytes(bytes):
54
"""Determine the right protocol factory for 'bytes'.
56
This will return an appropriate protocol factory depending on the version
57
of the protocol being used, as determined by inspecting the given bytes.
58
The bytes should have at least one newline byte (i.e. be a whole line),
59
otherwise it's possible that a request will be incorrectly identified as
62
Typical use would be::
64
factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
65
server_protocol = factory(transport, write_func, root_client_path)
66
server_protocol.accept_bytes(unused_bytes)
68
:param bytes: a str of bytes of the start of the request.
69
:returns: 2-tuple of (protocol_factory, unused_bytes). protocol_factory is
70
a callable that takes three args: transport, write_func,
71
root_client_path. unused_bytes are any bytes that were not part of a
72
protocol version marker.
74
if bytes.startswith(protocol.MESSAGE_VERSION_THREE):
75
protocol_factory = protocol.build_server_protocol_three
76
bytes = bytes[len(protocol.MESSAGE_VERSION_THREE):]
77
elif bytes.startswith(protocol.REQUEST_VERSION_TWO):
78
protocol_factory = protocol.SmartServerRequestProtocolTwo
79
bytes = bytes[len(protocol.REQUEST_VERSION_TWO):]
81
protocol_factory = protocol.SmartServerRequestProtocolOne
82
return protocol_factory, bytes
85
def _get_line(read_bytes_func):
86
"""Read bytes using read_bytes_func until a newline byte.
88
This isn't particularly efficient, so should only be used when the
89
expected size of the line is quite short.
91
:returns: a tuple of two strs: (line, excess)
95
while newline_pos == -1:
96
new_bytes = read_bytes_func(1)
99
# Ran out of bytes before receiving a complete line.
101
newline_pos = bytes.find('\n')
102
line = bytes[:newline_pos+1]
103
excess = bytes[newline_pos+1:]
107
class SmartMedium(object):
108
"""Base class for smart protocol media, both client- and server-side."""
111
self._push_back_buffer = None
113
def _push_back(self, bytes):
114
"""Return unused bytes to the medium, because they belong to the next
117
This sets the _push_back_buffer to the given bytes.
119
if self._push_back_buffer is not None:
120
raise AssertionError(
121
"_push_back called when self._push_back_buffer is %r"
122
% (self._push_back_buffer,))
125
self._push_back_buffer = bytes
127
def _get_push_back_buffer(self):
128
if self._push_back_buffer == '':
129
raise AssertionError(
130
'%s._push_back_buffer should never be the empty string, '
131
'which can be confused with EOF' % (self,))
132
bytes = self._push_back_buffer
133
self._push_back_buffer = None
136
def read_bytes(self, desired_count):
137
"""Read some bytes from this medium.
139
:returns: some bytes, possibly more or less than the number requested
140
in 'desired_count' depending on the medium.
142
if self._push_back_buffer is not None:
143
return self._get_push_back_buffer()
144
bytes_to_read = min(desired_count, _MAX_READ_SIZE)
145
return self._read_bytes(bytes_to_read)
147
def _read_bytes(self, count):
148
raise NotImplementedError(self._read_bytes)
151
"""Read bytes from this request's response until a newline byte.
153
This isn't particularly efficient, so should only be used when the
154
expected size of the line is quite short.
156
:returns: a string of bytes ending in a newline (byte 0x0A).
158
line, excess = _get_line(self.read_bytes)
159
self._push_back(excess)
163
class SmartServerStreamMedium(SmartMedium):
164
"""Handles smart commands coming over a stream.
166
The stream may be a pipe connected to sshd, or a tcp socket, or an
167
in-process fifo for testing.
169
One instance is created for each connected client; it can serve multiple
170
requests in the lifetime of the connection.
172
The server passes requests through to an underlying backing transport,
173
which will typically be a LocalTransport looking at the server's filesystem.
175
:ivar _push_back_buffer: a str of bytes that have been read from the stream
176
but not used yet, or None if there are no buffered bytes. Subclasses
177
should make sure to exhaust this buffer before reading more bytes from
178
the stream. See also the _push_back method.
181
def __init__(self, backing_transport, root_client_path='/'):
182
"""Construct new server.
184
:param backing_transport: Transport for the directory served.
186
# backing_transport could be passed to serve instead of __init__
187
self.backing_transport = backing_transport
188
self.root_client_path = root_client_path
189
self.finished = False
190
SmartMedium.__init__(self)
193
"""Serve requests until the client disconnects."""
194
# Keep a reference to stderr because the sys module's globals get set to
195
# None during interpreter shutdown.
196
from sys import stderr
198
while not self.finished:
199
server_protocol = self._build_protocol()
200
self._serve_one_request(server_protocol)
202
stderr.write("%s terminating on exception %s\n" % (self, e))
205
def _build_protocol(self):
206
"""Identifies the version of the incoming request, and returns an
207
a protocol object that can interpret it.
209
If more bytes than the version prefix of the request are read, they will
210
be fed into the protocol before it is returned.
212
:returns: a SmartServerRequestProtocol.
214
bytes = self._get_line()
215
protocol_factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
216
protocol = protocol_factory(
217
self.backing_transport, self._write_out, self.root_client_path)
218
protocol.accept_bytes(unused_bytes)
221
def _serve_one_request(self, protocol):
222
"""Read one request from input, process, send back a response.
224
:param protocol: a SmartServerRequestProtocol.
227
self._serve_one_request_unguarded(protocol)
228
except KeyboardInterrupt:
231
self.terminate_due_to_error()
233
def terminate_due_to_error(self):
234
"""Called when an unhandled exception from the protocol occurs."""
235
raise NotImplementedError(self.terminate_due_to_error)
237
def _read_bytes(self, desired_count):
238
"""Get some bytes from the medium.
240
:param desired_count: number of bytes we want to read.
242
raise NotImplementedError(self._read_bytes)
245
class SmartServerSocketStreamMedium(SmartServerStreamMedium):
247
def __init__(self, sock, backing_transport, root_client_path='/'):
250
:param sock: the socket the server will read from. It will be put
253
SmartServerStreamMedium.__init__(
254
self, backing_transport, root_client_path=root_client_path)
255
sock.setblocking(True)
258
def _serve_one_request_unguarded(self, protocol):
259
while protocol.next_read_size():
260
# We can safely try to read large chunks. If there is less data
261
# than _MAX_READ_SIZE ready, the socket wil just return a short
262
# read immediately rather than block.
263
bytes = self.read_bytes(_MAX_READ_SIZE)
267
protocol.accept_bytes(bytes)
269
self._push_back(protocol.unused_data)
271
def _read_bytes(self, desired_count):
272
# We ignore the desired_count because on sockets it's more efficient to
273
# read large chunks (of _MAX_READ_SIZE bytes) at a time.
274
return self.socket.recv(_MAX_READ_SIZE)
276
def terminate_due_to_error(self):
277
# TODO: This should log to a server log file, but no such thing
278
# exists yet. Andrew Bennetts 2006-09-29.
282
def _write_out(self, bytes):
283
osutils.send_all(self.socket, bytes)
286
class SmartServerPipeStreamMedium(SmartServerStreamMedium):
288
def __init__(self, in_file, out_file, backing_transport):
289
"""Construct new server.
291
:param in_file: Python file from which requests can be read.
292
:param out_file: Python file to write responses.
293
:param backing_transport: Transport for the directory served.
295
SmartServerStreamMedium.__init__(self, backing_transport)
296
if sys.platform == 'win32':
297
# force binary mode for files
299
for f in (in_file, out_file):
300
fileno = getattr(f, 'fileno', None)
302
msvcrt.setmode(fileno(), os.O_BINARY)
306
def _serve_one_request_unguarded(self, protocol):
308
# We need to be careful not to read past the end of the current
309
# request, or else the read from the pipe will block, so we use
310
# protocol.next_read_size().
311
bytes_to_read = protocol.next_read_size()
312
if bytes_to_read == 0:
313
# Finished serving this request.
316
bytes = self.read_bytes(bytes_to_read)
318
# Connection has been closed.
322
protocol.accept_bytes(bytes)
324
def _read_bytes(self, desired_count):
325
return self._in.read(desired_count)
327
def terminate_due_to_error(self):
328
# TODO: This should log to a server log file, but no such thing
329
# exists yet. Andrew Bennetts 2006-09-29.
333
def _write_out(self, bytes):
334
self._out.write(bytes)
337
class SmartClientMediumRequest(object):
338
"""A request on a SmartClientMedium.
340
Each request allows bytes to be provided to it via accept_bytes, and then
341
the response bytes to be read via read_bytes.
344
request.accept_bytes('123')
345
request.finished_writing()
346
result = request.read_bytes(3)
347
request.finished_reading()
349
It is up to the individual SmartClientMedium whether multiple concurrent
350
requests can exist. See SmartClientMedium.get_request to obtain instances
351
of SmartClientMediumRequest, and the concrete Medium you are using for
352
details on concurrency and pipelining.
355
def __init__(self, medium):
356
"""Construct a SmartClientMediumRequest for the medium medium."""
357
self._medium = medium
358
# we track state by constants - we may want to use the same
359
# pattern as BodyReader if it gets more complex.
360
# valid states are: "writing", "reading", "done"
361
self._state = "writing"
363
def accept_bytes(self, bytes):
364
"""Accept bytes for inclusion in this request.
366
This method may not be be called after finished_writing() has been
367
called. It depends upon the Medium whether or not the bytes will be
368
immediately transmitted. Message based Mediums will tend to buffer the
369
bytes until finished_writing() is called.
371
:param bytes: A bytestring.
373
if self._state != "writing":
374
raise errors.WritingCompleted(self)
375
self._accept_bytes(bytes)
377
def _accept_bytes(self, bytes):
378
"""Helper for accept_bytes.
380
Accept_bytes checks the state of the request to determing if bytes
381
should be accepted. After that it hands off to _accept_bytes to do the
384
raise NotImplementedError(self._accept_bytes)
386
def finished_reading(self):
387
"""Inform the request that all desired data has been read.
389
This will remove the request from the pipeline for its medium (if the
390
medium supports pipelining) and any further calls to methods on the
391
request will raise ReadingCompleted.
393
if self._state == "writing":
394
raise errors.WritingNotComplete(self)
395
if self._state != "reading":
396
raise errors.ReadingCompleted(self)
398
self._finished_reading()
400
def _finished_reading(self):
401
"""Helper for finished_reading.
403
finished_reading checks the state of the request to determine if
404
finished_reading is allowed, and if it is hands off to _finished_reading
405
to perform the action.
407
raise NotImplementedError(self._finished_reading)
409
def finished_writing(self):
410
"""Finish the writing phase of this request.
412
This will flush all pending data for this request along the medium.
413
After calling finished_writing, you may not call accept_bytes anymore.
415
if self._state != "writing":
416
raise errors.WritingCompleted(self)
417
self._state = "reading"
418
self._finished_writing()
420
def _finished_writing(self):
421
"""Helper for finished_writing.
423
finished_writing checks the state of the request to determine if
424
finished_writing is allowed, and if it is hands off to _finished_writing
425
to perform the action.
427
raise NotImplementedError(self._finished_writing)
429
def read_bytes(self, count):
430
"""Read bytes from this requests response.
432
This method will block and wait for count bytes to be read. It may not
433
be invoked until finished_writing() has been called - this is to ensure
434
a message-based approach to requests, for compatibility with message
435
based mediums like HTTP.
437
if self._state == "writing":
438
raise errors.WritingNotComplete(self)
439
if self._state != "reading":
440
raise errors.ReadingCompleted(self)
441
return self._read_bytes(count)
443
def _read_bytes(self, count):
444
"""Helper for SmartClientMediumRequest.read_bytes.
446
read_bytes checks the state of the request to determing if bytes
447
should be read. After that it hands off to _read_bytes to do the
450
By default this forwards to self._medium.read_bytes because we are
451
operating on the medium's stream.
453
return self._medium.read_bytes(count)
456
line = self._read_line()
457
if not line.endswith('\n'):
458
# end of file encountered reading from server
459
raise errors.ConnectionReset(
460
"please check connectivity and permissions",
461
"(and try -Dhpss if further diagnosis is required)")
464
def _read_line(self):
465
"""Helper for SmartClientMediumRequest.read_line.
467
By default this forwards to self._medium._get_line because we are
468
operating on the medium's stream.
470
return self._medium._get_line()
473
_atexit_registered = False
476
class _HPSSCallCounter(object):
477
"""An object that counts the HPSS calls made to a particular medium.
479
When the medium is garbage-collected, or failing that when atexit functions
480
are run, the total number of calls made on that medium are reported to
483
It only keeps a weakref to the medium, so shouldn't affect the medium's
487
def __init__(self, medium):
490
self.medium_ref = weakref.ref(medium, self.done)
491
self.medium_repr = repr(medium)
492
# Register an atexit handler if one hasn't already been registered.
493
# Usually the weakref callback is enough, but quite often if the
494
# program aborts with an exception the medium doesn't get
495
# garbage-collected, presumably because one of the traceback frames
496
# still references it.
497
global _atexit_registered, _atexit_counters
498
if not _atexit_registered:
500
_atexit_counters = []
501
def finish_counters():
502
for counter in _atexit_counters:
504
atexit.register(finish_counters)
505
_atexit_registered = True
506
_atexit_counters.append(self)
508
def increment(self, params):
509
"""Install this method as a _SmartClient.hooks['call'] hook."""
510
if params.medium is self.medium_ref():
514
"""This method is called when the medium is done."""
520
print >> sys.stderr, 'HPSS calls: %d (%s)' % (
521
self.count, self.medium_repr)
522
_atexit_counters.remove(self)
525
class SmartClientMedium(SmartMedium):
526
"""Smart client is a medium for sending smart protocol requests over."""
528
def __init__(self, base):
529
super(SmartClientMedium, self).__init__()
531
self._protocol_version_error = None
532
self._protocol_version = None
533
self._done_hello = False
534
# Be optimistic: we assume the remote end can accept new remote
535
# requests until we get an error saying otherwise.
536
# _remote_version_is_before tracks the bzr version the remote side
537
# can be based on what we've seen so far.
538
self._remote_version_is_before = None
539
if 'hpss' in debug.debug_flags:
540
counter = _HPSSCallCounter(self)
541
client._SmartClient.hooks.install_named_hook('call',
542
counter.increment, 'hpss debug')
544
def _is_remote_before(self, version_tuple):
545
"""Is it possible the remote side supports RPCs for a given version?
549
needed_version = (1, 2)
550
if medium._is_remote_before(needed_version):
551
fallback_to_pre_1_2_rpc()
555
except UnknownSmartMethod:
556
medium._remember_remote_is_before(needed_version)
557
fallback_to_pre_1_2_rpc()
559
:seealso: _remember_remote_is_before
561
if self._remote_version_is_before is None:
562
# So far, the remote side seems to support everything
564
return version_tuple >= self._remote_version_is_before
566
def _remember_remote_is_before(self, version_tuple):
567
"""Tell this medium that the remote side is older the given version.
569
:seealso: _is_remote_before
571
if (self._remote_version_is_before is not None and
572
version_tuple > self._remote_version_is_before):
573
raise AssertionError(
574
"_remember_remote_is_before(%r) called, but "
575
"_remember_remote_is_before(%r) was called previously."
576
% (version_tuple, self._remote_version_is_before))
577
self._remote_version_is_before = version_tuple
579
def protocol_version(self):
580
"""Find out if 'hello' smart request works."""
581
if self._protocol_version_error is not None:
582
raise self._protocol_version_error
583
if not self._done_hello:
585
medium_request = self.get_request()
586
# Send a 'hello' request in protocol version one, for maximum
587
# backwards compatibility.
588
client_protocol = protocol.SmartClientRequestProtocolOne(medium_request)
589
client_protocol.query_version()
590
self._done_hello = True
591
except errors.SmartProtocolError, e:
592
# Cache the error, just like we would cache a successful
594
self._protocol_version_error = e
598
def should_probe(self):
599
"""Should RemoteBzrDirFormat.probe_transport send a smart request on
602
Some transports are unambiguously smart-only; there's no need to check
603
if the transport is able to carry smart requests, because that's all
604
it is for. In those cases, this method should return False.
606
But some HTTP transports can sometimes fail to carry smart requests,
607
but still be usuable for accessing remote bzrdirs via plain file
608
accesses. So for those transports, their media should return True here
609
so that RemoteBzrDirFormat can determine if it is appropriate for that
614
def disconnect(self):
615
"""If this medium maintains a persistent connection, close it.
617
The default implementation does nothing.
620
def remote_path_from_transport(self, transport):
621
"""Convert transport into a path suitable for using in a request.
623
Note that the resulting remote path doesn't encode the host name or
624
anything but path, so it is only safe to use it in requests sent over
625
the medium from the matching transport.
627
medium_base = urlutils.join(self.base, '/')
628
rel_url = urlutils.relative_url(medium_base, transport.base)
629
return urllib.unquote(rel_url)
632
class SmartClientStreamMedium(SmartClientMedium):
633
"""Stream based medium common class.
635
SmartClientStreamMediums operate on a stream. All subclasses use a common
636
SmartClientStreamMediumRequest for their requests, and should implement
637
_accept_bytes and _read_bytes to allow the request objects to send and
641
def __init__(self, base):
642
SmartClientMedium.__init__(self, base)
643
self._current_request = None
645
def accept_bytes(self, bytes):
646
self._accept_bytes(bytes)
649
"""The SmartClientStreamMedium knows how to close the stream when it is
655
"""Flush the output stream.
657
This method is used by the SmartClientStreamMediumRequest to ensure that
658
all data for a request is sent, to avoid long timeouts or deadlocks.
660
raise NotImplementedError(self._flush)
662
def get_request(self):
663
"""See SmartClientMedium.get_request().
665
SmartClientStreamMedium always returns a SmartClientStreamMediumRequest
668
return SmartClientStreamMediumRequest(self)
671
class SmartSimplePipesClientMedium(SmartClientStreamMedium):
672
"""A client medium using simple pipes.
674
This client does not manage the pipes: it assumes they will always be open.
677
def __init__(self, readable_pipe, writeable_pipe, base):
678
SmartClientStreamMedium.__init__(self, base)
679
self._readable_pipe = readable_pipe
680
self._writeable_pipe = writeable_pipe
682
def _accept_bytes(self, bytes):
683
"""See SmartClientStreamMedium.accept_bytes."""
684
self._writeable_pipe.write(bytes)
687
"""See SmartClientStreamMedium._flush()."""
688
self._writeable_pipe.flush()
690
def _read_bytes(self, count):
691
"""See SmartClientStreamMedium._read_bytes."""
692
return self._readable_pipe.read(count)
695
class SmartSSHClientMedium(SmartClientStreamMedium):
696
"""A client medium using SSH."""
698
def __init__(self, host, port=None, username=None, password=None,
699
base=None, vendor=None, bzr_remote_path=None):
700
"""Creates a client that will connect on the first use.
702
:param vendor: An optional override for the ssh vendor to use. See
703
bzrlib.transport.ssh for details on ssh vendors.
705
SmartClientStreamMedium.__init__(self, base)
706
self._connected = False
708
self._password = password
710
self._username = username
711
self._read_from = None
712
self._ssh_connection = None
713
self._vendor = vendor
714
self._write_to = None
715
self._bzr_remote_path = bzr_remote_path
716
if self._bzr_remote_path is None:
717
symbol_versioning.warn(
718
'bzr_remote_path is required as of bzr 0.92',
719
DeprecationWarning, stacklevel=2)
720
self._bzr_remote_path = os.environ.get('BZR_REMOTE_PATH', 'bzr')
722
def _accept_bytes(self, bytes):
723
"""See SmartClientStreamMedium.accept_bytes."""
724
self._ensure_connection()
725
self._write_to.write(bytes)
727
def disconnect(self):
728
"""See SmartClientMedium.disconnect()."""
729
if not self._connected:
731
self._read_from.close()
732
self._write_to.close()
733
self._ssh_connection.close()
734
self._connected = False
735
super(SmartSSHClientMedium, self).disconnect()
737
def _ensure_connection(self):
738
"""Connect this medium if not already connected."""
741
if self._vendor is None:
742
vendor = ssh._get_ssh_vendor()
744
vendor = self._vendor
745
self._ssh_connection = vendor.connect_ssh(self._username,
746
self._password, self._host, self._port,
747
command=[self._bzr_remote_path, 'serve', '--inet',
748
'--directory=/', '--allow-writes'])
749
self._read_from, self._write_to = \
750
self._ssh_connection.get_filelike_channels()
751
self._connected = True
754
"""See SmartClientStreamMedium._flush()."""
755
self._write_to.flush()
757
def _read_bytes(self, count):
758
"""See SmartClientStreamMedium.read_bytes."""
759
if not self._connected:
760
raise errors.MediumNotConnected(self)
761
bytes_to_read = min(count, _MAX_READ_SIZE)
762
return self._read_from.read(bytes_to_read)
765
# Port 4155 is the default port for bzr://, registered with IANA.
766
BZR_DEFAULT_INTERFACE = None
767
BZR_DEFAULT_PORT = 4155
770
class SmartTCPClientMedium(SmartClientStreamMedium):
771
"""A client medium using TCP."""
773
def __init__(self, host, port, base):
774
"""Creates a client that will connect on the first use."""
775
SmartClientStreamMedium.__init__(self, base)
776
self._connected = False
781
def _accept_bytes(self, bytes):
782
"""See SmartClientMedium.accept_bytes."""
783
self._ensure_connection()
784
osutils.send_all(self._socket, bytes)
786
def disconnect(self):
787
"""See SmartClientMedium.disconnect()."""
788
if not self._connected:
792
self._connected = False
793
super(SmartTCPClientMedium, self).disconnect()
795
def _ensure_connection(self):
796
"""Connect this medium if not already connected."""
799
if self._port is None:
800
port = BZR_DEFAULT_PORT
802
port = int(self._port)
804
sockaddrs = socket.getaddrinfo(self._host, port, socket.AF_UNSPEC,
805
socket.SOCK_STREAM, 0, 0)
806
except socket.gaierror, (err_num, err_msg):
807
raise errors.ConnectionError("failed to lookup %s:%d: %s" %
808
(self._host, port, err_msg))
809
# Initialize err in case there are no addresses returned:
810
err = socket.error("no address found for %s" % self._host)
811
for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
813
self._socket = socket.socket(family, socktype, proto)
814
self._socket.setsockopt(socket.IPPROTO_TCP,
815
socket.TCP_NODELAY, 1)
816
self._socket.connect(sockaddr)
817
except socket.error, err:
818
if self._socket is not None:
823
if self._socket is None:
824
# socket errors either have a (string) or (errno, string) as their
826
if type(err.args) is str:
829
err_msg = err.args[1]
830
raise errors.ConnectionError("failed to connect to %s:%d: %s" %
831
(self._host, port, err_msg))
832
self._connected = True
835
"""See SmartClientStreamMedium._flush().
837
For TCP we do no flushing. We may want to turn off TCP_NODELAY and
838
add a means to do a flush, but that can be done in the future.
841
def _read_bytes(self, count):
842
"""See SmartClientMedium.read_bytes."""
843
if not self._connected:
844
raise errors.MediumNotConnected(self)
845
# We ignore the desired_count because on sockets it's more efficient to
846
# read large chunks (of _MAX_READ_SIZE bytes) at a time.
847
return self._socket.recv(_MAX_READ_SIZE)
850
class SmartClientStreamMediumRequest(SmartClientMediumRequest):
851
"""A SmartClientMediumRequest that works with an SmartClientStreamMedium."""
853
def __init__(self, medium):
854
SmartClientMediumRequest.__init__(self, medium)
855
# check that we are safe concurrency wise. If some streams start
856
# allowing concurrent requests - i.e. via multiplexing - then this
857
# assert should be moved to SmartClientStreamMedium.get_request,
858
# and the setting/unsetting of _current_request likewise moved into
859
# that class : but its unneeded overhead for now. RBC 20060922
860
if self._medium._current_request is not None:
861
raise errors.TooManyConcurrentRequests(self._medium)
862
self._medium._current_request = self
864
def _accept_bytes(self, bytes):
865
"""See SmartClientMediumRequest._accept_bytes.
867
This forwards to self._medium._accept_bytes because we are operating
868
on the mediums stream.
870
self._medium._accept_bytes(bytes)
872
def _finished_reading(self):
873
"""See SmartClientMediumRequest._finished_reading.
875
This clears the _current_request on self._medium to allow a new
876
request to be created.
878
if self._medium._current_request is not self:
879
raise AssertionError()
880
self._medium._current_request = None
882
def _finished_writing(self):
883
"""See SmartClientMediumRequest._finished_writing.
885
This invokes self._medium._flush to ensure all bytes are transmitted.
887
self._medium._flush()