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 give error 10053 or 10055 if we read more than 64k from a socket.
56
_MAX_READ_SIZE = 64 * 1024
59
def _get_protocol_factory_for_bytes(bytes):
60
"""Determine the right protocol factory for 'bytes'.
62
This will return an appropriate protocol factory depending on the version
63
of the protocol being used, as determined by inspecting the given bytes.
64
The bytes should have at least one newline byte (i.e. be a whole line),
65
otherwise it's possible that a request will be incorrectly identified as
68
Typical use would be::
70
factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
71
server_protocol = factory(transport, write_func, root_client_path)
72
server_protocol.accept_bytes(unused_bytes)
74
:param bytes: a str of bytes of the start of the request.
75
:returns: 2-tuple of (protocol_factory, unused_bytes). protocol_factory is
76
a callable that takes three args: transport, write_func,
77
root_client_path. unused_bytes are any bytes that were not part of a
78
protocol version marker.
80
if bytes.startswith(protocol.MESSAGE_VERSION_THREE):
81
protocol_factory = protocol.build_server_protocol_three
82
bytes = bytes[len(protocol.MESSAGE_VERSION_THREE):]
83
elif bytes.startswith(protocol.REQUEST_VERSION_TWO):
84
protocol_factory = protocol.SmartServerRequestProtocolTwo
85
bytes = bytes[len(protocol.REQUEST_VERSION_TWO):]
87
protocol_factory = protocol.SmartServerRequestProtocolOne
88
return protocol_factory, bytes
91
def _get_line(read_bytes_func):
92
"""Read bytes using read_bytes_func until a newline byte.
94
This isn't particularly efficient, so should only be used when the
95
expected size of the line is quite short.
97
:returns: a tuple of two strs: (line, excess)
101
while newline_pos == -1:
102
new_bytes = read_bytes_func(1)
105
# Ran out of bytes before receiving a complete line.
107
newline_pos = bytes.find('\n')
108
line = bytes[:newline_pos+1]
109
excess = bytes[newline_pos+1:]
113
class SmartMedium(object):
114
"""Base class for smart protocol media, both client- and server-side."""
117
self._push_back_buffer = None
119
def _push_back(self, bytes):
120
"""Return unused bytes to the medium, because they belong to the next
123
This sets the _push_back_buffer to the given bytes.
125
if self._push_back_buffer is not None:
126
raise AssertionError(
127
"_push_back called when self._push_back_buffer is %r"
128
% (self._push_back_buffer,))
131
self._push_back_buffer = bytes
133
def _get_push_back_buffer(self):
134
if self._push_back_buffer == '':
135
raise AssertionError(
136
'%s._push_back_buffer should never be the empty string, '
137
'which can be confused with EOF' % (self,))
138
bytes = self._push_back_buffer
139
self._push_back_buffer = None
142
def read_bytes(self, desired_count):
143
"""Read some bytes from this medium.
145
:returns: some bytes, possibly more or less than the number requested
146
in 'desired_count' depending on the medium.
148
if self._push_back_buffer is not None:
149
return self._get_push_back_buffer()
150
bytes_to_read = min(desired_count, _MAX_READ_SIZE)
151
return self._read_bytes(bytes_to_read)
153
def _read_bytes(self, count):
154
raise NotImplementedError(self._read_bytes)
157
"""Read bytes from this request's response until a newline byte.
159
This isn't particularly efficient, so should only be used when the
160
expected size of the line is quite short.
162
:returns: a string of bytes ending in a newline (byte 0x0A).
164
line, excess = _get_line(self.read_bytes)
165
self._push_back(excess)
168
def _report_activity(self, bytes, direction):
169
"""Notify that this medium has activity.
171
Implementations should call this from all methods that actually do IO.
172
Be careful that it's not called twice, if one method is implemented on
175
:param bytes: Number of bytes read or written.
176
:param direction: 'read' or 'write' or None.
178
ui.ui_factory.report_transport_activity(self, bytes, direction)
181
class SmartServerStreamMedium(SmartMedium):
182
"""Handles smart commands coming over a stream.
184
The stream may be a pipe connected to sshd, or a tcp socket, or an
185
in-process fifo for testing.
187
One instance is created for each connected client; it can serve multiple
188
requests in the lifetime of the connection.
190
The server passes requests through to an underlying backing transport,
191
which will typically be a LocalTransport looking at the server's filesystem.
193
:ivar _push_back_buffer: a str of bytes that have been read from the stream
194
but not used yet, or None if there are no buffered bytes. Subclasses
195
should make sure to exhaust this buffer before reading more bytes from
196
the stream. See also the _push_back method.
199
def __init__(self, backing_transport, root_client_path='/'):
200
"""Construct new server.
202
:param backing_transport: Transport for the directory served.
204
# backing_transport could be passed to serve instead of __init__
205
self.backing_transport = backing_transport
206
self.root_client_path = root_client_path
207
self.finished = False
208
SmartMedium.__init__(self)
211
"""Serve requests until the client disconnects."""
212
# Keep a reference to stderr because the sys module's globals get set to
213
# None during interpreter shutdown.
214
from sys import stderr
216
while not self.finished:
217
server_protocol = self._build_protocol()
218
self._serve_one_request(server_protocol)
220
stderr.write("%s terminating on exception %s\n" % (self, e))
223
def _build_protocol(self):
224
"""Identifies the version of the incoming request, and returns an
225
a protocol object that can interpret it.
227
If more bytes than the version prefix of the request are read, they will
228
be fed into the protocol before it is returned.
230
:returns: a SmartServerRequestProtocol.
232
bytes = self._get_line()
233
protocol_factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
234
protocol = protocol_factory(
235
self.backing_transport, self._write_out, self.root_client_path)
236
protocol.accept_bytes(unused_bytes)
239
def _serve_one_request(self, protocol):
240
"""Read one request from input, process, send back a response.
242
:param protocol: a SmartServerRequestProtocol.
245
self._serve_one_request_unguarded(protocol)
246
except KeyboardInterrupt:
249
self.terminate_due_to_error()
251
def terminate_due_to_error(self):
252
"""Called when an unhandled exception from the protocol occurs."""
253
raise NotImplementedError(self.terminate_due_to_error)
255
def _read_bytes(self, desired_count):
256
"""Get some bytes from the medium.
258
:param desired_count: number of bytes we want to read.
260
raise NotImplementedError(self._read_bytes)
263
class SmartServerSocketStreamMedium(SmartServerStreamMedium):
265
def __init__(self, sock, backing_transport, root_client_path='/'):
268
:param sock: the socket the server will read from. It will be put
271
SmartServerStreamMedium.__init__(
272
self, backing_transport, root_client_path=root_client_path)
273
sock.setblocking(True)
276
def _serve_one_request_unguarded(self, protocol):
277
while protocol.next_read_size():
278
# We can safely try to read large chunks. If there is less data
279
# than _MAX_READ_SIZE ready, the socket wil just return a short
280
# read immediately rather than block.
281
bytes = self.read_bytes(_MAX_READ_SIZE)
285
protocol.accept_bytes(bytes)
287
self._push_back(protocol.unused_data)
289
def _read_bytes(self, desired_count):
290
return _read_bytes_from_socket(
291
self.socket.recv, desired_count, self._report_activity)
293
def terminate_due_to_error(self):
294
# TODO: This should log to a server log file, but no such thing
295
# exists yet. Andrew Bennetts 2006-09-29.
296
osutils.until_no_eintr(self.socket.close)
299
def _write_out(self, bytes):
300
tstart = osutils.timer_func()
301
osutils.send_all(self.socket, bytes, self._report_activity)
302
if 'hpss' in debug.debug_flags:
303
thread_id = thread.get_ident()
304
trace.mutter('%12s: [%s] %d bytes to the socket in %.3fs'
305
% ('wrote', thread_id, len(bytes),
306
osutils.timer_func() - tstart))
309
class SmartServerPipeStreamMedium(SmartServerStreamMedium):
311
def __init__(self, in_file, out_file, backing_transport):
312
"""Construct new server.
314
:param in_file: Python file from which requests can be read.
315
:param out_file: Python file to write responses.
316
:param backing_transport: Transport for the directory served.
318
SmartServerStreamMedium.__init__(self, backing_transport)
319
if sys.platform == 'win32':
320
# force binary mode for files
322
for f in (in_file, out_file):
323
fileno = getattr(f, 'fileno', None)
325
msvcrt.setmode(fileno(), os.O_BINARY)
329
def _serve_one_request_unguarded(self, protocol):
331
# We need to be careful not to read past the end of the current
332
# request, or else the read from the pipe will block, so we use
333
# protocol.next_read_size().
334
bytes_to_read = protocol.next_read_size()
335
if bytes_to_read == 0:
336
# Finished serving this request.
337
osutils.until_no_eintr(self._out.flush)
339
bytes = self.read_bytes(bytes_to_read)
341
# Connection has been closed.
343
osutils.until_no_eintr(self._out.flush)
345
protocol.accept_bytes(bytes)
347
def _read_bytes(self, desired_count):
348
return osutils.until_no_eintr(self._in.read, desired_count)
350
def terminate_due_to_error(self):
351
# TODO: This should log to a server log file, but no such thing
352
# exists yet. Andrew Bennetts 2006-09-29.
353
osutils.until_no_eintr(self._out.close)
356
def _write_out(self, bytes):
357
osutils.until_no_eintr(self._out.write, bytes)
360
class SmartClientMediumRequest(object):
361
"""A request on a SmartClientMedium.
363
Each request allows bytes to be provided to it via accept_bytes, and then
364
the response bytes to be read via read_bytes.
367
request.accept_bytes('123')
368
request.finished_writing()
369
result = request.read_bytes(3)
370
request.finished_reading()
372
It is up to the individual SmartClientMedium whether multiple concurrent
373
requests can exist. See SmartClientMedium.get_request to obtain instances
374
of SmartClientMediumRequest, and the concrete Medium you are using for
375
details on concurrency and pipelining.
378
def __init__(self, medium):
379
"""Construct a SmartClientMediumRequest for the medium medium."""
380
self._medium = medium
381
# we track state by constants - we may want to use the same
382
# pattern as BodyReader if it gets more complex.
383
# valid states are: "writing", "reading", "done"
384
self._state = "writing"
386
def accept_bytes(self, bytes):
387
"""Accept bytes for inclusion in this request.
389
This method may not be called after finished_writing() has been
390
called. It depends upon the Medium whether or not the bytes will be
391
immediately transmitted. Message based Mediums will tend to buffer the
392
bytes until finished_writing() is called.
394
:param bytes: A bytestring.
396
if self._state != "writing":
397
raise errors.WritingCompleted(self)
398
self._accept_bytes(bytes)
400
def _accept_bytes(self, bytes):
401
"""Helper for accept_bytes.
403
Accept_bytes checks the state of the request to determing if bytes
404
should be accepted. After that it hands off to _accept_bytes to do the
407
raise NotImplementedError(self._accept_bytes)
409
def finished_reading(self):
410
"""Inform the request that all desired data has been read.
412
This will remove the request from the pipeline for its medium (if the
413
medium supports pipelining) and any further calls to methods on the
414
request will raise ReadingCompleted.
416
if self._state == "writing":
417
raise errors.WritingNotComplete(self)
418
if self._state != "reading":
419
raise errors.ReadingCompleted(self)
421
self._finished_reading()
423
def _finished_reading(self):
424
"""Helper for finished_reading.
426
finished_reading checks the state of the request to determine if
427
finished_reading is allowed, and if it is hands off to _finished_reading
428
to perform the action.
430
raise NotImplementedError(self._finished_reading)
432
def finished_writing(self):
433
"""Finish the writing phase of this request.
435
This will flush all pending data for this request along the medium.
436
After calling finished_writing, you may not call accept_bytes anymore.
438
if self._state != "writing":
439
raise errors.WritingCompleted(self)
440
self._state = "reading"
441
self._finished_writing()
443
def _finished_writing(self):
444
"""Helper for finished_writing.
446
finished_writing checks the state of the request to determine if
447
finished_writing is allowed, and if it is hands off to _finished_writing
448
to perform the action.
450
raise NotImplementedError(self._finished_writing)
452
def read_bytes(self, count):
453
"""Read bytes from this requests response.
455
This method will block and wait for count bytes to be read. It may not
456
be invoked until finished_writing() has been called - this is to ensure
457
a message-based approach to requests, for compatibility with message
458
based mediums like HTTP.
460
if self._state == "writing":
461
raise errors.WritingNotComplete(self)
462
if self._state != "reading":
463
raise errors.ReadingCompleted(self)
464
return self._read_bytes(count)
466
def _read_bytes(self, count):
467
"""Helper for SmartClientMediumRequest.read_bytes.
469
read_bytes checks the state of the request to determing if bytes
470
should be read. After that it hands off to _read_bytes to do the
473
By default this forwards to self._medium.read_bytes because we are
474
operating on the medium's stream.
476
return self._medium.read_bytes(count)
479
line = self._read_line()
480
if not line.endswith('\n'):
481
# end of file encountered reading from server
482
raise errors.ConnectionReset(
483
"Unexpected end of message. Please check connectivity "
484
"and permissions, and report a bug if problems persist.")
487
def _read_line(self):
488
"""Helper for SmartClientMediumRequest.read_line.
490
By default this forwards to self._medium._get_line because we are
491
operating on the medium's stream.
493
return self._medium._get_line()
496
class _DebugCounter(object):
497
"""An object that counts the HPSS calls made to each client medium.
499
When a medium is garbage-collected, or failing that when atexit functions
500
are run, the total number of calls made on that medium are reported via
505
self.counts = weakref.WeakKeyDictionary()
506
client._SmartClient.hooks.install_named_hook(
507
'call', self.increment_call_count, 'hpss call counter')
508
atexit.register(self.flush_all)
510
def track(self, medium):
511
"""Start tracking calls made to a medium.
513
This only keeps a weakref to the medium, so shouldn't affect the
516
medium_repr = repr(medium)
517
# Add this medium to the WeakKeyDictionary
518
self.counts[medium] = dict(count=0, vfs_count=0,
519
medium_repr=medium_repr)
520
# Weakref callbacks are fired in reverse order of their association
521
# with the referenced object. So we add a weakref *after* adding to
522
# the WeakKeyDict so that we can report the value from it before the
523
# entry is removed by the WeakKeyDict's own callback.
524
ref = weakref.ref(medium, self.done)
526
def increment_call_count(self, params):
527
# Increment the count in the WeakKeyDictionary
528
value = self.counts[params.medium]
531
request_method = request.request_handlers.get(params.method)
533
# A method we don't know about doesn't count as a VFS method.
535
if issubclass(request_method, vfs.VfsRequest):
536
value['vfs_count'] += 1
539
value = self.counts[ref]
540
count, vfs_count, medium_repr = (
541
value['count'], value['vfs_count'], value['medium_repr'])
542
# In case this callback is invoked for the same ref twice (by the
543
# weakref callback and by the atexit function), set the call count back
544
# to 0 so this item won't be reported twice.
546
value['vfs_count'] = 0
548
trace.note('HPSS calls: %d (%d vfs) %s',
549
count, vfs_count, medium_repr)
552
for ref in list(self.counts.keys()):
555
_debug_counter = None
558
class SmartClientMedium(SmartMedium):
559
"""Smart client is a medium for sending smart protocol requests over."""
561
def __init__(self, base):
562
super(SmartClientMedium, self).__init__()
564
self._protocol_version_error = None
565
self._protocol_version = None
566
self._done_hello = False
567
# Be optimistic: we assume the remote end can accept new remote
568
# requests until we get an error saying otherwise.
569
# _remote_version_is_before tracks the bzr version the remote side
570
# can be based on what we've seen so far.
571
self._remote_version_is_before = None
572
# Install debug hook function if debug flag is set.
573
if 'hpss' in debug.debug_flags:
574
global _debug_counter
575
if _debug_counter is None:
576
_debug_counter = _DebugCounter()
577
_debug_counter.track(self)
579
def _is_remote_before(self, version_tuple):
580
"""Is it possible the remote side supports RPCs for a given version?
584
needed_version = (1, 2)
585
if medium._is_remote_before(needed_version):
586
fallback_to_pre_1_2_rpc()
590
except UnknownSmartMethod:
591
medium._remember_remote_is_before(needed_version)
592
fallback_to_pre_1_2_rpc()
594
:seealso: _remember_remote_is_before
596
if self._remote_version_is_before is None:
597
# So far, the remote side seems to support everything
599
return version_tuple >= self._remote_version_is_before
601
def _remember_remote_is_before(self, version_tuple):
602
"""Tell this medium that the remote side is older the given version.
604
:seealso: _is_remote_before
606
if (self._remote_version_is_before is not None and
607
version_tuple > self._remote_version_is_before):
608
# We have been told that the remote side is older than some version
609
# which is newer than a previously supplied older-than version.
610
# This indicates that some smart verb call is not guarded
611
# appropriately (it should simply not have been tried).
612
raise AssertionError(
613
"_remember_remote_is_before(%r) called, but "
614
"_remember_remote_is_before(%r) was called previously."
615
% (version_tuple, self._remote_version_is_before))
616
self._remote_version_is_before = version_tuple
618
def protocol_version(self):
619
"""Find out if 'hello' smart request works."""
620
if self._protocol_version_error is not None:
621
raise self._protocol_version_error
622
if not self._done_hello:
624
medium_request = self.get_request()
625
# Send a 'hello' request in protocol version one, for maximum
626
# backwards compatibility.
627
client_protocol = protocol.SmartClientRequestProtocolOne(medium_request)
628
client_protocol.query_version()
629
self._done_hello = True
630
except errors.SmartProtocolError, e:
631
# Cache the error, just like we would cache a successful
633
self._protocol_version_error = e
637
def should_probe(self):
638
"""Should RemoteBzrDirFormat.probe_transport send a smart request on
641
Some transports are unambiguously smart-only; there's no need to check
642
if the transport is able to carry smart requests, because that's all
643
it is for. In those cases, this method should return False.
645
But some HTTP transports can sometimes fail to carry smart requests,
646
but still be usuable for accessing remote bzrdirs via plain file
647
accesses. So for those transports, their media should return True here
648
so that RemoteBzrDirFormat can determine if it is appropriate for that
653
def disconnect(self):
654
"""If this medium maintains a persistent connection, close it.
656
The default implementation does nothing.
659
def remote_path_from_transport(self, transport):
660
"""Convert transport into a path suitable for using in a request.
662
Note that the resulting remote path doesn't encode the host name or
663
anything but path, so it is only safe to use it in requests sent over
664
the medium from the matching transport.
666
medium_base = urlutils.join(self.base, '/')
667
rel_url = urlutils.relative_url(medium_base, transport.base)
668
return urllib.unquote(rel_url)
671
class SmartClientStreamMedium(SmartClientMedium):
672
"""Stream based medium common class.
674
SmartClientStreamMediums operate on a stream. All subclasses use a common
675
SmartClientStreamMediumRequest for their requests, and should implement
676
_accept_bytes and _read_bytes to allow the request objects to send and
680
def __init__(self, base):
681
SmartClientMedium.__init__(self, base)
682
self._current_request = None
684
def accept_bytes(self, bytes):
685
self._accept_bytes(bytes)
688
"""The SmartClientStreamMedium knows how to close the stream when it is
694
"""Flush the output stream.
696
This method is used by the SmartClientStreamMediumRequest to ensure that
697
all data for a request is sent, to avoid long timeouts or deadlocks.
699
raise NotImplementedError(self._flush)
701
def get_request(self):
702
"""See SmartClientMedium.get_request().
704
SmartClientStreamMedium always returns a SmartClientStreamMediumRequest
707
return SmartClientStreamMediumRequest(self)
710
class SmartSimplePipesClientMedium(SmartClientStreamMedium):
711
"""A client medium using simple pipes.
713
This client does not manage the pipes: it assumes they will always be open.
716
def __init__(self, readable_pipe, writeable_pipe, base):
717
SmartClientStreamMedium.__init__(self, base)
718
self._readable_pipe = readable_pipe
719
self._writeable_pipe = writeable_pipe
721
def _accept_bytes(self, bytes):
722
"""See SmartClientStreamMedium.accept_bytes."""
723
osutils.until_no_eintr(self._writeable_pipe.write, bytes)
724
self._report_activity(len(bytes), 'write')
727
"""See SmartClientStreamMedium._flush()."""
728
osutils.until_no_eintr(self._writeable_pipe.flush)
730
def _read_bytes(self, count):
731
"""See SmartClientStreamMedium._read_bytes."""
732
bytes = osutils.until_no_eintr(self._readable_pipe.read, count)
733
self._report_activity(len(bytes), 'read')
737
class SmartSSHClientMedium(SmartClientStreamMedium):
738
"""A client medium using SSH."""
740
def __init__(self, host, port=None, username=None, password=None,
741
base=None, vendor=None, bzr_remote_path=None):
742
"""Creates a client that will connect on the first use.
744
:param vendor: An optional override for the ssh vendor to use. See
745
bzrlib.transport.ssh for details on ssh vendors.
747
self._connected = False
749
self._password = password
751
self._username = username
752
# for the benefit of progress making a short description of this
754
self._scheme = 'bzr+ssh'
755
# SmartClientStreamMedium stores the repr of this object in its
756
# _DebugCounter so we have to store all the values used in our repr
757
# method before calling the super init.
758
SmartClientStreamMedium.__init__(self, base)
759
self._read_from = None
760
self._ssh_connection = None
761
self._vendor = vendor
762
self._write_to = None
763
self._bzr_remote_path = bzr_remote_path
766
if self._port is None:
769
maybe_port = ':%s' % self._port
770
return "%s(%s://%s@%s%s/)" % (
771
self.__class__.__name__,
777
def _accept_bytes(self, bytes):
778
"""See SmartClientStreamMedium.accept_bytes."""
779
self._ensure_connection()
780
osutils.until_no_eintr(self._write_to.write, bytes)
781
self._report_activity(len(bytes), 'write')
783
def disconnect(self):
784
"""See SmartClientMedium.disconnect()."""
785
if not self._connected:
787
osutils.until_no_eintr(self._read_from.close)
788
osutils.until_no_eintr(self._write_to.close)
789
self._ssh_connection.close()
790
self._connected = False
792
def _ensure_connection(self):
793
"""Connect this medium if not already connected."""
796
if self._vendor is None:
797
vendor = ssh._get_ssh_vendor()
799
vendor = self._vendor
800
self._ssh_connection = vendor.connect_ssh(self._username,
801
self._password, self._host, self._port,
802
command=[self._bzr_remote_path, 'serve', '--inet',
803
'--directory=/', '--allow-writes'])
804
self._read_from, self._write_to = \
805
self._ssh_connection.get_filelike_channels()
806
self._connected = True
809
"""See SmartClientStreamMedium._flush()."""
810
self._write_to.flush()
812
def _read_bytes(self, count):
813
"""See SmartClientStreamMedium.read_bytes."""
814
if not self._connected:
815
raise errors.MediumNotConnected(self)
816
bytes_to_read = min(count, _MAX_READ_SIZE)
817
bytes = osutils.until_no_eintr(self._read_from.read, bytes_to_read)
818
self._report_activity(len(bytes), 'read')
822
# Port 4155 is the default port for bzr://, registered with IANA.
823
BZR_DEFAULT_INTERFACE = None
824
BZR_DEFAULT_PORT = 4155
827
class SmartTCPClientMedium(SmartClientStreamMedium):
828
"""A client medium using TCP."""
830
def __init__(self, host, port, base):
831
"""Creates a client that will connect on the first use."""
832
SmartClientStreamMedium.__init__(self, base)
833
self._connected = False
838
def _accept_bytes(self, bytes):
839
"""See SmartClientMedium.accept_bytes."""
840
self._ensure_connection()
841
osutils.send_all(self._socket, bytes, self._report_activity)
843
def disconnect(self):
844
"""See SmartClientMedium.disconnect()."""
845
if not self._connected:
847
osutils.until_no_eintr(self._socket.close)
849
self._connected = False
851
def _ensure_connection(self):
852
"""Connect this medium if not already connected."""
855
if self._port is None:
856
port = BZR_DEFAULT_PORT
858
port = int(self._port)
860
sockaddrs = socket.getaddrinfo(self._host, port, socket.AF_UNSPEC,
861
socket.SOCK_STREAM, 0, 0)
862
except socket.gaierror, (err_num, err_msg):
863
raise errors.ConnectionError("failed to lookup %s:%d: %s" %
864
(self._host, port, err_msg))
865
# Initialize err in case there are no addresses returned:
866
err = socket.error("no address found for %s" % self._host)
867
for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
869
self._socket = socket.socket(family, socktype, proto)
870
self._socket.setsockopt(socket.IPPROTO_TCP,
871
socket.TCP_NODELAY, 1)
872
self._socket.connect(sockaddr)
873
except socket.error, err:
874
if self._socket is not None:
879
if self._socket is None:
880
# socket errors either have a (string) or (errno, string) as their
882
if type(err.args) is str:
885
err_msg = err.args[1]
886
raise errors.ConnectionError("failed to connect to %s:%d: %s" %
887
(self._host, port, err_msg))
888
self._connected = True
891
"""See SmartClientStreamMedium._flush().
893
For TCP we do no flushing. We may want to turn off TCP_NODELAY and
894
add a means to do a flush, but that can be done in the future.
897
def _read_bytes(self, count):
898
"""See SmartClientMedium.read_bytes."""
899
if not self._connected:
900
raise errors.MediumNotConnected(self)
901
return _read_bytes_from_socket(
902
self._socket.recv, count, self._report_activity)
905
class SmartClientStreamMediumRequest(SmartClientMediumRequest):
906
"""A SmartClientMediumRequest that works with an SmartClientStreamMedium."""
908
def __init__(self, medium):
909
SmartClientMediumRequest.__init__(self, medium)
910
# check that we are safe concurrency wise. If some streams start
911
# allowing concurrent requests - i.e. via multiplexing - then this
912
# assert should be moved to SmartClientStreamMedium.get_request,
913
# and the setting/unsetting of _current_request likewise moved into
914
# that class : but its unneeded overhead for now. RBC 20060922
915
if self._medium._current_request is not None:
916
raise errors.TooManyConcurrentRequests(self._medium)
917
self._medium._current_request = self
919
def _accept_bytes(self, bytes):
920
"""See SmartClientMediumRequest._accept_bytes.
922
This forwards to self._medium._accept_bytes because we are operating
923
on the mediums stream.
925
self._medium._accept_bytes(bytes)
927
def _finished_reading(self):
928
"""See SmartClientMediumRequest._finished_reading.
930
This clears the _current_request on self._medium to allow a new
931
request to be created.
933
if self._medium._current_request is not self:
934
raise AssertionError()
935
self._medium._current_request = None
937
def _finished_writing(self):
938
"""See SmartClientMediumRequest._finished_writing.
940
This invokes self._medium._flush to ensure all bytes are transmitted.
942
self._medium._flush()
945
def _read_bytes_from_socket(sock, desired_count, report_activity):
946
# We ignore the desired_count because on sockets it's more efficient to
947
# read large chunks (of _MAX_READ_SIZE bytes) at a time.
949
bytes = osutils.until_no_eintr(sock, _MAX_READ_SIZE)
950
except socket.error, e:
951
if len(e.args) and e.args[0] in (errno.ECONNRESET, 10054):
952
# The connection was closed by the other side. Callers expect an
953
# empty string to signal end-of-stream.
958
report_activity(len(bytes), 'read')