22
22
Media carry the bytes of the requests somehow (e.g. via TCP, wrapped in HTTP, or
23
23
over SSH), and pass them to and from the protocol logic. See the overview in
24
breezy/transport/smart/__init__.py.
24
bzrlib/transport/smart/__init__.py.
27
from __future__ import absolute_import
36
from ...lazy_import import lazy_import
32
from bzrlib.lazy_import import lazy_import
37
33
lazy_import(globals(), """
50
from breezy.i18n import gettext
51
from breezy.bzr.smart import client, protocol, request, signals, vfs
52
from breezy.transport import ssh
40
from bzrlib.smart import protocol
41
from bzrlib.transport import ssh
59
# Throughout this module buffer size parameters are either limited to be at
60
# most _MAX_READ_SIZE, or are ignored and _MAX_READ_SIZE is used instead.
61
# For this module's purposes, MAX_SOCKET_CHUNK is a reasonable size for reads
62
# from non-sockets as well.
63
_MAX_READ_SIZE = osutils.MAX_SOCKET_CHUNK
66
class HpssVfsRequestNotAllowed(errors.BzrError):
68
_fmt = ("VFS requests over the smart server are not allowed. Encountered: "
69
"%(method)s, %(arguments)s.")
71
def __init__(self, method, arguments):
73
self.arguments = arguments
45
# We must not read any more than 64k at a time so we don't risk "no buffer
46
# space available" errors on some platforms. Windows in particular is likely
47
# to give error 10053 or 10055 if we read more than 64k from a socket.
48
_MAX_READ_SIZE = 64 * 1024
76
51
def _get_protocol_factory_for_bytes(bytes):
249
196
while not self.finished:
250
197
server_protocol = self._build_protocol()
251
198
self._serve_one_request(server_protocol)
252
except errors.ConnectionTimeout as e:
253
trace.note('%s' % (e,))
254
trace.log_exception_quietly()
255
self._disconnect_client()
256
# We reported it, no reason to make a big fuss.
258
except Exception as e:
259
200
stderr.write("%s terminating on exception %s\n" % (self, e))
261
self._disconnect_client()
263
def _stop_gracefully(self):
264
"""When we finish this message, stop looking for more."""
265
trace.mutter('Stopping %s' % (self,))
268
def _disconnect_client(self):
269
"""Close the current connection. We stopped due to a timeout/etc."""
270
# The default implementation is a no-op, because that is all we used to
271
# do when disconnecting from a client. I suppose we never had the
272
# *server* initiate a disconnect, before
274
def _wait_for_bytes_with_timeout(self, timeout_seconds):
275
"""Wait for more bytes to be read, but timeout if none available.
277
This allows us to detect idle connections, and stop trying to read from
278
them, without setting the socket itself to non-blocking. This also
279
allows us to specify when we watch for idle timeouts.
281
:return: Did we timeout? (True if we timed out, False if there is data
284
raise NotImplementedError(self._wait_for_bytes_with_timeout)
286
203
def _build_protocol(self):
287
204
"""Identifies the version of the incoming request, and returns an
303
216
protocol.accept_bytes(unused_bytes)
306
def _wait_on_descriptor(self, fd, timeout_seconds):
307
"""select() on a file descriptor, waiting for nonblocking read()
309
This will raise a ConnectionTimeout exception if we do not get a
310
readable handle before timeout_seconds.
313
t_end = self._timer() + timeout_seconds
314
poll_timeout = min(timeout_seconds, self._client_poll_timeout)
316
while not rs and not xs and self._timer() < t_end:
320
rs, _, xs = select.select([fd], [], [fd], poll_timeout)
321
except (select.error, socket.error) as e:
322
err = getattr(e, 'errno', None)
323
if err is None and getattr(e, 'args', None) is not None:
324
# select.error doesn't have 'errno', it just has args[0]
326
if err in _bad_file_descriptor:
327
return # Not a socket indicates read() will fail
328
elif err == errno.EINTR:
329
# Interrupted, keep looping.
333
return # Socket may already be closed
336
raise errors.ConnectionTimeout('disconnecting client after %.1f seconds'
337
% (timeout_seconds,))
339
219
def _serve_one_request(self, protocol):
340
220
"""Read one request from input, process, send back a response.
342
222
:param protocol: a SmartServerRequestProtocol.
347
225
self._serve_one_request_unguarded(protocol)
348
226
except KeyboardInterrupt:
350
except Exception as e:
351
229
self.terminate_due_to_error()
353
231
def terminate_due_to_error(self):
365
243
class SmartServerSocketStreamMedium(SmartServerStreamMedium):
367
def __init__(self, sock, backing_transport, root_client_path='/',
245
def __init__(self, sock, backing_transport, root_client_path='/'):
371
248
:param sock: the socket the server will read from. It will be put
372
249
into blocking mode.
374
251
SmartServerStreamMedium.__init__(
375
self, backing_transport, root_client_path=root_client_path,
252
self, backing_transport, root_client_path=root_client_path)
377
253
sock.setblocking(True)
378
254
self.socket = sock
379
# Get the getpeername now, as we might be closed later when we care.
381
self._client_info = sock.getpeername()
383
self._client_info = '<unknown>'
386
return '%s(client=%s)' % (self.__class__.__name__, self._client_info)
389
return '%s.%s(client=%s)' % (self.__module__, self.__class__.__name__,
392
256
def _serve_one_request_unguarded(self, protocol):
393
257
while protocol.next_read_size():
394
258
# We can safely try to read large chunks. If there is less data
395
# than MAX_SOCKET_CHUNK ready, the socket will just return a
396
# short read immediately rather than block.
397
bytes = self.read_bytes(osutils.MAX_SOCKET_CHUNK)
259
# than _MAX_READ_SIZE ready, the socket wil just return a short
260
# read immediately rather than block.
261
bytes = self.read_bytes(_MAX_READ_SIZE)
399
263
self.finished = True
401
265
protocol.accept_bytes(bytes)
403
267
self._push_back(protocol.unused_data)
405
def _disconnect_client(self):
406
"""Close the current connection. We stopped due to a timeout/etc."""
409
def _wait_for_bytes_with_timeout(self, timeout_seconds):
410
"""Wait for more bytes to be read, but timeout if none available.
412
This allows us to detect idle connections, and stop trying to read from
413
them, without setting the socket itself to non-blocking. This also
414
allows us to specify when we watch for idle timeouts.
416
:return: None, this will raise ConnectionTimeout if we time out before
419
return self._wait_on_descriptor(self.socket, timeout_seconds)
421
269
def _read_bytes(self, desired_count):
422
return osutils.read_bytes_from_socket(
423
self.socket, self._report_activity)
270
# We ignore the desired_count because on sockets it's more efficient to
271
# read large chunks (of _MAX_READ_SIZE bytes) at a time.
272
return self.socket.recv(_MAX_READ_SIZE)
425
274
def terminate_due_to_error(self):
426
275
# TODO: This should log to a server log file, but no such thing
646
453
def read_line(self):
647
454
line = self._read_line()
648
if not line.endswith(b'\n'):
455
if not line.endswith('\n'):
649
456
# end of file encountered reading from server
650
457
raise errors.ConnectionReset(
651
"Unexpected end of message. Please check connectivity "
652
"and permissions, and report a bug if problems persist.")
458
"please check connectivity and permissions",
459
"(and try -Dhpss if further diagnosis is required)")
655
462
def _read_line(self):
656
463
"""Helper for SmartClientMediumRequest.read_line.
658
465
By default this forwards to self._medium._get_line because we are
659
466
operating on the medium's stream.
661
468
return self._medium._get_line()
664
class _VfsRefuser(object):
665
"""An object that refuses all VFS requests.
670
client._SmartClient.hooks.install_named_hook(
671
'call', self.check_vfs, 'vfs refuser')
673
def check_vfs(self, params):
675
request_method = request.request_handlers.get(params.method)
677
# A method we don't know about doesn't count as a VFS method.
679
if issubclass(request_method, vfs.VfsRequest):
680
raise HpssVfsRequestNotAllowed(params.method, params.args)
683
class _DebugCounter(object):
684
"""An object that counts the HPSS calls made to each client medium.
686
When a medium is garbage-collected, or failing that when
687
breezy.global_state exits, the total number of calls made on that medium
688
are reported via trace.note.
692
self.counts = weakref.WeakKeyDictionary()
693
client._SmartClient.hooks.install_named_hook(
694
'call', self.increment_call_count, 'hpss call counter')
695
breezy.get_global_state().cleanups.add_cleanup(self.flush_all)
697
def track(self, medium):
698
"""Start tracking calls made to a medium.
700
This only keeps a weakref to the medium, so shouldn't affect the
703
medium_repr = repr(medium)
704
# Add this medium to the WeakKeyDictionary
705
self.counts[medium] = dict(count=0, vfs_count=0,
706
medium_repr=medium_repr)
707
# Weakref callbacks are fired in reverse order of their association
708
# with the referenced object. So we add a weakref *after* adding to
709
# the WeakKeyDict so that we can report the value from it before the
710
# entry is removed by the WeakKeyDict's own callback.
711
ref = weakref.ref(medium, self.done)
713
def increment_call_count(self, params):
714
# Increment the count in the WeakKeyDictionary
715
value = self.counts[params.medium]
718
request_method = request.request_handlers.get(params.method)
720
# A method we don't know about doesn't count as a VFS method.
722
if issubclass(request_method, vfs.VfsRequest):
723
value['vfs_count'] += 1
726
value = self.counts[ref]
727
count, vfs_count, medium_repr = (
728
value['count'], value['vfs_count'], value['medium_repr'])
729
# In case this callback is invoked for the same ref twice (by the
730
# weakref callback and by the atexit function), set the call count back
731
# to 0 so this item won't be reported twice.
733
value['vfs_count'] = 0
735
trace.note(gettext('HPSS calls: {0} ({1} vfs) {2}').format(
736
count, vfs_count, medium_repr))
739
for ref in list(self.counts.keys()):
742
_debug_counter = None
746
471
class SmartClientMedium(SmartMedium):
747
472
"""Smart client is a medium for sending smart protocol requests over."""
924
621
self._readable_pipe = readable_pipe
925
622
self._writeable_pipe = writeable_pipe
927
def _accept_bytes(self, data):
624
def _accept_bytes(self, bytes):
928
625
"""See SmartClientStreamMedium.accept_bytes."""
930
self._writeable_pipe.write(data)
932
if e.errno in (errno.EINVAL, errno.EPIPE):
933
raise errors.ConnectionReset(
934
"Error trying to write to subprocess", e)
936
self._report_activity(len(data), 'write')
626
self._writeable_pipe.write(bytes)
938
628
def _flush(self):
939
629
"""See SmartClientStreamMedium._flush()."""
940
# Note: If flush were to fail, we'd like to raise ConnectionReset, etc.
941
# However, testing shows that even when the child process is
942
# gone, this doesn't error.
943
630
self._writeable_pipe.flush()
945
632
def _read_bytes(self, count):
946
633
"""See SmartClientStreamMedium._read_bytes."""
947
bytes_to_read = min(count, _MAX_READ_SIZE)
948
data = self._readable_pipe.read(bytes_to_read)
949
self._report_activity(len(data), 'read')
953
class SSHParams(object):
954
"""A set of parameters for starting a remote bzr via SSH."""
634
return self._readable_pipe.read(count)
637
class SmartSSHClientMedium(SmartClientStreamMedium):
638
"""A client medium using SSH."""
956
640
def __init__(self, host, port=None, username=None, password=None,
957
bzr_remote_path='bzr'):
960
self.username = username
961
self.password = password
962
self.bzr_remote_path = bzr_remote_path
965
class SmartSSHClientMedium(SmartClientStreamMedium):
966
"""A client medium using SSH.
968
It delegates IO to a SmartSimplePipesClientMedium or
969
SmartClientAlreadyConnectedSocketMedium (depending on platform).
972
def __init__(self, base, ssh_params, vendor=None):
641
base=None, vendor=None, bzr_remote_path=None):
973
642
"""Creates a client that will connect on the first use.
975
:param ssh_params: A SSHParams instance.
976
644
:param vendor: An optional override for the ssh vendor to use. See
977
breezy.transport.ssh for details on ssh vendors.
645
bzrlib.transport.ssh for details on ssh vendors.
979
self._real_medium = None
980
self._ssh_params = ssh_params
981
# for the benefit of progress making a short description of this
983
self._scheme = 'bzr+ssh'
984
# SmartClientStreamMedium stores the repr of this object in its
985
# _DebugCounter so we have to store all the values used in our repr
986
# method before calling the super init.
987
647
SmartClientStreamMedium.__init__(self, base)
648
self._connected = False
650
self._password = password
652
self._username = username
653
self._read_from = None
654
self._ssh_connection = None
988
655
self._vendor = vendor
989
self._ssh_connection = None
992
if self._ssh_params.port is None:
995
maybe_port = ':%s' % self._ssh_params.port
996
if self._ssh_params.username is None:
999
maybe_user = '%s@' % self._ssh_params.username
1000
return "%s(%s://%s%s%s/)" % (
1001
self.__class__.__name__,
1004
self._ssh_params.host,
656
self._write_to = None
657
self._bzr_remote_path = bzr_remote_path
658
if self._bzr_remote_path is None:
659
symbol_versioning.warn(
660
'bzr_remote_path is required as of bzr 0.92',
661
DeprecationWarning, stacklevel=2)
662
self._bzr_remote_path = os.environ.get('BZR_REMOTE_PATH', 'bzr')
1007
664
def _accept_bytes(self, bytes):
1008
665
"""See SmartClientStreamMedium.accept_bytes."""
1009
666
self._ensure_connection()
1010
self._real_medium.accept_bytes(bytes)
667
self._write_to.write(bytes)
1012
669
def disconnect(self):
1013
670
"""See SmartClientMedium.disconnect()."""
1014
if self._real_medium is not None:
1015
self._real_medium.disconnect()
1016
self._real_medium = None
1017
if self._ssh_connection is not None:
1018
self._ssh_connection.close()
1019
self._ssh_connection = None
671
if not self._connected:
673
self._read_from.close()
674
self._write_to.close()
675
self._ssh_connection.close()
676
self._connected = False
1021
678
def _ensure_connection(self):
1022
679
"""Connect this medium if not already connected."""
1023
if self._real_medium is not None:
1025
682
if self._vendor is None:
1026
683
vendor = ssh._get_ssh_vendor()
1028
685
vendor = self._vendor
1029
self._ssh_connection = vendor.connect_ssh(self._ssh_params.username,
1030
self._ssh_params.password, self._ssh_params.host,
1031
self._ssh_params.port,
1032
command=[self._ssh_params.bzr_remote_path, 'serve', '--inet',
686
self._ssh_connection = vendor.connect_ssh(self._username,
687
self._password, self._host, self._port,
688
command=[self._bzr_remote_path, 'serve', '--inet',
1033
689
'--directory=/', '--allow-writes'])
1034
io_kind, io_object = self._ssh_connection.get_sock_or_pipes()
1035
if io_kind == 'socket':
1036
self._real_medium = SmartClientAlreadyConnectedSocketMedium(
1037
self.base, io_object)
1038
elif io_kind == 'pipes':
1039
read_from, write_to = io_object
1040
self._real_medium = SmartSimplePipesClientMedium(
1041
read_from, write_to, self.base)
1043
raise AssertionError(
1044
"Unexpected io_kind %r from %r"
1045
% (io_kind, self._ssh_connection))
1046
for hook in transport.Transport.hooks["post_connect"]:
690
self._read_from, self._write_to = \
691
self._ssh_connection.get_filelike_channels()
692
self._connected = True
1049
694
def _flush(self):
1050
695
"""See SmartClientStreamMedium._flush()."""
1051
self._real_medium._flush()
696
self._write_to.flush()
1053
698
def _read_bytes(self, count):
1054
699
"""See SmartClientStreamMedium.read_bytes."""
1055
if self._real_medium is None:
700
if not self._connected:
1056
701
raise errors.MediumNotConnected(self)
1057
return self._real_medium.read_bytes(count)
702
bytes_to_read = min(count, _MAX_READ_SIZE)
703
return self._read_from.read(bytes_to_read)
1060
706
# Port 4155 is the default port for bzr://, registered with IANA.
1061
BZR_DEFAULT_INTERFACE = None
707
BZR_DEFAULT_INTERFACE = '0.0.0.0'
1062
708
BZR_DEFAULT_PORT = 4155
1065
class SmartClientSocketMedium(SmartClientStreamMedium):
1066
"""A client medium using a socket.
1068
This class isn't usable directly. Use one of its subclasses instead.
1071
def __init__(self, base):
711
class SmartTCPClientMedium(SmartClientStreamMedium):
712
"""A client medium using TCP."""
714
def __init__(self, host, port, base):
715
"""Creates a client that will connect on the first use."""
1072
716
SmartClientStreamMedium.__init__(self, base)
717
self._connected = False
1073
720
self._socket = None
1074
self._connected = False
1076
722
def _accept_bytes(self, bytes):
1077
723
"""See SmartClientMedium.accept_bytes."""
1078
724
self._ensure_connection()
1079
osutils.send_all(self._socket, bytes, self._report_activity)
1081
def _ensure_connection(self):
1082
"""Connect this medium if not already connected."""
1083
raise NotImplementedError(self._ensure_connection)
1086
"""See SmartClientStreamMedium._flush().
1088
For sockets we do no flushing. For TCP sockets we may want to turn off
1089
TCP_NODELAY and add a means to do a flush, but that can be done in the
1093
def _read_bytes(self, count):
1094
"""See SmartClientMedium.read_bytes."""
1095
if not self._connected:
1096
raise errors.MediumNotConnected(self)
1097
return osutils.read_bytes_from_socket(
1098
self._socket, self._report_activity)
725
osutils.send_all(self._socket, bytes)
1100
727
def disconnect(self):
1101
728
"""See SmartClientMedium.disconnect()."""
1105
732
self._socket = None
1106
733
self._connected = False
1109
class SmartTCPClientMedium(SmartClientSocketMedium):
1110
"""A client medium that creates a TCP connection."""
1112
def __init__(self, host, port, base):
1113
"""Creates a client that will connect on the first use."""
1114
SmartClientSocketMedium.__init__(self, base)
1118
735
def _ensure_connection(self):
1119
736
"""Connect this medium if not already connected."""
1120
737
if self._connected:
739
self._socket = socket.socket()
740
self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
1122
741
if self._port is None:
1123
742
port = BZR_DEFAULT_PORT
1125
744
port = int(self._port)
1127
sockaddrs = socket.getaddrinfo(self._host, port, socket.AF_UNSPEC,
1128
socket.SOCK_STREAM, 0, 0)
1129
except socket.gaierror as xxx_todo_changeme:
1130
(err_num, err_msg) = xxx_todo_changeme.args
1131
raise errors.ConnectionError("failed to lookup %s:%d: %s" %
1132
(self._host, port, err_msg))
1133
# Initialize err in case there are no addresses returned:
1134
last_err = socket.error("no address found for %s" % self._host)
1135
for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
1137
self._socket = socket.socket(family, socktype, proto)
1138
self._socket.setsockopt(socket.IPPROTO_TCP,
1139
socket.TCP_NODELAY, 1)
1140
self._socket.connect(sockaddr)
1141
except socket.error as err:
1142
if self._socket is not None:
1143
self._socket.close()
1148
if self._socket is None:
746
self._socket.connect((self._host, port))
747
except socket.error, err:
1149
748
# socket errors either have a (string) or (errno, string) as their
1151
if isinstance(last_err.args, str):
1152
err_msg = last_err.args
750
if type(err.args) is str:
1154
err_msg = last_err.args[1]
753
err_msg = err.args[1]
1155
754
raise errors.ConnectionError("failed to connect to %s:%d: %s" %
1156
755
(self._host, port, err_msg))
1157
756
self._connected = True
1158
for hook in transport.Transport.hooks["post_connect"]:
1162
class SmartClientAlreadyConnectedSocketMedium(SmartClientSocketMedium):
1163
"""A client medium for an already connected socket.
1165
Note that this class will assume it "owns" the socket, so it will close it
1166
when its disconnect method is called.
1169
def __init__(self, base, sock):
1170
SmartClientSocketMedium.__init__(self, base)
1172
self._connected = True
1174
def _ensure_connection(self):
1175
# Already connected, by definition! So nothing to do.
759
"""See SmartClientStreamMedium._flush().
761
For TCP we do no flushing. We may want to turn off TCP_NODELAY and
762
add a means to do a flush, but that can be done in the future.
765
def _read_bytes(self, count):
766
"""See SmartClientMedium.read_bytes."""
767
if not self._connected:
768
raise errors.MediumNotConnected(self)
769
# We ignore the desired_count because on sockets it's more efficient to
770
# read large chunks (of _MAX_READ_SIZE bytes) at a time.
771
return self._socket.recv(_MAX_READ_SIZE)
1179
774
class SmartClientStreamMediumRequest(SmartClientMediumRequest):