24
24
bzrlib/transport/smart/__init__.py.
33
from bzrlib.lazy_import import lazy_import
34
lazy_import(globals(), """
31
39
from bzrlib import (
36
from bzrlib.smart.protocol import (
38
SmartServerRequestProtocolOne,
39
SmartServerRequestProtocolTwo,
47
from bzrlib.smart import client, protocol, request, vfs
41
48
from bzrlib.transport import ssh
44
class SmartServerStreamMedium(object):
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):
45
182
"""Handles smart commands coming over a stream.
47
184
The stream may be a pipe connected to sshd, or a tcp socket, or an
112
252
"""Called when an unhandled exception from the protocol occurs."""
113
253
raise NotImplementedError(self.terminate_due_to_error)
115
def _get_bytes(self, desired_count):
255
def _read_bytes(self, desired_count):
116
256
"""Get some bytes from the medium.
118
258
:param desired_count: number of bytes we want to read.
120
raise NotImplementedError(self._get_bytes)
123
"""Read bytes from this request's response until a newline byte.
125
This isn't particularly efficient, so should only be used when the
126
expected size of the line is quite short.
128
:returns: a string of bytes ending in a newline (byte 0x0A).
130
# XXX: this duplicates SmartClientRequestProtocolOne._recv_tuple
132
while not line or line[-1] != '\n':
133
new_char = self._get_bytes(1)
136
# Ran out of bytes before receiving a complete line.
260
raise NotImplementedError(self._read_bytes)
141
263
class SmartServerSocketStreamMedium(SmartServerStreamMedium):
143
def __init__(self, sock, backing_transport):
265
def __init__(self, sock, backing_transport, root_client_path='/'):
146
268
:param sock: the socket the server will read from. It will be put
147
269
into blocking mode.
149
SmartServerStreamMedium.__init__(self, backing_transport)
271
SmartServerStreamMedium.__init__(
272
self, backing_transport, root_client_path=root_client_path)
151
273
sock.setblocking(True)
152
274
self.socket = sock
154
276
def _serve_one_request_unguarded(self, protocol):
155
277
while protocol.next_read_size():
157
protocol.accept_bytes(self.push_back)
160
bytes = self._get_bytes(4096)
164
protocol.accept_bytes(bytes)
166
self.push_back = protocol.excess_buffer
168
def _get_bytes(self, desired_count):
169
# We ignore the desired_count because on sockets it's more efficient to
171
return self.socket.recv(4096)
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)
173
293
def terminate_due_to_error(self):
174
"""Called when an unhandled exception from the protocol occurs."""
175
294
# TODO: This should log to a server log file, but no such thing
176
295
# exists yet. Andrew Bennetts 2006-09-29.
296
osutils.until_no_eintr(self.socket.close)
178
297
self.finished = True
180
299
def _write_out(self, bytes):
181
osutils.send_all(self.socket, 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))
184
309
class SmartServerPipeStreamMedium(SmartServerStreamMedium):
336
464
return self._read_bytes(count)
338
466
def _read_bytes(self, count):
339
"""Helper for read_bytes.
467
"""Helper for SmartClientMediumRequest.read_bytes.
341
469
read_bytes checks the state of the request to determing if bytes
342
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.
345
raise NotImplementedError(self._read_bytes)
476
return self._medium.read_bytes(count)
347
478
def read_line(self):
348
"""Read bytes from this request's response until a newline byte.
350
This isn't particularly efficient, so should only be used when the
351
expected size of the line is quite short.
353
:returns: a string of bytes ending in a newline (byte 0x0A).
355
# XXX: this duplicates SmartClientRequestProtocolOne._recv_tuple
357
while not line or line[-1] != '\n':
358
new_char = self.read_bytes(1)
361
# end of file encountered reading from server
362
raise errors.ConnectionReset(
363
"please check connectivity and permissions",
364
"(and try -Dhpss if further diagnosis is required)")
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.")
368
class SmartClientMedium(object):
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):
369
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
371
653
def disconnect(self):
372
654
"""If this medium maintains a persistent connection, close it.
374
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)
378
671
class SmartClientStreamMedium(SmartClientMedium):
379
672
"""Stream based medium common class.
417
707
return SmartClientStreamMediumRequest(self)
419
def read_bytes(self, count):
420
return self._read_bytes(count)
423
710
class SmartSimplePipesClientMedium(SmartClientStreamMedium):
424
711
"""A client medium using simple pipes.
426
713
This client does not manage the pipes: it assumes they will always be open.
429
def __init__(self, readable_pipe, writeable_pipe):
430
SmartClientStreamMedium.__init__(self)
716
def __init__(self, readable_pipe, writeable_pipe, base):
717
SmartClientStreamMedium.__init__(self, base)
431
718
self._readable_pipe = readable_pipe
432
719
self._writeable_pipe = writeable_pipe
434
721
def _accept_bytes(self, bytes):
435
722
"""See SmartClientStreamMedium.accept_bytes."""
436
self._writeable_pipe.write(bytes)
723
osutils.until_no_eintr(self._writeable_pipe.write, bytes)
724
self._report_activity(len(bytes), 'write')
438
726
def _flush(self):
439
727
"""See SmartClientStreamMedium._flush()."""
440
self._writeable_pipe.flush()
728
osutils.until_no_eintr(self._writeable_pipe.flush)
442
730
def _read_bytes(self, count):
443
731
"""See SmartClientStreamMedium._read_bytes."""
444
return self._readable_pipe.read(count)
732
bytes = osutils.until_no_eintr(self._readable_pipe.read, count)
733
self._report_activity(len(bytes), 'read')
447
737
class SmartSSHClientMedium(SmartClientStreamMedium):
448
738
"""A client medium using SSH."""
450
740
def __init__(self, host, port=None, username=None, password=None,
451
vendor=None, bzr_remote_path=None):
741
base=None, vendor=None, bzr_remote_path=None):
452
742
"""Creates a client that will connect on the first use.
454
744
:param vendor: An optional override for the ssh vendor to use. See
455
745
bzrlib.transport.ssh for details on ssh vendors.
457
SmartClientStreamMedium.__init__(self)
458
747
self._connected = False
459
748
self._host = host
460
749
self._password = password
461
750
self._port = port
462
751
self._username = username
752
# SmartClientStreamMedium stores the repr of this object in its
753
# _DebugCounter so we have to store all the values used in our repr
754
# method before calling the super init.
755
SmartClientStreamMedium.__init__(self, base)
463
756
self._read_from = None
464
757
self._ssh_connection = None
465
758
self._vendor = vendor
466
759
self._write_to = None
467
760
self._bzr_remote_path = bzr_remote_path
468
if self._bzr_remote_path is None:
469
symbol_versioning.warn(
470
'bzr_remote_path is required as of bzr 0.92',
471
DeprecationWarning, stacklevel=2)
472
self._bzr_remote_path = os.environ.get('BZR_REMOTE_PATH', 'bzr')
761
# for the benefit of progress making a short description of this
763
self._scheme = 'bzr+ssh'
766
return "%s(connected=%r, username=%r, host=%r, port=%r)" % (
767
self.__class__.__name__,
474
773
def _accept_bytes(self, bytes):
475
774
"""See SmartClientStreamMedium.accept_bytes."""
476
775
self._ensure_connection()
477
self._write_to.write(bytes)
776
osutils.until_no_eintr(self._write_to.write, bytes)
777
self._report_activity(len(bytes), 'write')
479
779
def disconnect(self):
480
780
"""See SmartClientMedium.disconnect()."""
481
781
if not self._connected:
483
self._read_from.close()
484
self._write_to.close()
783
osutils.until_no_eintr(self._read_from.close)
784
osutils.until_no_eintr(self._write_to.close)
485
785
self._ssh_connection.close()
486
786
self._connected = False
545
848
"""Connect this medium if not already connected."""
546
849
if self._connected:
548
self._socket = socket.socket()
549
self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
550
851
if self._port is None:
551
852
port = BZR_DEFAULT_PORT
553
854
port = int(self._port)
555
self._socket.connect((self._host, port))
556
except socket.error, err:
856
sockaddrs = socket.getaddrinfo(self._host, port, socket.AF_UNSPEC,
857
socket.SOCK_STREAM, 0, 0)
858
except socket.gaierror, (err_num, err_msg):
859
raise errors.ConnectionError("failed to lookup %s:%d: %s" %
860
(self._host, port, err_msg))
861
# Initialize err in case there are no addresses returned:
862
err = socket.error("no address found for %s" % self._host)
863
for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
865
self._socket = socket.socket(family, socktype, proto)
866
self._socket.setsockopt(socket.IPPROTO_TCP,
867
socket.TCP_NODELAY, 1)
868
self._socket.connect(sockaddr)
869
except socket.error, err:
870
if self._socket is not None:
875
if self._socket is None:
557
876
# socket errors either have a (string) or (errno, string) as their
559
878
if type(err.args) is str: