24
24
bzrlib/transport/smart/__init__.py.
33
from bzrlib.lazy_import import lazy_import
34
lazy_import(globals(), """
31
from bzrlib import errors
32
from bzrlib.smart.protocol import (
34
SmartServerRequestProtocolOne,
35
SmartServerRequestProtocolTwo,
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):
39
from bzrlib.transport import ssh
40
except errors.ParamikoNotPresent:
41
# no paramiko. SmartSSHClientMedium will break.
45
class SmartServerStreamMedium(object):
182
46
"""Handles smart commands coming over a stream.
184
48
The stream may be a pipe connected to sshd, or a tcp socket, or an
252
113
"""Called when an unhandled exception from the protocol occurs."""
253
114
raise NotImplementedError(self.terminate_due_to_error)
255
def _read_bytes(self, desired_count):
116
def _get_bytes(self, desired_count):
256
117
"""Get some bytes from the medium.
258
119
:param desired_count: number of bytes we want to read.
260
raise NotImplementedError(self._read_bytes)
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.
263
142
class SmartServerSocketStreamMedium(SmartServerStreamMedium):
265
def __init__(self, sock, backing_transport, root_client_path='/'):
144
def __init__(self, sock, backing_transport):
268
147
:param sock: the socket the server will read from. It will be put
269
148
into blocking mode.
271
SmartServerStreamMedium.__init__(
272
self, backing_transport, root_client_path=root_client_path)
150
SmartServerStreamMedium.__init__(self, backing_transport)
273
152
sock.setblocking(True)
274
153
self.socket = sock
276
155
def _serve_one_request_unguarded(self, protocol):
277
156
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)
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)
293
174
def terminate_due_to_error(self):
175
"""Called when an unhandled exception from the protocol occurs."""
294
176
# TODO: This should log to a server log file, but no such thing
295
177
# exists yet. Andrew Bennetts 2006-09-29.
296
osutils.until_no_eintr(self.socket.close)
297
179
self.finished = True
299
181
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))
182
self.socket.sendall(bytes)
309
185
class SmartServerPipeStreamMedium(SmartServerStreamMedium):
464
337
return self._read_bytes(count)
466
339
def _read_bytes(self, count):
467
"""Helper for SmartClientMediumRequest.read_bytes.
340
"""Helper for read_bytes.
469
342
read_bytes checks the state of the request to determing if bytes
470
343
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)
346
raise NotImplementedError(self._read_bytes)
478
348
def read_line(self):
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.")
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')
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):
367
class SmartClientMedium(object):
559
368
"""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
370
def disconnect(self):
654
371
"""If this medium maintains a persistent connection, close it.
656
373
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
377
class SmartClientStreamMedium(SmartClientMedium):
672
378
"""Stream based medium common class.
707
412
return SmartClientStreamMediumRequest(self)
414
def read_bytes(self, count):
415
return self._read_bytes(count)
710
418
class SmartSimplePipesClientMedium(SmartClientStreamMedium):
711
419
"""A client medium using simple pipes.
713
421
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)
424
def __init__(self, readable_pipe, writeable_pipe):
425
SmartClientStreamMedium.__init__(self)
718
426
self._readable_pipe = readable_pipe
719
427
self._writeable_pipe = writeable_pipe
721
429
def _accept_bytes(self, bytes):
722
430
"""See SmartClientStreamMedium.accept_bytes."""
723
osutils.until_no_eintr(self._writeable_pipe.write, bytes)
724
self._report_activity(len(bytes), 'write')
431
self._writeable_pipe.write(bytes)
726
433
def _flush(self):
727
434
"""See SmartClientStreamMedium._flush()."""
728
osutils.until_no_eintr(self._writeable_pipe.flush)
435
self._writeable_pipe.flush()
730
437
def _read_bytes(self, count):
731
438
"""See SmartClientStreamMedium._read_bytes."""
732
bytes = osutils.until_no_eintr(self._readable_pipe.read, count)
733
self._report_activity(len(bytes), 'read')
439
return self._readable_pipe.read(count)
737
442
class SmartSSHClientMedium(SmartClientStreamMedium):
738
443
"""A client medium using SSH."""
740
445
def __init__(self, host, port=None, username=None, password=None,
741
base=None, vendor=None, bzr_remote_path=None):
742
447
"""Creates a client that will connect on the first use.
744
449
:param vendor: An optional override for the ssh vendor to use. See
745
450
bzrlib.transport.ssh for details on ssh vendors.
452
SmartClientStreamMedium.__init__(self)
747
453
self._connected = False
748
454
self._host = host
749
455
self._password = password
750
456
self._port = port
751
457
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)
756
458
self._read_from = None
757
459
self._ssh_connection = None
758
460
self._vendor = vendor
759
461
self._write_to = None
760
self._bzr_remote_path = bzr_remote_path
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__,
773
463
def _accept_bytes(self, bytes):
774
464
"""See SmartClientStreamMedium.accept_bytes."""
775
465
self._ensure_connection()
776
osutils.until_no_eintr(self._write_to.write, bytes)
777
self._report_activity(len(bytes), 'write')
466
self._write_to.write(bytes)
779
468
def disconnect(self):
780
469
"""See SmartClientMedium.disconnect()."""
781
470
if not self._connected:
783
osutils.until_no_eintr(self._read_from.close)
784
osutils.until_no_eintr(self._write_to.close)
472
self._read_from.close()
473
self._write_to.close()
785
474
self._ssh_connection.close()
786
475
self._connected = False
848
530
"""Connect this medium if not already connected."""
849
531
if self._connected:
851
if self._port is None:
852
port = BZR_DEFAULT_PORT
854
port = int(self._port)
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:
876
# socket errors either have a (string) or (errno, string) as their
878
if type(err.args) is str:
881
err_msg = err.args[1]
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)))
882
537
raise errors.ConnectionError("failed to connect to %s:%d: %s" %
883
(self._host, port, err_msg))
538
(self._host, self._port, os.strerror(result)))
884
539
self._connected = True
886
541
def _flush(self):
887
542
"""See SmartClientStreamMedium._flush().
889
For TCP we do no flushing. We may want to turn off TCP_NODELAY and
544
For TCP we do no flushing. We may want to turn off TCP_NODELAY and
890
545
add a means to do a flush, but that can be done in the future.