~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/smart/medium.py

  • Committer: Martin Pool
  • Date: 2010-08-05 08:18:06 UTC
  • mto: (5050.3.20 2.2)
  • mto: This revision was merged to the branch mainline in revision 5371.
  • Revision ID: mbp@sourcefrog.net-20100805081806-4c4gjsiw9i3j0c3w
Clear off progress bars by painting spaces.

This selectively reverts part of the previous progress change.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006 Canonical Ltd
 
1
# Copyright (C) 2006-2010 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
28
27
import os
29
 
import socket
30
28
import sys
31
29
import urllib
32
30
 
 
31
import bzrlib
33
32
from bzrlib.lazy_import import lazy_import
34
33
lazy_import(globals(), """
35
 
import atexit
 
34
import socket
 
35
import thread
36
36
import weakref
 
37
 
37
38
from bzrlib import (
38
39
    debug,
39
40
    errors,
40
 
    osutils,
41
41
    symbol_versioning,
42
42
    trace,
43
43
    ui,
44
44
    urlutils,
45
45
    )
46
 
from bzrlib.smart import client, protocol
 
46
from bzrlib.smart import client, protocol, request, vfs
47
47
from bzrlib.transport import ssh
48
48
""")
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
 
 
 
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
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_READ_SIZE ready, the socket wil just return a short
278
 
            # read immediately rather than block.
279
 
            bytes = self.read_bytes(_MAX_READ_SIZE)
 
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)
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
 
        # We ignore the desired_count because on sockets it's more efficient to
289
 
        # read large chunks (of _MAX_READ_SIZE bytes) at a time.
290
 
        bytes = osutils.until_no_eintr(self.socket.recv, _MAX_READ_SIZE)
291
 
        self._report_activity(len(bytes), 'read')
292
 
        return bytes
 
288
        return osutils.read_bytes_from_socket(
 
289
            self.socket, self._report_activity)
293
290
 
294
291
    def terminate_due_to_error(self):
295
292
        # TODO: This should log to a server log file, but no such thing
298
295
        self.finished = True
299
296
 
300
297
    def _write_out(self, bytes):
 
298
        tstart = osutils.timer_func()
301
299
        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))
302
305
 
303
306
 
304
307
class SmartServerPipeStreamMedium(SmartServerStreamMedium):
381
384
    def accept_bytes(self, bytes):
382
385
        """Accept bytes for inclusion in this request.
383
386
 
384
 
        This method may not be be called after finished_writing() has been
 
387
        This method may not be called after finished_writing() has been
385
388
        called.  It depends upon the Medium whether or not the bytes will be
386
389
        immediately transmitted. Message based Mediums will tend to buffer the
387
390
        bytes until finished_writing() is called.
475
478
        if not line.endswith('\n'):
476
479
            # end of file encountered reading from server
477
480
            raise errors.ConnectionReset(
478
 
                "please check connectivity and permissions")
 
481
                "Unexpected end of message. Please check connectivity "
 
482
                "and permissions, and report a bug if problems persist.")
479
483
        return line
480
484
 
481
485
    def _read_line(self):
490
494
class _DebugCounter(object):
491
495
    """An object that counts the HPSS calls made to each client medium.
492
496
 
493
 
    When a medium is garbage-collected, or failing that when atexit functions
494
 
    are run, the total number of calls made on that medium are reported via
495
 
    trace.note.
 
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.
496
500
    """
497
501
 
498
502
    def __init__(self):
499
503
        self.counts = weakref.WeakKeyDictionary()
500
504
        client._SmartClient.hooks.install_named_hook(
501
505
            'call', self.increment_call_count, 'hpss call counter')
502
 
        atexit.register(self.flush_all)
 
506
        bzrlib.global_state.cleanups.add_cleanup(self.flush_all)
503
507
 
504
508
    def track(self, medium):
505
509
        """Start tracking calls made to a medium.
509
513
        """
510
514
        medium_repr = repr(medium)
511
515
        # Add this medium to the WeakKeyDictionary
512
 
        self.counts[medium] = [0, medium_repr]
 
516
        self.counts[medium] = dict(count=0, vfs_count=0,
 
517
                                   medium_repr=medium_repr)
513
518
        # Weakref callbacks are fired in reverse order of their association
514
519
        # with the referenced object.  So we add a weakref *after* adding to
515
520
        # the WeakKeyDict so that we can report the value from it before the
519
524
    def increment_call_count(self, params):
520
525
        # Increment the count in the WeakKeyDictionary
521
526
        value = self.counts[params.medium]
522
 
        value[0] += 1
 
527
        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
 
533
        if issubclass(request_method, vfs.VfsRequest):
 
534
            value['vfs_count'] += 1
523
535
 
524
536
    def done(self, ref):
525
537
        value = self.counts[ref]
526
 
        count, medium_repr = value
 
538
        count, vfs_count, medium_repr = (
 
539
            value['count'], value['vfs_count'], value['medium_repr'])
527
540
        # In case this callback is invoked for the same ref twice (by the
528
541
        # weakref callback and by the atexit function), set the call count back
529
542
        # to 0 so this item won't be reported twice.
530
 
        value[0] = 0
 
543
        value['count'] = 0
 
544
        value['vfs_count'] = 0
531
545
        if count != 0:
532
 
            trace.note('HPSS calls: %d %s', count, medium_repr)
 
546
            trace.note('HPSS calls: %d (%d vfs) %s',
 
547
                       count, vfs_count, medium_repr)
533
548
 
534
549
    def flush_all(self):
535
550
        for ref in list(self.counts.keys()):
592
607
            # which is newer than a previously supplied older-than version.
593
608
            # This indicates that some smart verb call is not guarded
594
609
            # appropriately (it should simply not have been tried).
595
 
            raise AssertionError(
 
610
            trace.mutter(
596
611
                "_remember_remote_is_before(%r) called, but "
597
612
                "_remember_remote_is_before(%r) was called previously."
598
 
                % (version_tuple, self._remote_version_is_before))
 
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
599
620
        self._remote_version_is_before = version_tuple
600
621
 
601
622
    def protocol_version(self):
712
733
 
713
734
    def _read_bytes(self, count):
714
735
        """See SmartClientStreamMedium._read_bytes."""
715
 
        bytes = self._readable_pipe.read(count)
 
736
        bytes_to_read = min(count, _MAX_READ_SIZE)
 
737
        bytes = self._readable_pipe.read(bytes_to_read)
716
738
        self._report_activity(len(bytes), 'read')
717
739
        return bytes
718
740
 
719
741
 
 
742
class SSHParams(object):
 
743
    """A set of parameters for starting a remote bzr via SSH."""
 
744
 
 
745
    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
 
720
754
class SmartSSHClientMedium(SmartClientStreamMedium):
721
 
    """A client medium using SSH."""
 
755
    """A client medium using SSH.
 
756
    
 
757
    It delegates IO to a SmartClientSocketMedium or
 
758
    SmartClientAlreadyConnectedSocketMedium (depending on platform).
 
759
    """
722
760
 
723
 
    def __init__(self, host, port=None, username=None, password=None,
724
 
            base=None, vendor=None, bzr_remote_path=None):
 
761
    def __init__(self, base, ssh_params, vendor=None):
725
762
        """Creates a client that will connect on the first use.
726
763
 
 
764
        :param ssh_params: A SSHParams instance.
727
765
        :param vendor: An optional override for the ssh vendor to use. See
728
766
            bzrlib.transport.ssh for details on ssh vendors.
729
767
        """
730
 
        self._connected = False
731
 
        self._host = host
732
 
        self._password = password
733
 
        self._port = port
734
 
        self._username = username
 
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'
735
773
        # SmartClientStreamMedium stores the repr of this object in its
736
774
        # _DebugCounter so we have to store all the values used in our repr
737
775
        # method before calling the super init.
738
776
        SmartClientStreamMedium.__init__(self, base)
739
 
        self._read_from = None
 
777
        self._vendor = vendor
740
778
        self._ssh_connection = None
741
 
        self._vendor = vendor
742
 
        self._write_to = None
743
 
        self._bzr_remote_path = bzr_remote_path
744
 
        # for the benefit of progress making a short description of this
745
 
        # transport
746
 
        self._scheme = 'bzr+ssh'
747
779
 
748
780
    def __repr__(self):
749
 
        return "%s(connected=%r, username=%r, host=%r, port=%r)" % (
 
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/)" % (
750
786
            self.__class__.__name__,
751
 
            self._connected,
752
 
            self._username,
753
 
            self._host,
754
 
            self._port)
 
787
            self._scheme,
 
788
            self._ssh_params.username,
 
789
            self._ssh_params.host,
 
790
            maybe_port)
755
791
 
756
792
    def _accept_bytes(self, bytes):
757
793
        """See SmartClientStreamMedium.accept_bytes."""
758
794
        self._ensure_connection()
759
 
        self._write_to.write(bytes)
760
 
        self._report_activity(len(bytes), 'write')
 
795
        self._real_medium.accept_bytes(bytes)
761
796
 
762
797
    def disconnect(self):
763
798
        """See SmartClientMedium.disconnect()."""
764
 
        if not self._connected:
765
 
            return
766
 
        self._read_from.close()
767
 
        self._write_to.close()
768
 
        self._ssh_connection.close()
769
 
        self._connected = False
 
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
770
805
 
771
806
    def _ensure_connection(self):
772
807
        """Connect this medium if not already connected."""
773
 
        if self._connected:
 
808
        if self._real_medium is not None:
774
809
            return
775
810
        if self._vendor is None:
776
811
            vendor = ssh._get_ssh_vendor()
777
812
        else:
778
813
            vendor = self._vendor
779
 
        self._ssh_connection = vendor.connect_ssh(self._username,
780
 
                self._password, self._host, self._port,
781
 
                command=[self._bzr_remote_path, 'serve', '--inet',
 
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',
782
818
                         '--directory=/', '--allow-writes'])
783
 
        self._read_from, self._write_to = \
784
 
            self._ssh_connection.get_filelike_channels()
785
 
        self._connected = True
 
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))
786
831
 
787
832
    def _flush(self):
788
833
        """See SmartClientStreamMedium._flush()."""
789
 
        self._write_to.flush()
 
834
        self._real_medium._flush()
790
835
 
791
836
    def _read_bytes(self, count):
792
837
        """See SmartClientStreamMedium.read_bytes."""
793
 
        if not self._connected:
 
838
        if self._real_medium is None:
794
839
            raise errors.MediumNotConnected(self)
795
 
        bytes_to_read = min(count, _MAX_READ_SIZE)
796
 
        bytes = self._read_from.read(bytes_to_read)
797
 
        self._report_activity(len(bytes), 'read')
798
 
        return bytes
 
840
        return self._real_medium.read_bytes(count)
799
841
 
800
842
 
801
843
# Port 4155 is the default port for bzr://, registered with IANA.
803
845
BZR_DEFAULT_PORT = 4155
804
846
 
805
847
 
806
 
class SmartTCPClientMedium(SmartClientStreamMedium):
807
 
    """A client medium using TCP."""
 
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
    """
808
853
 
809
 
    def __init__(self, host, port, base):
810
 
        """Creates a client that will connect on the first use."""
 
854
    def __init__(self, base):
811
855
        SmartClientStreamMedium.__init__(self, base)
 
856
        self._socket = None
812
857
        self._connected = False
813
 
        self._host = host
814
 
        self._port = port
815
 
        self._socket = None
816
858
 
817
859
    def _accept_bytes(self, bytes):
818
860
        """See SmartClientMedium.accept_bytes."""
819
861
        self._ensure_connection()
820
862
        osutils.send_all(self._socket, bytes, self._report_activity)
821
863
 
 
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
 
822
883
    def disconnect(self):
823
884
        """See SmartClientMedium.disconnect()."""
824
885
        if not self._connected:
827
888
        self._socket = None
828
889
        self._connected = False
829
890
 
 
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
 
830
901
    def _ensure_connection(self):
831
902
        """Connect this medium if not already connected."""
832
903
        if self._connected:
866
937
                    (self._host, port, err_msg))
867
938
        self._connected = True
868
939
 
869
 
    def _flush(self):
870
 
        """See SmartClientStreamMedium._flush().
871
 
 
872
 
        For TCP we do no flushing. We may want to turn off TCP_NODELAY and
873
 
        add a means to do a flush, but that can be done in the 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
 
        # We ignore the desired_count because on sockets it's more efficient to
881
 
        # read large chunks (of _MAX_READ_SIZE bytes) at a time.
882
 
        try:
883
 
            bytes = osutils.until_no_eintr(self._socket.recv, _MAX_READ_SIZE)
884
 
        except socket.error, e:
885
 
            if len(e.args) and e.args[0] == errno.ECONNRESET:
886
 
                # Callers expect an empty string in that case
887
 
                return ''
888
 
            else:
889
 
                raise
890
 
        else:
891
 
            self._report_activity(len(bytes), 'read')
892
 
            return bytes
 
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
893
956
 
894
957
 
895
958
class SmartClientStreamMediumRequest(SmartClientMediumRequest):
931
994
        """
932
995
        self._medium._flush()
933
996
 
 
997