/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: Canonical.com Patch Queue Manager
  • Date: 2009-12-18 10:09:49 UTC
  • mfrom: (4871.5.4 admin-guide-submit)
  • Revision ID: pqm@pqm.ubuntu.com-20091218100949-2c1ityvnbqjtdf3g
(nmb) Add backup section to admin-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
import threading
36
37
import weakref
37
38
 
38
39
from bzrlib import (
46
47
from bzrlib.smart import client, protocol, request, vfs
47
48
from bzrlib.transport import ssh
48
49
""")
 
50
#usually already imported, and getting IllegalScoperReplacer on it here.
49
51
from bzrlib import osutils
50
52
 
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
 
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
 
56
58
 
57
59
def _get_protocol_factory_for_bytes(bytes):
58
60
    """Determine the right protocol factory for 'bytes'.
274
276
    def _serve_one_request_unguarded(self, protocol):
275
277
        while protocol.next_read_size():
276
278
            # 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)
 
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)
280
282
            if bytes == '':
281
283
                self.finished = True
282
284
                return
285
287
        self._push_back(protocol.unused_data)
286
288
 
287
289
    def _read_bytes(self, desired_count):
288
 
        return osutils.read_bytes_from_socket(
289
 
            self.socket, self._report_activity)
 
290
        return _read_bytes_from_socket(
 
291
            self.socket.recv, desired_count, self._report_activity)
290
292
 
291
293
    def terminate_due_to_error(self):
292
294
        # TODO: This should log to a server log file, but no such thing
293
295
        # exists yet.  Andrew Bennetts 2006-09-29.
294
 
        self.socket.close()
 
296
        osutils.until_no_eintr(self.socket.close)
295
297
        self.finished = True
296
298
 
297
299
    def _write_out(self, bytes):
298
300
        tstart = osutils.timer_func()
299
301
        osutils.send_all(self.socket, bytes, self._report_activity)
300
302
        if 'hpss' in debug.debug_flags:
301
 
            thread_id = thread.get_ident()
 
303
            thread_id = threading.currentThread().ident
302
304
            trace.mutter('%12s: [%s] %d bytes to the socket in %.3fs'
303
305
                         % ('wrote', thread_id, len(bytes),
304
306
                            osutils.timer_func() - tstart))
332
334
            bytes_to_read = protocol.next_read_size()
333
335
            if bytes_to_read == 0:
334
336
                # Finished serving this request.
335
 
                self._out.flush()
 
337
                osutils.until_no_eintr(self._out.flush)
336
338
                return
337
339
            bytes = self.read_bytes(bytes_to_read)
338
340
            if bytes == '':
339
341
                # Connection has been closed.
340
342
                self.finished = True
341
 
                self._out.flush()
 
343
                osutils.until_no_eintr(self._out.flush)
342
344
                return
343
345
            protocol.accept_bytes(bytes)
344
346
 
345
347
    def _read_bytes(self, desired_count):
346
 
        return self._in.read(desired_count)
 
348
        return osutils.until_no_eintr(self._in.read, desired_count)
347
349
 
348
350
    def terminate_due_to_error(self):
349
351
        # TODO: This should log to a server log file, but no such thing
350
352
        # exists yet.  Andrew Bennetts 2006-09-29.
351
 
        self._out.close()
 
353
        osutils.until_no_eintr(self._out.close)
352
354
        self.finished = True
353
355
 
354
356
    def _write_out(self, bytes):
355
 
        self._out.write(bytes)
 
357
        osutils.until_no_eintr(self._out.write, bytes)
356
358
 
357
359
 
358
360
class SmartClientMediumRequest(object):
494
496
class _DebugCounter(object):
495
497
    """An object that counts the HPSS calls made to each client medium.
496
498
 
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.
 
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.
500
502
    """
501
503
 
502
504
    def __init__(self):
503
505
        self.counts = weakref.WeakKeyDictionary()
504
506
        client._SmartClient.hooks.install_named_hook(
505
507
            'call', self.increment_call_count, 'hpss call counter')
506
 
        bzrlib.global_state.cleanups.add_cleanup(self.flush_all)
 
508
        atexit.register(self.flush_all)
507
509
 
508
510
    def track(self, medium):
509
511
        """Start tracking calls made to a medium.
607
609
            # which is newer than a previously supplied older-than version.
608
610
            # This indicates that some smart verb call is not guarded
609
611
            # appropriately (it should simply not have been tried).
610
 
            trace.mutter(
 
612
            raise AssertionError(
611
613
                "_remember_remote_is_before(%r) called, but "
612
614
                "_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
 
615
                % (version_tuple, self._remote_version_is_before))
620
616
        self._remote_version_is_before = version_tuple
621
617
 
622
618
    def protocol_version(self):
724
720
 
725
721
    def _accept_bytes(self, bytes):
726
722
        """See SmartClientStreamMedium.accept_bytes."""
727
 
        self._writeable_pipe.write(bytes)
 
723
        osutils.until_no_eintr(self._writeable_pipe.write, bytes)
728
724
        self._report_activity(len(bytes), 'write')
729
725
 
730
726
    def _flush(self):
731
727
        """See SmartClientStreamMedium._flush()."""
732
 
        self._writeable_pipe.flush()
 
728
        osutils.until_no_eintr(self._writeable_pipe.flush)
733
729
 
734
730
    def _read_bytes(self, count):
735
731
        """See SmartClientStreamMedium._read_bytes."""
736
 
        bytes_to_read = min(count, _MAX_READ_SIZE)
737
 
        bytes = self._readable_pipe.read(bytes_to_read)
 
732
        bytes = osutils.until_no_eintr(self._readable_pipe.read, count)
738
733
        self._report_activity(len(bytes), 'read')
739
734
        return bytes
740
735
 
741
736
 
742
 
class SSHParams(object):
743
 
    """A set of parameters for starting a remote bzr via SSH."""
 
737
class SmartSSHClientMedium(SmartClientStreamMedium):
 
738
    """A client medium using SSH."""
744
739
 
745
740
    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):
 
741
            base=None, vendor=None, bzr_remote_path=None):
762
742
        """Creates a client that will connect on the first use.
763
743
 
764
 
        :param ssh_params: A SSHParams instance.
765
744
        :param vendor: An optional override for the ssh vendor to use. See
766
745
            bzrlib.transport.ssh for details on ssh vendors.
767
746
        """
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'
 
747
        self._connected = False
 
748
        self._host = host
 
749
        self._password = password
 
750
        self._port = port
 
751
        self._username = username
773
752
        # SmartClientStreamMedium stores the repr of this object in its
774
753
        # _DebugCounter so we have to store all the values used in our repr
775
754
        # method before calling the super init.
776
755
        SmartClientStreamMedium.__init__(self, base)
 
756
        self._read_from = None
 
757
        self._ssh_connection = None
777
758
        self._vendor = vendor
778
 
        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'
779
764
 
780
765
    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/)" % (
 
766
        return "%s(connected=%r, username=%r, host=%r, port=%r)" % (
786
767
            self.__class__.__name__,
787
 
            self._scheme,
788
 
            self._ssh_params.username,
789
 
            self._ssh_params.host,
790
 
            maybe_port)
 
768
            self._connected,
 
769
            self._username,
 
770
            self._host,
 
771
            self._port)
791
772
 
792
773
    def _accept_bytes(self, bytes):
793
774
        """See SmartClientStreamMedium.accept_bytes."""
794
775
        self._ensure_connection()
795
 
        self._real_medium.accept_bytes(bytes)
 
776
        osutils.until_no_eintr(self._write_to.write, bytes)
 
777
        self._report_activity(len(bytes), 'write')
796
778
 
797
779
    def disconnect(self):
798
780
        """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
 
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
805
787
 
806
788
    def _ensure_connection(self):
807
789
        """Connect this medium if not already connected."""
808
 
        if self._real_medium is not None:
 
790
        if self._connected:
809
791
            return
810
792
        if self._vendor is None:
811
793
            vendor = ssh._get_ssh_vendor()
812
794
        else:
813
795
            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',
 
796
        self._ssh_connection = vendor.connect_ssh(self._username,
 
797
                self._password, self._host, self._port,
 
798
                command=[self._bzr_remote_path, 'serve', '--inet',
818
799
                         '--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))
 
800
        self._read_from, self._write_to = \
 
801
            self._ssh_connection.get_filelike_channels()
 
802
        self._connected = True
831
803
 
832
804
    def _flush(self):
833
805
        """See SmartClientStreamMedium._flush()."""
834
 
        self._real_medium._flush()
 
806
        self._write_to.flush()
835
807
 
836
808
    def _read_bytes(self, count):
837
809
        """See SmartClientStreamMedium.read_bytes."""
838
 
        if self._real_medium is None:
 
810
        if not self._connected:
839
811
            raise errors.MediumNotConnected(self)
840
 
        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
841
816
 
842
817
 
843
818
# Port 4155 is the default port for bzr://, registered with IANA.
845
820
BZR_DEFAULT_PORT = 4155
846
821
 
847
822
 
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
 
    """
 
823
class SmartTCPClientMedium(SmartClientStreamMedium):
 
824
    """A client medium using TCP."""
853
825
 
854
 
    def __init__(self, base):
 
826
    def __init__(self, host, port, base):
 
827
        """Creates a client that will connect on the first use."""
855
828
        SmartClientStreamMedium.__init__(self, base)
 
829
        self._connected = False
 
830
        self._host = host
 
831
        self._port = port
856
832
        self._socket = None
857
 
        self._connected = False
858
833
 
859
834
    def _accept_bytes(self, bytes):
860
835
        """See SmartClientMedium.accept_bytes."""
861
836
        self._ensure_connection()
862
837
        osutils.send_all(self._socket, bytes, self._report_activity)
863
838
 
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
839
    def disconnect(self):
884
840
        """See SmartClientMedium.disconnect()."""
885
841
        if not self._connected:
886
842
            return
887
 
        self._socket.close()
 
843
        osutils.until_no_eintr(self._socket.close)
888
844
        self._socket = None
889
845
        self._connected = False
890
846
 
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
847
    def _ensure_connection(self):
902
848
        """Connect this medium if not already connected."""
903
849
        if self._connected:
937
883
                    (self._host, port, err_msg))
938
884
        self._connected = True
939
885
 
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
 
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)
956
899
 
957
900
 
958
901
class SmartClientStreamMediumRequest(SmartClientMediumRequest):
995
938
        self._medium._flush()
996
939
 
997
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