~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/smart/medium.py

  • Committer: Robert Collins
  • Date: 2009-12-16 22:29:31 UTC
  • mto: This revision was merged to the branch mainline in revision 4920.
  • Revision ID: robertc@robertcollins.net-20091216222931-wbbn5ey4mwmpatwd
Review feedback.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2011 Canonical Ltd
 
1
# Copyright (C) 2006 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
24
24
bzrlib/transport/smart/__init__.py.
25
25
"""
26
26
 
 
27
import errno
27
28
import os
 
29
import socket
28
30
import sys
29
31
import urllib
30
32
 
31
 
import bzrlib
32
33
from bzrlib.lazy_import import lazy_import
33
34
lazy_import(globals(), """
34
 
import socket
35
 
import thread
 
35
import atexit
 
36
import threading
36
37
import weakref
37
38
 
38
39
from bzrlib import (
39
40
    debug,
40
41
    errors,
 
42
    symbol_versioning,
41
43
    trace,
42
44
    ui,
43
45
    urlutils,
45
47
from bzrlib.smart import client, protocol, request, vfs
46
48
from bzrlib.transport import ssh
47
49
""")
 
50
#usually already imported, and getting IllegalScoperReplacer on it here.
48
51
from bzrlib import osutils
49
52
 
50
 
# Throughout this module buffer size parameters are either limited to be at
51
 
# most _MAX_READ_SIZE, or are ignored and _MAX_READ_SIZE is used instead.
52
 
# For this module's purposes, MAX_SOCKET_CHUNK is a reasonable size for reads
53
 
# from non-sockets as well.
54
 
_MAX_READ_SIZE = osutils.MAX_SOCKET_CHUNK
 
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
 
57
 
55
58
 
56
59
def _get_protocol_factory_for_bytes(bytes):
57
60
    """Determine the right protocol factory for 'bytes'.
273
276
    def _serve_one_request_unguarded(self, protocol):
274
277
        while protocol.next_read_size():
275
278
            # We can safely try to read large chunks.  If there is less data
276
 
            # than MAX_SOCKET_CHUNK ready, the socket will just return a
277
 
            # short read immediately rather than block.
278
 
            bytes = self.read_bytes(osutils.MAX_SOCKET_CHUNK)
 
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)
279
282
            if bytes == '':
280
283
                self.finished = True
281
284
                return
284
287
        self._push_back(protocol.unused_data)
285
288
 
286
289
    def _read_bytes(self, desired_count):
287
 
        return osutils.read_bytes_from_socket(
288
 
            self.socket, self._report_activity)
 
290
        return _read_bytes_from_socket(
 
291
            self.socket.recv, desired_count, self._report_activity)
289
292
 
290
293
    def terminate_due_to_error(self):
291
294
        # TODO: This should log to a server log file, but no such thing
292
295
        # exists yet.  Andrew Bennetts 2006-09-29.
293
 
        self.socket.close()
 
296
        osutils.until_no_eintr(self.socket.close)
294
297
        self.finished = True
295
298
 
296
299
    def _write_out(self, bytes):
297
300
        tstart = osutils.timer_func()
298
301
        osutils.send_all(self.socket, bytes, self._report_activity)
299
302
        if 'hpss' in debug.debug_flags:
300
 
            thread_id = thread.get_ident()
 
303
            thread_id = threading.currentThread().ident
301
304
            trace.mutter('%12s: [%s] %d bytes to the socket in %.3fs'
302
305
                         % ('wrote', thread_id, len(bytes),
303
306
                            osutils.timer_func() - tstart))
331
334
            bytes_to_read = protocol.next_read_size()
332
335
            if bytes_to_read == 0:
333
336
                # Finished serving this request.
334
 
                self._out.flush()
 
337
                osutils.until_no_eintr(self._out.flush)
335
338
                return
336
339
            bytes = self.read_bytes(bytes_to_read)
337
340
            if bytes == '':
338
341
                # Connection has been closed.
339
342
                self.finished = True
340
 
                self._out.flush()
 
343
                osutils.until_no_eintr(self._out.flush)
341
344
                return
342
345
            protocol.accept_bytes(bytes)
343
346
 
344
347
    def _read_bytes(self, desired_count):
345
 
        return self._in.read(desired_count)
 
348
        return osutils.until_no_eintr(self._in.read, desired_count)
346
349
 
347
350
    def terminate_due_to_error(self):
348
351
        # TODO: This should log to a server log file, but no such thing
349
352
        # exists yet.  Andrew Bennetts 2006-09-29.
350
 
        self._out.close()
 
353
        osutils.until_no_eintr(self._out.close)
351
354
        self.finished = True
352
355
 
353
356
    def _write_out(self, bytes):
354
 
        self._out.write(bytes)
 
357
        osutils.until_no_eintr(self._out.write, bytes)
355
358
 
356
359
 
357
360
class SmartClientMediumRequest(object):
493
496
class _DebugCounter(object):
494
497
    """An object that counts the HPSS calls made to each client medium.
495
498
 
496
 
    When a medium is garbage-collected, or failing that when
497
 
    bzrlib.global_state exits, the total number of calls made on that medium
498
 
    are reported via trace.note.
 
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
 
501
    trace.note.
499
502
    """
500
503
 
501
504
    def __init__(self):
502
505
        self.counts = weakref.WeakKeyDictionary()
503
506
        client._SmartClient.hooks.install_named_hook(
504
507
            'call', self.increment_call_count, 'hpss call counter')
505
 
        bzrlib.global_state.cleanups.add_cleanup(self.flush_all)
 
508
        atexit.register(self.flush_all)
506
509
 
507
510
    def track(self, medium):
508
511
        """Start tracking calls made to a medium.
606
609
            # which is newer than a previously supplied older-than version.
607
610
            # This indicates that some smart verb call is not guarded
608
611
            # appropriately (it should simply not have been tried).
609
 
            trace.mutter(
 
612
            raise AssertionError(
610
613
                "_remember_remote_is_before(%r) called, but "
611
614
                "_remember_remote_is_before(%r) was called previously."
612
 
                , version_tuple, self._remote_version_is_before)
613
 
            if 'hpss' in debug.debug_flags:
614
 
                ui.ui_factory.show_warning(
615
 
                    "_remember_remote_is_before(%r) called, but "
616
 
                    "_remember_remote_is_before(%r) was called previously."
617
 
                    % (version_tuple, self._remote_version_is_before))
618
 
            return
 
615
                % (version_tuple, self._remote_version_is_before))
619
616
        self._remote_version_is_before = version_tuple
620
617
 
621
618
    def protocol_version(self):
723
720
 
724
721
    def _accept_bytes(self, bytes):
725
722
        """See SmartClientStreamMedium.accept_bytes."""
726
 
        self._writeable_pipe.write(bytes)
 
723
        osutils.until_no_eintr(self._writeable_pipe.write, bytes)
727
724
        self._report_activity(len(bytes), 'write')
728
725
 
729
726
    def _flush(self):
730
727
        """See SmartClientStreamMedium._flush()."""
731
 
        self._writeable_pipe.flush()
 
728
        osutils.until_no_eintr(self._writeable_pipe.flush)
732
729
 
733
730
    def _read_bytes(self, count):
734
731
        """See SmartClientStreamMedium._read_bytes."""
735
 
        bytes_to_read = min(count, _MAX_READ_SIZE)
736
 
        bytes = self._readable_pipe.read(bytes_to_read)
 
732
        bytes = osutils.until_no_eintr(self._readable_pipe.read, count)
737
733
        self._report_activity(len(bytes), 'read')
738
734
        return bytes
739
735
 
740
736
 
741
 
class SSHParams(object):
742
 
    """A set of parameters for starting a remote bzr via SSH."""
 
737
class SmartSSHClientMedium(SmartClientStreamMedium):
 
738
    """A client medium using SSH."""
743
739
 
744
740
    def __init__(self, host, port=None, username=None, password=None,
745
 
            bzr_remote_path='bzr'):
746
 
        self.host = host
747
 
        self.port = port
748
 
        self.username = username
749
 
        self.password = password
750
 
        self.bzr_remote_path = bzr_remote_path
751
 
 
752
 
 
753
 
class SmartSSHClientMedium(SmartClientStreamMedium):
754
 
    """A client medium using SSH.
755
 
    
756
 
    It delegates IO to a SmartClientSocketMedium or
757
 
    SmartClientAlreadyConnectedSocketMedium (depending on platform).
758
 
    """
759
 
 
760
 
    def __init__(self, base, ssh_params, vendor=None):
 
741
            base=None, vendor=None, bzr_remote_path=None):
761
742
        """Creates a client that will connect on the first use.
762
743
 
763
 
        :param ssh_params: A SSHParams instance.
764
744
        :param vendor: An optional override for the ssh vendor to use. See
765
745
            bzrlib.transport.ssh for details on ssh vendors.
766
746
        """
767
 
        self._real_medium = None
768
 
        self._ssh_params = ssh_params
769
 
        # for the benefit of progress making a short description of this
770
 
        # transport
771
 
        self._scheme = 'bzr+ssh'
 
747
        self._connected = False
 
748
        self._host = host
 
749
        self._password = password
 
750
        self._port = port
 
751
        self._username = username
772
752
        # SmartClientStreamMedium stores the repr of this object in its
773
753
        # _DebugCounter so we have to store all the values used in our repr
774
754
        # method before calling the super init.
775
755
        SmartClientStreamMedium.__init__(self, base)
 
756
        self._read_from = None
 
757
        self._ssh_connection = None
776
758
        self._vendor = vendor
777
 
        self._ssh_connection = None
 
759
        self._write_to = None
 
760
        self._bzr_remote_path = bzr_remote_path
 
761
        # for the benefit of progress making a short description of this
 
762
        # transport
 
763
        self._scheme = 'bzr+ssh'
778
764
 
779
765
    def __repr__(self):
780
 
        if self._ssh_params.port is None:
781
 
            maybe_port = ''
782
 
        else:
783
 
            maybe_port = ':%s' % self._ssh_params.port
784
 
        return "%s(%s://%s@%s%s/)" % (
 
766
        return "%s(connected=%r, username=%r, host=%r, port=%r)" % (
785
767
            self.__class__.__name__,
786
 
            self._scheme,
787
 
            self._ssh_params.username,
788
 
            self._ssh_params.host,
789
 
            maybe_port)
 
768
            self._connected,
 
769
            self._username,
 
770
            self._host,
 
771
            self._port)
790
772
 
791
773
    def _accept_bytes(self, bytes):
792
774
        """See SmartClientStreamMedium.accept_bytes."""
793
775
        self._ensure_connection()
794
 
        self._real_medium.accept_bytes(bytes)
 
776
        osutils.until_no_eintr(self._write_to.write, bytes)
 
777
        self._report_activity(len(bytes), 'write')
795
778
 
796
779
    def disconnect(self):
797
780
        """See SmartClientMedium.disconnect()."""
798
 
        if self._real_medium is not None:
799
 
            self._real_medium.disconnect()
800
 
            self._real_medium = None
801
 
        if self._ssh_connection is not None:
802
 
            self._ssh_connection.close()
803
 
            self._ssh_connection = None
 
781
        if not self._connected:
 
782
            return
 
783
        osutils.until_no_eintr(self._read_from.close)
 
784
        osutils.until_no_eintr(self._write_to.close)
 
785
        self._ssh_connection.close()
 
786
        self._connected = False
804
787
 
805
788
    def _ensure_connection(self):
806
789
        """Connect this medium if not already connected."""
807
 
        if self._real_medium is not None:
 
790
        if self._connected:
808
791
            return
809
792
        if self._vendor is None:
810
793
            vendor = ssh._get_ssh_vendor()
811
794
        else:
812
795
            vendor = self._vendor
813
 
        self._ssh_connection = vendor.connect_ssh(self._ssh_params.username,
814
 
                self._ssh_params.password, self._ssh_params.host,
815
 
                self._ssh_params.port,
816
 
                command=[self._ssh_params.bzr_remote_path, 'serve', '--inet',
 
796
        self._ssh_connection = vendor.connect_ssh(self._username,
 
797
                self._password, self._host, self._port,
 
798
                command=[self._bzr_remote_path, 'serve', '--inet',
817
799
                         '--directory=/', '--allow-writes'])
818
 
        io_kind, io_object = self._ssh_connection.get_sock_or_pipes()
819
 
        if io_kind == 'socket':
820
 
            self._real_medium = SmartClientAlreadyConnectedSocketMedium(
821
 
                self.base, io_object)
822
 
        elif io_kind == 'pipes':
823
 
            read_from, write_to = io_object
824
 
            self._real_medium = SmartSimplePipesClientMedium(
825
 
                read_from, write_to, self.base)
826
 
        else:
827
 
            raise AssertionError(
828
 
                "Unexpected io_kind %r from %r"
829
 
                % (io_kind, self._ssh_connection))
 
800
        self._read_from, self._write_to = \
 
801
            self._ssh_connection.get_filelike_channels()
 
802
        self._connected = True
830
803
 
831
804
    def _flush(self):
832
805
        """See SmartClientStreamMedium._flush()."""
833
 
        self._real_medium._flush()
 
806
        self._write_to.flush()
834
807
 
835
808
    def _read_bytes(self, count):
836
809
        """See SmartClientStreamMedium.read_bytes."""
837
 
        if self._real_medium is None:
 
810
        if not self._connected:
838
811
            raise errors.MediumNotConnected(self)
839
 
        return self._real_medium.read_bytes(count)
 
812
        bytes_to_read = min(count, _MAX_READ_SIZE)
 
813
        bytes = osutils.until_no_eintr(self._read_from.read, bytes_to_read)
 
814
        self._report_activity(len(bytes), 'read')
 
815
        return bytes
840
816
 
841
817
 
842
818
# Port 4155 is the default port for bzr://, registered with IANA.
844
820
BZR_DEFAULT_PORT = 4155
845
821
 
846
822
 
847
 
class SmartClientSocketMedium(SmartClientStreamMedium):
848
 
    """A client medium using a socket.
849
 
    
850
 
    This class isn't usable directly.  Use one of its subclasses instead.
851
 
    """
 
823
class SmartTCPClientMedium(SmartClientStreamMedium):
 
824
    """A client medium using TCP."""
852
825
 
853
 
    def __init__(self, base):
 
826
    def __init__(self, host, port, base):
 
827
        """Creates a client that will connect on the first use."""
854
828
        SmartClientStreamMedium.__init__(self, base)
 
829
        self._connected = False
 
830
        self._host = host
 
831
        self._port = port
855
832
        self._socket = None
856
 
        self._connected = False
857
833
 
858
834
    def _accept_bytes(self, bytes):
859
835
        """See SmartClientMedium.accept_bytes."""
860
836
        self._ensure_connection()
861
837
        osutils.send_all(self._socket, bytes, self._report_activity)
862
838
 
863
 
    def _ensure_connection(self):
864
 
        """Connect this medium if not already connected."""
865
 
        raise NotImplementedError(self._ensure_connection)
866
 
 
867
 
    def _flush(self):
868
 
        """See SmartClientStreamMedium._flush().
869
 
 
870
 
        For sockets we do no flushing. For TCP sockets we may want to turn off
871
 
        TCP_NODELAY and add a means to do a flush, but that can be done in the
872
 
        future.
873
 
        """
874
 
 
875
 
    def _read_bytes(self, count):
876
 
        """See SmartClientMedium.read_bytes."""
877
 
        if not self._connected:
878
 
            raise errors.MediumNotConnected(self)
879
 
        return osutils.read_bytes_from_socket(
880
 
            self._socket, self._report_activity)
881
 
 
882
839
    def disconnect(self):
883
840
        """See SmartClientMedium.disconnect()."""
884
841
        if not self._connected:
885
842
            return
886
 
        self._socket.close()
 
843
        osutils.until_no_eintr(self._socket.close)
887
844
        self._socket = None
888
845
        self._connected = False
889
846
 
890
 
 
891
 
class SmartTCPClientMedium(SmartClientSocketMedium):
892
 
    """A client medium that creates a TCP connection."""
893
 
 
894
 
    def __init__(self, host, port, base):
895
 
        """Creates a client that will connect on the first use."""
896
 
        SmartClientSocketMedium.__init__(self, base)
897
 
        self._host = host
898
 
        self._port = port
899
 
 
900
847
    def _ensure_connection(self):
901
848
        """Connect this medium if not already connected."""
902
849
        if self._connected:
936
883
                    (self._host, port, err_msg))
937
884
        self._connected = True
938
885
 
939
 
 
940
 
class SmartClientAlreadyConnectedSocketMedium(SmartClientSocketMedium):
941
 
    """A client medium for an already connected socket.
942
 
    
943
 
    Note that this class will assume it "owns" the socket, so it will close it
944
 
    when its disconnect method is called.
945
 
    """
946
 
 
947
 
    def __init__(self, base, sock):
948
 
        SmartClientSocketMedium.__init__(self, base)
949
 
        self._socket = sock
950
 
        self._connected = True
951
 
 
952
 
    def _ensure_connection(self):
953
 
        # Already connected, by definition!  So nothing to do.
954
 
        pass
 
886
    def _flush(self):
 
887
        """See SmartClientStreamMedium._flush().
 
888
 
 
889
        For TCP we do no flushing. We may want to turn off TCP_NODELAY and
 
890
        add a means to do a flush, but that can be done in the future.
 
891
        """
 
892
 
 
893
    def _read_bytes(self, count):
 
894
        """See SmartClientMedium.read_bytes."""
 
895
        if not self._connected:
 
896
            raise errors.MediumNotConnected(self)
 
897
        return _read_bytes_from_socket(
 
898
            self._socket.recv, count, self._report_activity)
955
899
 
956
900
 
957
901
class SmartClientStreamMediumRequest(SmartClientMediumRequest):
994
938
        self._medium._flush()
995
939
 
996
940
 
 
941
def _read_bytes_from_socket(sock, desired_count, report_activity):
 
942
    # We ignore the desired_count because on sockets it's more efficient to
 
943
    # read large chunks (of _MAX_READ_SIZE bytes) at a time.
 
944
    try:
 
945
        bytes = osutils.until_no_eintr(sock, _MAX_READ_SIZE)
 
946
    except socket.error, e:
 
947
        if len(e.args) and e.args[0] in (errno.ECONNRESET, 10054):
 
948
            # The connection was closed by the other side.  Callers expect an
 
949
            # empty string to signal end-of-stream.
 
950
            bytes = ''
 
951
        else:
 
952
            raise
 
953
    else:
 
954
        report_activity(len(bytes), 'read')
 
955
    return bytes
 
956