/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/smart/medium.py

  • Committer: Ian Clatworthy
  • Date: 2009-07-02 08:26:00 UTC
  • mto: (4527.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 4529.
  • Revision ID: ian.clatworthy@canonical.com-20090702082600-qwb1evvvfa8ctnye
first draft of a 2.0 Upgrade Guide

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 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
36
import weakref
37
 
 
38
37
from bzrlib import (
39
38
    debug,
40
39
    errors,
 
40
    osutils,
41
41
    symbol_versioning,
42
42
    trace,
43
43
    ui,
46
46
from bzrlib.smart import client, protocol, request, vfs
47
47
from bzrlib.transport import ssh
48
48
""")
49
 
from bzrlib import osutils
50
 
 
51
 
# Throughout this module buffer size parameters are either limited to be at
52
 
# most _MAX_READ_SIZE, or are ignored and _MAX_READ_SIZE is used instead.
53
 
# For this module's purposes, MAX_SOCKET_CHUNK is a reasonable size for reads
54
 
# from non-sockets as well.
55
 
_MAX_READ_SIZE = osutils.MAX_SOCKET_CHUNK
 
49
 
 
50
 
 
51
# We must not read any more than 64k at a time so we don't risk "no buffer
 
52
# space available" errors on some platforms.  Windows in particular is likely
 
53
# to give error 10053 or 10055 if we read more than 64k from a socket.
 
54
_MAX_READ_SIZE = 64 * 1024
 
55
 
56
56
 
57
57
def _get_protocol_factory_for_bytes(bytes):
58
58
    """Determine the right protocol factory for 'bytes'.
274
274
    def _serve_one_request_unguarded(self, protocol):
275
275
        while protocol.next_read_size():
276
276
            # We can safely try to read large chunks.  If there is less data
277
 
            # than MAX_SOCKET_CHUNK ready, the socket will just return a
278
 
            # short read immediately rather than block.
279
 
            bytes = self.read_bytes(osutils.MAX_SOCKET_CHUNK)
 
277
            # than _MAX_READ_SIZE ready, the socket wil just return a short
 
278
            # read immediately rather than block.
 
279
            bytes = self.read_bytes(_MAX_READ_SIZE)
280
280
            if bytes == '':
281
281
                self.finished = True
282
282
                return
285
285
        self._push_back(protocol.unused_data)
286
286
 
287
287
    def _read_bytes(self, desired_count):
288
 
        return osutils.read_bytes_from_socket(
289
 
            self.socket, self._report_activity)
 
288
        return _read_bytes_from_socket(
 
289
            self.socket.recv, desired_count, self._report_activity)
290
290
 
291
291
    def terminate_due_to_error(self):
292
292
        # TODO: This should log to a server log file, but no such thing
295
295
        self.finished = True
296
296
 
297
297
    def _write_out(self, bytes):
298
 
        tstart = osutils.timer_func()
299
298
        osutils.send_all(self.socket, bytes, self._report_activity)
300
 
        if 'hpss' in debug.debug_flags:
301
 
            thread_id = thread.get_ident()
302
 
            trace.mutter('%12s: [%s] %d bytes to the socket in %.3fs'
303
 
                         % ('wrote', thread_id, len(bytes),
304
 
                            osutils.timer_func() - tstart))
305
299
 
306
300
 
307
301
class SmartServerPipeStreamMedium(SmartServerStreamMedium):
478
472
        if not line.endswith('\n'):
479
473
            # end of file encountered reading from server
480
474
            raise errors.ConnectionReset(
481
 
                "Unexpected end of message. Please check connectivity "
482
 
                "and permissions, and report a bug if problems persist.")
 
475
                "please check connectivity and permissions")
483
476
        return line
484
477
 
485
478
    def _read_line(self):
494
487
class _DebugCounter(object):
495
488
    """An object that counts the HPSS calls made to each client medium.
496
489
 
497
 
    When a medium is garbage-collected, or failing that when
498
 
    bzrlib.global_state exits, the total number of calls made on that medium
499
 
    are reported via trace.note.
 
490
    When a medium is garbage-collected, or failing that when atexit functions
 
491
    are run, the total number of calls made on that medium are reported via
 
492
    trace.note.
500
493
    """
501
494
 
502
495
    def __init__(self):
503
496
        self.counts = weakref.WeakKeyDictionary()
504
497
        client._SmartClient.hooks.install_named_hook(
505
498
            'call', self.increment_call_count, 'hpss call counter')
506
 
        bzrlib.global_state.cleanups.add_cleanup(self.flush_all)
 
499
        atexit.register(self.flush_all)
507
500
 
508
501
    def track(self, medium):
509
502
        """Start tracking calls made to a medium.
525
518
        # Increment the count in the WeakKeyDictionary
526
519
        value = self.counts[params.medium]
527
520
        value['count'] += 1
528
 
        try:
529
 
            request_method = request.request_handlers.get(params.method)
530
 
        except KeyError:
531
 
            # A method we don't know about doesn't count as a VFS method.
532
 
            return
 
521
        request_method = request.request_handlers.get(params.method)
533
522
        if issubclass(request_method, vfs.VfsRequest):
534
523
            value['vfs_count'] += 1
535
524
 
607
596
            # which is newer than a previously supplied older-than version.
608
597
            # This indicates that some smart verb call is not guarded
609
598
            # appropriately (it should simply not have been tried).
610
 
            trace.mutter(
 
599
            raise AssertionError(
611
600
                "_remember_remote_is_before(%r) called, but "
612
601
                "_remember_remote_is_before(%r) was called previously."
613
 
                , version_tuple, self._remote_version_is_before)
614
 
            if 'hpss' in debug.debug_flags:
615
 
                ui.ui_factory.show_warning(
616
 
                    "_remember_remote_is_before(%r) called, but "
617
 
                    "_remember_remote_is_before(%r) was called previously."
618
 
                    % (version_tuple, self._remote_version_is_before))
619
 
            return
 
602
                % (version_tuple, self._remote_version_is_before))
620
603
        self._remote_version_is_before = version_tuple
621
604
 
622
605
    def protocol_version(self):
733
716
 
734
717
    def _read_bytes(self, count):
735
718
        """See SmartClientStreamMedium._read_bytes."""
736
 
        bytes_to_read = min(count, _MAX_READ_SIZE)
737
 
        bytes = self._readable_pipe.read(bytes_to_read)
 
719
        bytes = self._readable_pipe.read(count)
738
720
        self._report_activity(len(bytes), 'read')
739
721
        return bytes
740
722
 
741
723
 
742
 
class SSHParams(object):
743
 
    """A set of parameters for starting a remote bzr via SSH."""
 
724
class SmartSSHClientMedium(SmartClientStreamMedium):
 
725
    """A client medium using SSH."""
744
726
 
745
727
    def __init__(self, host, port=None, username=None, password=None,
746
 
            bzr_remote_path='bzr'):
747
 
        self.host = host
748
 
        self.port = port
749
 
        self.username = username
750
 
        self.password = password
751
 
        self.bzr_remote_path = bzr_remote_path
752
 
 
753
 
 
754
 
class SmartSSHClientMedium(SmartClientStreamMedium):
755
 
    """A client medium using SSH.
756
 
    
757
 
    It delegates IO to a SmartClientSocketMedium or
758
 
    SmartClientAlreadyConnectedSocketMedium (depending on platform).
759
 
    """
760
 
 
761
 
    def __init__(self, base, ssh_params, vendor=None):
 
728
            base=None, vendor=None, bzr_remote_path=None):
762
729
        """Creates a client that will connect on the first use.
763
730
 
764
 
        :param ssh_params: A SSHParams instance.
765
731
        :param vendor: An optional override for the ssh vendor to use. See
766
732
            bzrlib.transport.ssh for details on ssh vendors.
767
733
        """
768
 
        self._real_medium = None
769
 
        self._ssh_params = ssh_params
770
 
        # for the benefit of progress making a short description of this
771
 
        # transport
772
 
        self._scheme = 'bzr+ssh'
 
734
        self._connected = False
 
735
        self._host = host
 
736
        self._password = password
 
737
        self._port = port
 
738
        self._username = username
773
739
        # SmartClientStreamMedium stores the repr of this object in its
774
740
        # _DebugCounter so we have to store all the values used in our repr
775
741
        # method before calling the super init.
776
742
        SmartClientStreamMedium.__init__(self, base)
 
743
        self._read_from = None
 
744
        self._ssh_connection = None
777
745
        self._vendor = vendor
778
 
        self._ssh_connection = None
 
746
        self._write_to = None
 
747
        self._bzr_remote_path = bzr_remote_path
 
748
        # for the benefit of progress making a short description of this
 
749
        # transport
 
750
        self._scheme = 'bzr+ssh'
779
751
 
780
752
    def __repr__(self):
781
 
        if self._ssh_params.port is None:
782
 
            maybe_port = ''
783
 
        else:
784
 
            maybe_port = ':%s' % self._ssh_params.port
785
 
        return "%s(%s://%s@%s%s/)" % (
 
753
        return "%s(connected=%r, username=%r, host=%r, port=%r)" % (
786
754
            self.__class__.__name__,
787
 
            self._scheme,
788
 
            self._ssh_params.username,
789
 
            self._ssh_params.host,
790
 
            maybe_port)
 
755
            self._connected,
 
756
            self._username,
 
757
            self._host,
 
758
            self._port)
791
759
 
792
760
    def _accept_bytes(self, bytes):
793
761
        """See SmartClientStreamMedium.accept_bytes."""
794
762
        self._ensure_connection()
795
 
        self._real_medium.accept_bytes(bytes)
 
763
        self._write_to.write(bytes)
 
764
        self._report_activity(len(bytes), 'write')
796
765
 
797
766
    def disconnect(self):
798
767
        """See SmartClientMedium.disconnect()."""
799
 
        if self._real_medium is not None:
800
 
            self._real_medium.disconnect()
801
 
            self._real_medium = None
802
 
        if self._ssh_connection is not None:
803
 
            self._ssh_connection.close()
804
 
            self._ssh_connection = None
 
768
        if not self._connected:
 
769
            return
 
770
        self._read_from.close()
 
771
        self._write_to.close()
 
772
        self._ssh_connection.close()
 
773
        self._connected = False
805
774
 
806
775
    def _ensure_connection(self):
807
776
        """Connect this medium if not already connected."""
808
 
        if self._real_medium is not None:
 
777
        if self._connected:
809
778
            return
810
779
        if self._vendor is None:
811
780
            vendor = ssh._get_ssh_vendor()
812
781
        else:
813
782
            vendor = self._vendor
814
 
        self._ssh_connection = vendor.connect_ssh(self._ssh_params.username,
815
 
                self._ssh_params.password, self._ssh_params.host,
816
 
                self._ssh_params.port,
817
 
                command=[self._ssh_params.bzr_remote_path, 'serve', '--inet',
 
783
        self._ssh_connection = vendor.connect_ssh(self._username,
 
784
                self._password, self._host, self._port,
 
785
                command=[self._bzr_remote_path, 'serve', '--inet',
818
786
                         '--directory=/', '--allow-writes'])
819
 
        io_kind, io_object = self._ssh_connection.get_sock_or_pipes()
820
 
        if io_kind == 'socket':
821
 
            self._real_medium = SmartClientAlreadyConnectedSocketMedium(
822
 
                self.base, io_object)
823
 
        elif io_kind == 'pipes':
824
 
            read_from, write_to = io_object
825
 
            self._real_medium = SmartSimplePipesClientMedium(
826
 
                read_from, write_to, self.base)
827
 
        else:
828
 
            raise AssertionError(
829
 
                "Unexpected io_kind %r from %r"
830
 
                % (io_kind, self._ssh_connection))
 
787
        self._read_from, self._write_to = \
 
788
            self._ssh_connection.get_filelike_channels()
 
789
        self._connected = True
831
790
 
832
791
    def _flush(self):
833
792
        """See SmartClientStreamMedium._flush()."""
834
 
        self._real_medium._flush()
 
793
        self._write_to.flush()
835
794
 
836
795
    def _read_bytes(self, count):
837
796
        """See SmartClientStreamMedium.read_bytes."""
838
 
        if self._real_medium is None:
 
797
        if not self._connected:
839
798
            raise errors.MediumNotConnected(self)
840
 
        return self._real_medium.read_bytes(count)
 
799
        bytes_to_read = min(count, _MAX_READ_SIZE)
 
800
        bytes = self._read_from.read(bytes_to_read)
 
801
        self._report_activity(len(bytes), 'read')
 
802
        return bytes
841
803
 
842
804
 
843
805
# Port 4155 is the default port for bzr://, registered with IANA.
845
807
BZR_DEFAULT_PORT = 4155
846
808
 
847
809
 
848
 
class SmartClientSocketMedium(SmartClientStreamMedium):
849
 
    """A client medium using a socket.
850
 
    
851
 
    This class isn't usable directly.  Use one of its subclasses instead.
852
 
    """
 
810
class SmartTCPClientMedium(SmartClientStreamMedium):
 
811
    """A client medium using TCP."""
853
812
 
854
 
    def __init__(self, base):
 
813
    def __init__(self, host, port, base):
 
814
        """Creates a client that will connect on the first use."""
855
815
        SmartClientStreamMedium.__init__(self, base)
 
816
        self._connected = False
 
817
        self._host = host
 
818
        self._port = port
856
819
        self._socket = None
857
 
        self._connected = False
858
820
 
859
821
    def _accept_bytes(self, bytes):
860
822
        """See SmartClientMedium.accept_bytes."""
861
823
        self._ensure_connection()
862
824
        osutils.send_all(self._socket, bytes, self._report_activity)
863
825
 
864
 
    def _ensure_connection(self):
865
 
        """Connect this medium if not already connected."""
866
 
        raise NotImplementedError(self._ensure_connection)
867
 
 
868
 
    def _flush(self):
869
 
        """See SmartClientStreamMedium._flush().
870
 
 
871
 
        For sockets we do no flushing. For TCP sockets we may want to turn off
872
 
        TCP_NODELAY and add a means to do a flush, but that can be done in the
873
 
        future.
874
 
        """
875
 
 
876
 
    def _read_bytes(self, count):
877
 
        """See SmartClientMedium.read_bytes."""
878
 
        if not self._connected:
879
 
            raise errors.MediumNotConnected(self)
880
 
        return osutils.read_bytes_from_socket(
881
 
            self._socket, self._report_activity)
882
 
 
883
826
    def disconnect(self):
884
827
        """See SmartClientMedium.disconnect()."""
885
828
        if not self._connected:
888
831
        self._socket = None
889
832
        self._connected = False
890
833
 
891
 
 
892
 
class SmartTCPClientMedium(SmartClientSocketMedium):
893
 
    """A client medium that creates a TCP connection."""
894
 
 
895
 
    def __init__(self, host, port, base):
896
 
        """Creates a client that will connect on the first use."""
897
 
        SmartClientSocketMedium.__init__(self, base)
898
 
        self._host = host
899
 
        self._port = port
900
 
 
901
834
    def _ensure_connection(self):
902
835
        """Connect this medium if not already connected."""
903
836
        if self._connected:
937
870
                    (self._host, port, err_msg))
938
871
        self._connected = True
939
872
 
940
 
 
941
 
class SmartClientAlreadyConnectedSocketMedium(SmartClientSocketMedium):
942
 
    """A client medium for an already connected socket.
943
 
    
944
 
    Note that this class will assume it "owns" the socket, so it will close it
945
 
    when its disconnect method is called.
946
 
    """
947
 
 
948
 
    def __init__(self, base, sock):
949
 
        SmartClientSocketMedium.__init__(self, base)
950
 
        self._socket = sock
951
 
        self._connected = True
952
 
 
953
 
    def _ensure_connection(self):
954
 
        # Already connected, by definition!  So nothing to do.
955
 
        pass
 
873
    def _flush(self):
 
874
        """See SmartClientStreamMedium._flush().
 
875
 
 
876
        For TCP we do no flushing. We may want to turn off TCP_NODELAY and
 
877
        add a means to do a flush, but that can be done in the future.
 
878
        """
 
879
 
 
880
    def _read_bytes(self, count):
 
881
        """See SmartClientMedium.read_bytes."""
 
882
        if not self._connected:
 
883
            raise errors.MediumNotConnected(self)
 
884
        return _read_bytes_from_socket(
 
885
            self._socket.recv, count, self._report_activity)
956
886
 
957
887
 
958
888
class SmartClientStreamMediumRequest(SmartClientMediumRequest):
995
925
        self._medium._flush()
996
926
 
997
927
 
 
928
def _read_bytes_from_socket(sock, desired_count, report_activity):
 
929
    # We ignore the desired_count because on sockets it's more efficient to
 
930
    # read large chunks (of _MAX_READ_SIZE bytes) at a time.
 
931
    try:
 
932
        bytes = osutils.until_no_eintr(sock, _MAX_READ_SIZE)
 
933
    except socket.error, e:
 
934
        if len(e.args) and e.args[0] in (errno.ECONNRESET, 10054):
 
935
            # The connection was closed by the other side.  Callers expect an
 
936
            # empty string to signal end-of-stream.
 
937
            bytes = ''
 
938
        else:
 
939
            raise
 
940
    else:
 
941
        report_activity(len(bytes), 'read')
 
942
    return bytes
 
943