1
# Copyright (C) 2006-2010 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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(), """
47
from bzrlib.smart import client, protocol, request, vfs
48
from bzrlib.transport import ssh
50
#usually already imported, and getting IllegalScoperReplacer on it here.
51
from bzrlib import osutils
53
# We must not read any more than 64k at a time so we don't risk "no buffer
54
# space available" errors on some platforms. Windows in particular is likely
55
# to throw WSAECONNABORTED or WSAENOBUFS if given too much data at once.
56
# Throughout this module buffer size parameters are either limited to be at
57
# most 64k, or are ignored and 64k is used instead.
58
_MAX_READ_SIZE = 64 * 1024
61
def _get_protocol_factory_for_bytes(bytes):
62
"""Determine the right protocol factory for 'bytes'.
64
This will return an appropriate protocol factory depending on the version
65
of the protocol being used, as determined by inspecting the given bytes.
66
The bytes should have at least one newline byte (i.e. be a whole line),
67
otherwise it's possible that a request will be incorrectly identified as
70
Typical use would be::
72
factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
73
server_protocol = factory(transport, write_func, root_client_path)
74
server_protocol.accept_bytes(unused_bytes)
76
:param bytes: a str of bytes of the start of the request.
77
:returns: 2-tuple of (protocol_factory, unused_bytes). protocol_factory is
78
a callable that takes three args: transport, write_func,
79
root_client_path. unused_bytes are any bytes that were not part of a
80
protocol version marker.
82
if bytes.startswith(protocol.MESSAGE_VERSION_THREE):
83
protocol_factory = protocol.build_server_protocol_three
84
bytes = bytes[len(protocol.MESSAGE_VERSION_THREE):]
85
elif bytes.startswith(protocol.REQUEST_VERSION_TWO):
86
protocol_factory = protocol.SmartServerRequestProtocolTwo
87
bytes = bytes[len(protocol.REQUEST_VERSION_TWO):]
89
protocol_factory = protocol.SmartServerRequestProtocolOne
90
return protocol_factory, bytes
93
def _get_line(read_bytes_func):
94
"""Read bytes using read_bytes_func until a newline byte.
96
This isn't particularly efficient, so should only be used when the
97
expected size of the line is quite short.
99
:returns: a tuple of two strs: (line, excess)
103
while newline_pos == -1:
104
new_bytes = read_bytes_func(1)
107
# Ran out of bytes before receiving a complete line.
109
newline_pos = bytes.find('\n')
110
line = bytes[:newline_pos+1]
111
excess = bytes[newline_pos+1:]
115
class SmartMedium(object):
116
"""Base class for smart protocol media, both client- and server-side."""
119
self._push_back_buffer = None
121
def _push_back(self, bytes):
122
"""Return unused bytes to the medium, because they belong to the next
125
This sets the _push_back_buffer to the given bytes.
127
if self._push_back_buffer is not None:
128
raise AssertionError(
129
"_push_back called when self._push_back_buffer is %r"
130
% (self._push_back_buffer,))
133
self._push_back_buffer = bytes
135
def _get_push_back_buffer(self):
136
if self._push_back_buffer == '':
137
raise AssertionError(
138
'%s._push_back_buffer should never be the empty string, '
139
'which can be confused with EOF' % (self,))
140
bytes = self._push_back_buffer
141
self._push_back_buffer = None
144
def read_bytes(self, desired_count):
145
"""Read some bytes from this medium.
147
:returns: some bytes, possibly more or less than the number requested
148
in 'desired_count' depending on the medium.
150
if self._push_back_buffer is not None:
151
return self._get_push_back_buffer()
152
bytes_to_read = min(desired_count, _MAX_READ_SIZE)
153
return self._read_bytes(bytes_to_read)
155
def _read_bytes(self, count):
156
raise NotImplementedError(self._read_bytes)
159
"""Read bytes from this request's response until a newline byte.
161
This isn't particularly efficient, so should only be used when the
162
expected size of the line is quite short.
164
:returns: a string of bytes ending in a newline (byte 0x0A).
166
line, excess = _get_line(self.read_bytes)
167
self._push_back(excess)
170
def _report_activity(self, bytes, direction):
171
"""Notify that this medium has activity.
173
Implementations should call this from all methods that actually do IO.
174
Be careful that it's not called twice, if one method is implemented on
177
:param bytes: Number of bytes read or written.
178
:param direction: 'read' or 'write' or None.
180
ui.ui_factory.report_transport_activity(self, bytes, direction)
183
class SmartServerStreamMedium(SmartMedium):
184
"""Handles smart commands coming over a stream.
186
The stream may be a pipe connected to sshd, or a tcp socket, or an
187
in-process fifo for testing.
189
One instance is created for each connected client; it can serve multiple
190
requests in the lifetime of the connection.
192
The server passes requests through to an underlying backing transport,
193
which will typically be a LocalTransport looking at the server's filesystem.
195
:ivar _push_back_buffer: a str of bytes that have been read from the stream
196
but not used yet, or None if there are no buffered bytes. Subclasses
197
should make sure to exhaust this buffer before reading more bytes from
198
the stream. See also the _push_back method.
201
def __init__(self, backing_transport, root_client_path='/'):
202
"""Construct new server.
204
:param backing_transport: Transport for the directory served.
206
# backing_transport could be passed to serve instead of __init__
207
self.backing_transport = backing_transport
208
self.root_client_path = root_client_path
209
self.finished = False
210
SmartMedium.__init__(self)
213
"""Serve requests until the client disconnects."""
214
# Keep a reference to stderr because the sys module's globals get set to
215
# None during interpreter shutdown.
216
from sys import stderr
218
while not self.finished:
219
server_protocol = self._build_protocol()
220
self._serve_one_request(server_protocol)
222
stderr.write("%s terminating on exception %s\n" % (self, e))
225
def _build_protocol(self):
226
"""Identifies the version of the incoming request, and returns an
227
a protocol object that can interpret it.
229
If more bytes than the version prefix of the request are read, they will
230
be fed into the protocol before it is returned.
232
:returns: a SmartServerRequestProtocol.
234
bytes = self._get_line()
235
protocol_factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
236
protocol = protocol_factory(
237
self.backing_transport, self._write_out, self.root_client_path)
238
protocol.accept_bytes(unused_bytes)
241
def _serve_one_request(self, protocol):
242
"""Read one request from input, process, send back a response.
244
:param protocol: a SmartServerRequestProtocol.
247
self._serve_one_request_unguarded(protocol)
248
except KeyboardInterrupt:
251
self.terminate_due_to_error()
253
def terminate_due_to_error(self):
254
"""Called when an unhandled exception from the protocol occurs."""
255
raise NotImplementedError(self.terminate_due_to_error)
257
def _read_bytes(self, desired_count):
258
"""Get some bytes from the medium.
260
:param desired_count: number of bytes we want to read.
262
raise NotImplementedError(self._read_bytes)
265
class SmartServerSocketStreamMedium(SmartServerStreamMedium):
267
def __init__(self, sock, backing_transport, root_client_path='/'):
270
:param sock: the socket the server will read from. It will be put
273
SmartServerStreamMedium.__init__(
274
self, backing_transport, root_client_path=root_client_path)
275
sock.setblocking(True)
278
def _serve_one_request_unguarded(self, protocol):
279
while protocol.next_read_size():
280
# We can safely try to read large chunks. If there is less data
281
# than _MAX_READ_SIZE ready, the socket wil just return a short
282
# read immediately rather than block.
283
bytes = self.read_bytes(_MAX_READ_SIZE)
287
protocol.accept_bytes(bytes)
289
self._push_back(protocol.unused_data)
291
def _read_bytes(self, desired_count):
292
return _read_bytes_from_socket(self.socket, self._report_activity)
294
def terminate_due_to_error(self):
295
# TODO: This should log to a server log file, but no such thing
296
# exists yet. Andrew Bennetts 2006-09-29.
300
def _write_out(self, bytes):
301
tstart = osutils.timer_func()
302
osutils.send_all(self.socket, bytes, self._report_activity)
303
if 'hpss' in debug.debug_flags:
304
thread_id = thread.get_ident()
305
trace.mutter('%12s: [%s] %d bytes to the socket in %.3fs'
306
% ('wrote', thread_id, len(bytes),
307
osutils.timer_func() - tstart))
310
class SmartServerPipeStreamMedium(SmartServerStreamMedium):
312
def __init__(self, in_file, out_file, backing_transport):
313
"""Construct new server.
315
:param in_file: Python file from which requests can be read.
316
:param out_file: Python file to write responses.
317
:param backing_transport: Transport for the directory served.
319
SmartServerStreamMedium.__init__(self, backing_transport)
320
if sys.platform == 'win32':
321
# force binary mode for files
323
for f in (in_file, out_file):
324
fileno = getattr(f, 'fileno', None)
326
msvcrt.setmode(fileno(), os.O_BINARY)
330
def _serve_one_request_unguarded(self, protocol):
332
# We need to be careful not to read past the end of the current
333
# request, or else the read from the pipe will block, so we use
334
# protocol.next_read_size().
335
bytes_to_read = protocol.next_read_size()
336
if bytes_to_read == 0:
337
# Finished serving this request.
340
bytes = self.read_bytes(bytes_to_read)
342
# Connection has been closed.
346
protocol.accept_bytes(bytes)
348
def _read_bytes(self, desired_count):
349
return self._in.read(desired_count)
351
def terminate_due_to_error(self):
352
# TODO: This should log to a server log file, but no such thing
353
# exists yet. Andrew Bennetts 2006-09-29.
357
def _write_out(self, bytes):
358
self._out.write(bytes)
361
class SmartClientMediumRequest(object):
362
"""A request on a SmartClientMedium.
364
Each request allows bytes to be provided to it via accept_bytes, and then
365
the response bytes to be read via read_bytes.
368
request.accept_bytes('123')
369
request.finished_writing()
370
result = request.read_bytes(3)
371
request.finished_reading()
373
It is up to the individual SmartClientMedium whether multiple concurrent
374
requests can exist. See SmartClientMedium.get_request to obtain instances
375
of SmartClientMediumRequest, and the concrete Medium you are using for
376
details on concurrency and pipelining.
379
def __init__(self, medium):
380
"""Construct a SmartClientMediumRequest for the medium medium."""
381
self._medium = medium
382
# we track state by constants - we may want to use the same
383
# pattern as BodyReader if it gets more complex.
384
# valid states are: "writing", "reading", "done"
385
self._state = "writing"
387
def accept_bytes(self, bytes):
388
"""Accept bytes for inclusion in this request.
390
This method may not be called after finished_writing() has been
391
called. It depends upon the Medium whether or not the bytes will be
392
immediately transmitted. Message based Mediums will tend to buffer the
393
bytes until finished_writing() is called.
395
:param bytes: A bytestring.
397
if self._state != "writing":
398
raise errors.WritingCompleted(self)
399
self._accept_bytes(bytes)
401
def _accept_bytes(self, bytes):
402
"""Helper for accept_bytes.
404
Accept_bytes checks the state of the request to determing if bytes
405
should be accepted. After that it hands off to _accept_bytes to do the
408
raise NotImplementedError(self._accept_bytes)
410
def finished_reading(self):
411
"""Inform the request that all desired data has been read.
413
This will remove the request from the pipeline for its medium (if the
414
medium supports pipelining) and any further calls to methods on the
415
request will raise ReadingCompleted.
417
if self._state == "writing":
418
raise errors.WritingNotComplete(self)
419
if self._state != "reading":
420
raise errors.ReadingCompleted(self)
422
self._finished_reading()
424
def _finished_reading(self):
425
"""Helper for finished_reading.
427
finished_reading checks the state of the request to determine if
428
finished_reading is allowed, and if it is hands off to _finished_reading
429
to perform the action.
431
raise NotImplementedError(self._finished_reading)
433
def finished_writing(self):
434
"""Finish the writing phase of this request.
436
This will flush all pending data for this request along the medium.
437
After calling finished_writing, you may not call accept_bytes anymore.
439
if self._state != "writing":
440
raise errors.WritingCompleted(self)
441
self._state = "reading"
442
self._finished_writing()
444
def _finished_writing(self):
445
"""Helper for finished_writing.
447
finished_writing checks the state of the request to determine if
448
finished_writing is allowed, and if it is hands off to _finished_writing
449
to perform the action.
451
raise NotImplementedError(self._finished_writing)
453
def read_bytes(self, count):
454
"""Read bytes from this requests response.
456
This method will block and wait for count bytes to be read. It may not
457
be invoked until finished_writing() has been called - this is to ensure
458
a message-based approach to requests, for compatibility with message
459
based mediums like HTTP.
461
if self._state == "writing":
462
raise errors.WritingNotComplete(self)
463
if self._state != "reading":
464
raise errors.ReadingCompleted(self)
465
return self._read_bytes(count)
467
def _read_bytes(self, count):
468
"""Helper for SmartClientMediumRequest.read_bytes.
470
read_bytes checks the state of the request to determing if bytes
471
should be read. After that it hands off to _read_bytes to do the
474
By default this forwards to self._medium.read_bytes because we are
475
operating on the medium's stream.
477
return self._medium.read_bytes(count)
480
line = self._read_line()
481
if not line.endswith('\n'):
482
# end of file encountered reading from server
483
raise errors.ConnectionReset(
484
"Unexpected end of message. Please check connectivity "
485
"and permissions, and report a bug if problems persist.")
488
def _read_line(self):
489
"""Helper for SmartClientMediumRequest.read_line.
491
By default this forwards to self._medium._get_line because we are
492
operating on the medium's stream.
494
return self._medium._get_line()
497
class _DebugCounter(object):
498
"""An object that counts the HPSS calls made to each client medium.
500
When a medium is garbage-collected, or failing that when atexit functions
501
are run, the total number of calls made on that medium are reported via
506
self.counts = weakref.WeakKeyDictionary()
507
client._SmartClient.hooks.install_named_hook(
508
'call', self.increment_call_count, 'hpss call counter')
509
atexit.register(self.flush_all)
511
def track(self, medium):
512
"""Start tracking calls made to a medium.
514
This only keeps a weakref to the medium, so shouldn't affect the
517
medium_repr = repr(medium)
518
# Add this medium to the WeakKeyDictionary
519
self.counts[medium] = dict(count=0, vfs_count=0,
520
medium_repr=medium_repr)
521
# Weakref callbacks are fired in reverse order of their association
522
# with the referenced object. So we add a weakref *after* adding to
523
# the WeakKeyDict so that we can report the value from it before the
524
# entry is removed by the WeakKeyDict's own callback.
525
ref = weakref.ref(medium, self.done)
527
def increment_call_count(self, params):
528
# Increment the count in the WeakKeyDictionary
529
value = self.counts[params.medium]
532
request_method = request.request_handlers.get(params.method)
534
# A method we don't know about doesn't count as a VFS method.
536
if issubclass(request_method, vfs.VfsRequest):
537
value['vfs_count'] += 1
540
value = self.counts[ref]
541
count, vfs_count, medium_repr = (
542
value['count'], value['vfs_count'], value['medium_repr'])
543
# In case this callback is invoked for the same ref twice (by the
544
# weakref callback and by the atexit function), set the call count back
545
# to 0 so this item won't be reported twice.
547
value['vfs_count'] = 0
549
trace.note('HPSS calls: %d (%d vfs) %s',
550
count, vfs_count, medium_repr)
553
for ref in list(self.counts.keys()):
556
_debug_counter = None
559
class SmartClientMedium(SmartMedium):
560
"""Smart client is a medium for sending smart protocol requests over."""
562
def __init__(self, base):
563
super(SmartClientMedium, self).__init__()
565
self._protocol_version_error = None
566
self._protocol_version = None
567
self._done_hello = False
568
# Be optimistic: we assume the remote end can accept new remote
569
# requests until we get an error saying otherwise.
570
# _remote_version_is_before tracks the bzr version the remote side
571
# can be based on what we've seen so far.
572
self._remote_version_is_before = None
573
# Install debug hook function if debug flag is set.
574
if 'hpss' in debug.debug_flags:
575
global _debug_counter
576
if _debug_counter is None:
577
_debug_counter = _DebugCounter()
578
_debug_counter.track(self)
580
def _is_remote_before(self, version_tuple):
581
"""Is it possible the remote side supports RPCs for a given version?
585
needed_version = (1, 2)
586
if medium._is_remote_before(needed_version):
587
fallback_to_pre_1_2_rpc()
591
except UnknownSmartMethod:
592
medium._remember_remote_is_before(needed_version)
593
fallback_to_pre_1_2_rpc()
595
:seealso: _remember_remote_is_before
597
if self._remote_version_is_before is None:
598
# So far, the remote side seems to support everything
600
return version_tuple >= self._remote_version_is_before
602
def _remember_remote_is_before(self, version_tuple):
603
"""Tell this medium that the remote side is older the given version.
605
:seealso: _is_remote_before
607
if (self._remote_version_is_before is not None and
608
version_tuple > self._remote_version_is_before):
609
# We have been told that the remote side is older than some version
610
# which is newer than a previously supplied older-than version.
611
# This indicates that some smart verb call is not guarded
612
# appropriately (it should simply not have been tried).
613
raise AssertionError(
614
"_remember_remote_is_before(%r) called, but "
615
"_remember_remote_is_before(%r) was called previously."
616
% (version_tuple, self._remote_version_is_before))
617
self._remote_version_is_before = version_tuple
619
def protocol_version(self):
620
"""Find out if 'hello' smart request works."""
621
if self._protocol_version_error is not None:
622
raise self._protocol_version_error
623
if not self._done_hello:
625
medium_request = self.get_request()
626
# Send a 'hello' request in protocol version one, for maximum
627
# backwards compatibility.
628
client_protocol = protocol.SmartClientRequestProtocolOne(medium_request)
629
client_protocol.query_version()
630
self._done_hello = True
631
except errors.SmartProtocolError, e:
632
# Cache the error, just like we would cache a successful
634
self._protocol_version_error = e
638
def should_probe(self):
639
"""Should RemoteBzrDirFormat.probe_transport send a smart request on
642
Some transports are unambiguously smart-only; there's no need to check
643
if the transport is able to carry smart requests, because that's all
644
it is for. In those cases, this method should return False.
646
But some HTTP transports can sometimes fail to carry smart requests,
647
but still be usuable for accessing remote bzrdirs via plain file
648
accesses. So for those transports, their media should return True here
649
so that RemoteBzrDirFormat can determine if it is appropriate for that
654
def disconnect(self):
655
"""If this medium maintains a persistent connection, close it.
657
The default implementation does nothing.
660
def remote_path_from_transport(self, transport):
661
"""Convert transport into a path suitable for using in a request.
663
Note that the resulting remote path doesn't encode the host name or
664
anything but path, so it is only safe to use it in requests sent over
665
the medium from the matching transport.
667
medium_base = urlutils.join(self.base, '/')
668
rel_url = urlutils.relative_url(medium_base, transport.base)
669
return urllib.unquote(rel_url)
672
class SmartClientStreamMedium(SmartClientMedium):
673
"""Stream based medium common class.
675
SmartClientStreamMediums operate on a stream. All subclasses use a common
676
SmartClientStreamMediumRequest for their requests, and should implement
677
_accept_bytes and _read_bytes to allow the request objects to send and
681
def __init__(self, base):
682
SmartClientMedium.__init__(self, base)
683
self._current_request = None
685
def accept_bytes(self, bytes):
686
self._accept_bytes(bytes)
689
"""The SmartClientStreamMedium knows how to close the stream when it is
695
"""Flush the output stream.
697
This method is used by the SmartClientStreamMediumRequest to ensure that
698
all data for a request is sent, to avoid long timeouts or deadlocks.
700
raise NotImplementedError(self._flush)
702
def get_request(self):
703
"""See SmartClientMedium.get_request().
705
SmartClientStreamMedium always returns a SmartClientStreamMediumRequest
708
return SmartClientStreamMediumRequest(self)
711
class SmartSimplePipesClientMedium(SmartClientStreamMedium):
712
"""A client medium using simple pipes.
714
This client does not manage the pipes: it assumes they will always be open.
716
Note that if readable_pipe.read might raise IOError or OSError with errno
717
of EINTR, it must be safe to retry the read.
720
def __init__(self, readable_pipe, writeable_pipe, base):
721
SmartClientStreamMedium.__init__(self, base)
722
self._readable_pipe = readable_pipe
723
self._writeable_pipe = writeable_pipe
725
def _accept_bytes(self, bytes):
726
"""See SmartClientStreamMedium.accept_bytes."""
727
self._writeable_pipe.write(bytes)
728
self._report_activity(len(bytes), 'write')
731
"""See SmartClientStreamMedium._flush()."""
732
self._writeable_pipe.flush()
734
def _read_bytes(self, count):
735
"""See SmartClientStreamMedium._read_bytes."""
736
bytes = osutils.until_no_eintr(self._readable_pipe.read, count)
737
self._report_activity(len(bytes), 'read')
741
class SmartSSHClientMedium(SmartClientStreamMedium):
742
"""A client medium using SSH."""
744
def __init__(self, host, port=None, username=None, password=None,
745
base=None, vendor=None, bzr_remote_path=None):
746
"""Creates a client that will connect on the first use.
748
:param vendor: An optional override for the ssh vendor to use. See
749
bzrlib.transport.ssh for details on ssh vendors.
751
self._connected = False
753
self._password = password
755
self._username = username
756
# for the benefit of progress making a short description of this
758
self._scheme = 'bzr+ssh'
759
# SmartClientStreamMedium stores the repr of this object in its
760
# _DebugCounter so we have to store all the values used in our repr
761
# method before calling the super init.
762
SmartClientStreamMedium.__init__(self, base)
763
self._read_from = None
764
self._ssh_connection = None
765
self._vendor = vendor
766
self._write_to = None
767
self._bzr_remote_path = bzr_remote_path
770
if self._port is None:
773
maybe_port = ':%s' % self._port
774
return "%s(%s://%s@%s%s/)" % (
775
self.__class__.__name__,
781
def _accept_bytes(self, bytes):
782
"""See SmartClientStreamMedium.accept_bytes."""
783
self._ensure_connection()
784
self._write_to.write(bytes)
785
self._report_activity(len(bytes), 'write')
787
def disconnect(self):
788
"""See SmartClientMedium.disconnect()."""
789
if not self._connected:
791
self._read_from.close()
792
self._write_to.close()
793
self._ssh_connection.close()
794
self._connected = False
796
def _ensure_connection(self):
797
"""Connect this medium if not already connected."""
800
if self._vendor is None:
801
vendor = ssh._get_ssh_vendor()
803
vendor = self._vendor
804
self._ssh_connection = vendor.connect_ssh(self._username,
805
self._password, self._host, self._port,
806
command=[self._bzr_remote_path, 'serve', '--inet',
807
'--directory=/', '--allow-writes'])
808
self._read_from, self._write_to = \
809
self._ssh_connection.get_filelike_channels()
810
self._connected = True
813
"""See SmartClientStreamMedium._flush()."""
814
self._write_to.flush()
816
def _read_bytes(self, count):
817
"""See SmartClientStreamMedium.read_bytes."""
818
if not self._connected:
819
raise errors.MediumNotConnected(self)
820
bytes_to_read = min(count, _MAX_READ_SIZE)
821
bytes = self._read_from.read(bytes_to_read)
822
self._report_activity(len(bytes), 'read')
826
# Port 4155 is the default port for bzr://, registered with IANA.
827
BZR_DEFAULT_INTERFACE = None
828
BZR_DEFAULT_PORT = 4155
831
class SmartTCPClientMedium(SmartClientStreamMedium):
832
"""A client medium using TCP."""
834
def __init__(self, host, port, base):
835
"""Creates a client that will connect on the first use."""
836
SmartClientStreamMedium.__init__(self, base)
837
self._connected = False
842
def _accept_bytes(self, bytes):
843
"""See SmartClientMedium.accept_bytes."""
844
self._ensure_connection()
845
osutils.send_all(self._socket, bytes, self._report_activity)
847
def disconnect(self):
848
"""See SmartClientMedium.disconnect()."""
849
if not self._connected:
853
self._connected = False
855
def _ensure_connection(self):
856
"""Connect this medium if not already connected."""
859
if self._port is None:
860
port = BZR_DEFAULT_PORT
862
port = int(self._port)
864
sockaddrs = socket.getaddrinfo(self._host, port, socket.AF_UNSPEC,
865
socket.SOCK_STREAM, 0, 0)
866
except socket.gaierror, (err_num, err_msg):
867
raise errors.ConnectionError("failed to lookup %s:%d: %s" %
868
(self._host, port, err_msg))
869
# Initialize err in case there are no addresses returned:
870
err = socket.error("no address found for %s" % self._host)
871
for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
873
self._socket = socket.socket(family, socktype, proto)
874
self._socket.setsockopt(socket.IPPROTO_TCP,
875
socket.TCP_NODELAY, 1)
876
self._socket.connect(sockaddr)
877
except socket.error, err:
878
if self._socket is not None:
883
if self._socket is None:
884
# socket errors either have a (string) or (errno, string) as their
886
if type(err.args) is str:
889
err_msg = err.args[1]
890
raise errors.ConnectionError("failed to connect to %s:%d: %s" %
891
(self._host, port, err_msg))
892
self._connected = True
895
"""See SmartClientStreamMedium._flush().
897
For TCP we do no flushing. We may want to turn off TCP_NODELAY and
898
add a means to do a flush, but that can be done in the future.
901
def _read_bytes(self, count):
902
"""See SmartClientMedium.read_bytes."""
903
if not self._connected:
904
raise errors.MediumNotConnected(self)
905
return _read_bytes_from_socket(self._socket, self._report_activity)
908
class SmartClientStreamMediumRequest(SmartClientMediumRequest):
909
"""A SmartClientMediumRequest that works with an SmartClientStreamMedium."""
911
def __init__(self, medium):
912
SmartClientMediumRequest.__init__(self, medium)
913
# check that we are safe concurrency wise. If some streams start
914
# allowing concurrent requests - i.e. via multiplexing - then this
915
# assert should be moved to SmartClientStreamMedium.get_request,
916
# and the setting/unsetting of _current_request likewise moved into
917
# that class : but its unneeded overhead for now. RBC 20060922
918
if self._medium._current_request is not None:
919
raise errors.TooManyConcurrentRequests(self._medium)
920
self._medium._current_request = self
922
def _accept_bytes(self, bytes):
923
"""See SmartClientMediumRequest._accept_bytes.
925
This forwards to self._medium._accept_bytes because we are operating
926
on the mediums stream.
928
self._medium._accept_bytes(bytes)
930
def _finished_reading(self):
931
"""See SmartClientMediumRequest._finished_reading.
933
This clears the _current_request on self._medium to allow a new
934
request to be created.
936
if self._medium._current_request is not self:
937
raise AssertionError()
938
self._medium._current_request = None
940
def _finished_writing(self):
941
"""See SmartClientMediumRequest._finished_writing.
943
This invokes self._medium._flush to ensure all bytes are transmitted.
945
self._medium._flush()
948
def _read_bytes_from_socket(sock, report_activity,
949
max_read_size=_MAX_READ_SIZE):
950
"""Read up to max_read_size of bytes from sock and notify of progress.
952
Translates "Connection reset by peer" into file-like EOF (return an
953
empty string rather than raise an error), and repeats the recv if
954
interrupted by a signal.
958
bytes = sock.recv(_MAX_READ_SIZE)
959
except socket.error, e:
961
if eno == getattr(errno, "WSAECONNRESET", errno.ECONNRESET):
962
# The connection was closed by the other side. Callers expect
963
# an empty string to signal end-of-stream.
965
elif eno == errno.EINTR:
966
# Retry the interrupted recv.
970
report_activity(len(bytes), 'read')