24
24
bzrlib/transport/smart/__init__.py.
31
from bzrlib import errors
32
from bzrlib.smart.protocol import (
34
SmartServerRequestProtocolOne,
35
SmartServerRequestProtocolTwo,
33
from bzrlib.lazy_import import lazy_import
34
lazy_import(globals(), """
39
from bzrlib.transport import ssh
40
except errors.ParamikoNotPresent:
41
# no paramiko. SmartSSHClientMedium will break.
45
class SmartServerStreamMedium(object):
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):
46
182
"""Handles smart commands coming over a stream.
48
184
The stream may be a pipe connected to sshd, or a tcp socket, or an
113
252
"""Called when an unhandled exception from the protocol occurs."""
114
253
raise NotImplementedError(self.terminate_due_to_error)
116
def _get_bytes(self, desired_count):
255
def _read_bytes(self, desired_count):
117
256
"""Get some bytes from the medium.
119
258
:param desired_count: number of bytes we want to read.
121
raise NotImplementedError(self._get_bytes)
124
"""Read bytes from this request's response until a newline byte.
126
This isn't particularly efficient, so should only be used when the
127
expected size of the line is quite short.
129
:returns: a string of bytes ending in a newline (byte 0x0A).
131
# XXX: this duplicates SmartClientRequestProtocolOne._recv_tuple
133
while not line or line[-1] != '\n':
134
new_char = self._get_bytes(1)
137
# Ran out of bytes before receiving a complete line.
260
raise NotImplementedError(self._read_bytes)
142
263
class SmartServerSocketStreamMedium(SmartServerStreamMedium):
144
def __init__(self, sock, backing_transport):
265
def __init__(self, sock, backing_transport, root_client_path='/'):
147
268
:param sock: the socket the server will read from. It will be put
148
269
into blocking mode.
150
SmartServerStreamMedium.__init__(self, backing_transport)
271
SmartServerStreamMedium.__init__(
272
self, backing_transport, root_client_path=root_client_path)
152
273
sock.setblocking(True)
153
274
self.socket = sock
155
276
def _serve_one_request_unguarded(self, protocol):
156
277
while protocol.next_read_size():
158
protocol.accept_bytes(self.push_back)
161
bytes = self._get_bytes(4096)
165
protocol.accept_bytes(bytes)
167
self.push_back = protocol.excess_buffer
169
def _get_bytes(self, desired_count):
170
# We ignore the desired_count because on sockets it's more efficient to
172
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)
174
293
def terminate_due_to_error(self):
175
"""Called when an unhandled exception from the protocol occurs."""
176
294
# TODO: This should log to a server log file, but no such thing
177
295
# exists yet. Andrew Bennetts 2006-09-29.
296
osutils.until_no_eintr(self.socket.close)
179
297
self.finished = True
181
299
def _write_out(self, bytes):
182
self.socket.sendall(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))
185
309
class SmartServerPipeStreamMedium(SmartServerStreamMedium):
337
464
return self._read_bytes(count)
339
466
def _read_bytes(self, count):
340
"""Helper for read_bytes.
467
"""Helper for SmartClientMediumRequest.read_bytes.
342
469
read_bytes checks the state of the request to determing if bytes
343
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.
346
raise NotImplementedError(self._read_bytes)
476
return self._medium.read_bytes(count)
348
478
def read_line(self):
349
"""Read bytes from this request's response until a newline byte.
351
This isn't particularly efficient, so should only be used when the
352
expected size of the line is quite short.
354
:returns: a string of bytes ending in a newline (byte 0x0A).
356
# XXX: this duplicates SmartClientRequestProtocolOne._recv_tuple
358
while not line or line[-1] != '\n':
359
new_char = self.read_bytes(1)
362
raise errors.SmartProtocolError(
363
'unexpected end of file reading from server')
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.")
367
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):
368
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
370
653
def disconnect(self):
371
654
"""If this medium maintains a persistent connection, close it.
373
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)
377
671
class SmartClientStreamMedium(SmartClientMedium):
378
672
"""Stream based medium common class.
412
707
return SmartClientStreamMediumRequest(self)
414
def read_bytes(self, count):
415
return self._read_bytes(count)
418
710
class SmartSimplePipesClientMedium(SmartClientStreamMedium):
419
711
"""A client medium using simple pipes.
421
713
This client does not manage the pipes: it assumes they will always be open.
424
def __init__(self, readable_pipe, writeable_pipe):
425
SmartClientStreamMedium.__init__(self)
716
def __init__(self, readable_pipe, writeable_pipe, base):
717
SmartClientStreamMedium.__init__(self, base)
426
718
self._readable_pipe = readable_pipe
427
719
self._writeable_pipe = writeable_pipe
429
721
def _accept_bytes(self, bytes):
430
722
"""See SmartClientStreamMedium.accept_bytes."""
431
self._writeable_pipe.write(bytes)
723
osutils.until_no_eintr(self._writeable_pipe.write, bytes)
724
self._report_activity(len(bytes), 'write')
433
726
def _flush(self):
434
727
"""See SmartClientStreamMedium._flush()."""
435
self._writeable_pipe.flush()
728
osutils.until_no_eintr(self._writeable_pipe.flush)
437
730
def _read_bytes(self, count):
438
731
"""See SmartClientStreamMedium._read_bytes."""
439
return self._readable_pipe.read(count)
732
bytes = osutils.until_no_eintr(self._readable_pipe.read, count)
733
self._report_activity(len(bytes), 'read')
442
737
class SmartSSHClientMedium(SmartClientStreamMedium):
443
738
"""A client medium using SSH."""
445
740
def __init__(self, host, port=None, username=None, password=None,
741
base=None, vendor=None, bzr_remote_path=None):
447
742
"""Creates a client that will connect on the first use.
449
744
:param vendor: An optional override for the ssh vendor to use. See
450
745
bzrlib.transport.ssh for details on ssh vendors.
452
SmartClientStreamMedium.__init__(self)
453
747
self._connected = False
454
748
self._host = host
455
749
self._password = password
456
750
self._port = port
457
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)
458
759
self._read_from = None
459
760
self._ssh_connection = None
460
761
self._vendor = vendor
461
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__,
463
777
def _accept_bytes(self, bytes):
464
778
"""See SmartClientStreamMedium.accept_bytes."""
465
779
self._ensure_connection()
466
self._write_to.write(bytes)
780
osutils.until_no_eintr(self._write_to.write, bytes)
781
self._report_activity(len(bytes), 'write')
468
783
def disconnect(self):
469
784
"""See SmartClientMedium.disconnect()."""
470
785
if not self._connected:
472
self._read_from.close()
473
self._write_to.close()
787
osutils.until_no_eintr(self._read_from.close)
788
osutils.until_no_eintr(self._write_to.close)
474
789
self._ssh_connection.close()
475
790
self._connected = False
530
852
"""Connect this medium if not already connected."""
531
853
if self._connected:
533
self._socket = socket.socket()
534
self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
535
result = self._socket.connect_ex((self._host, int(self._port)))
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]
537
886
raise errors.ConnectionError("failed to connect to %s:%d: %s" %
538
(self._host, self._port, os.strerror(result)))
887
(self._host, port, err_msg))
539
888
self._connected = True
541
890
def _flush(self):
542
891
"""See SmartClientStreamMedium._flush().
544
For TCP we do no flushing. We may want to turn off TCP_NODELAY and
893
For TCP we do no flushing. We may want to turn off TCP_NODELAY and
545
894
add a means to do a flush, but that can be done in the future.