~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/smart/protocol.py

Remove a bunch of cruft, especially the SmartClientRequestProtocolThree class.

Show diffs side-by-side

added added

removed removed

Lines of Context:
277
277
        current_state = self.state_accept
278
278
        self._number_needed_bytes = None
279
279
        try:
280
 
            pr('invoking state_accept %s' %
281
 
                    (self.state_accept.im_func.__name__[len('_state_accept_'):],))
282
280
            self.state_accept(bytes)
283
281
            while current_state != self.state_accept:
284
282
                current_state = self.state_accept
285
 
                pr('invoking state_accept %s' %
286
 
                        (self.state_accept.im_func.__name__[len('_state_accept_'):],))
287
283
                self.state_accept('')
288
284
        except _NeedMoreBytes, e:
289
285
            #print '(need more bytes: %r)' % e.count
696
692
            bytes = self._request.read_bytes(bytes_wanted)
697
693
            _body_decoder.accept_bytes(bytes)
698
694
            for body_bytes in iter(_body_decoder.read_next_chunk, None):
699
 
                if 'hpss' in debug.debug_flags:
 
695
                if 'hpss' in debug.debug_flags and type(body_bytes) is str:
700
696
                    mutter('              %d byte chunk read',
701
697
                           len(body_bytes))
702
698
                yield body_bytes
734
730
#        self._body_decoder = None
735
731
 
736
732
    def accept_bytes(self, bytes):
737
 
        pr('......')
738
 
#        if 'put_non_atomic' in bytes:
739
 
#            import pdb; pdb.set_trace()
740
733
        def summarise_buf():
741
734
            if self._in_buffer is None:
742
735
                buf_summary = 'None'
761
754
            self.message_handler.protocol_error(exception)
762
755
            #self._send_response(request.FailedSmartServerResponse(
763
756
            #    ('error', str(exception))))
764
 
        pr('%s in %s(%s), got %r --> %s(%s)' % (
765
 
            handler_name, state_now, buf_now, bytes,
766
 
            self.state_accept.im_func.__name__[len('_state_accept_'):],
767
 
            summarise_buf()))
768
 
        pr('~~~~~~')
769
757
 
770
758
    def _extract_length_prefixed_bytes(self):
771
759
        if len(self._in_buffer) < 4:
872
860
                return 1 # XXX !!!
873
861
 
874
862
 
875
 
class SmartClientRequestProtocolThree(ProtocolThreeDecoder, SmartClientRequestProtocolTwo):
876
 
 
877
 
    response_marker = RESPONSE_VERSION_THREE
878
 
    request_marker = REQUEST_VERSION_THREE
879
 
 
880
 
    def __init__(self, client_medium_request):
881
 
        ProtocolThreeDecoder.__init__(self, message.MessageHandler())
882
 
        SmartClientRequestProtocolTwo.__init__(self, client_medium_request)
883
 
 
884
 
    # XXX: the encoding of requests and decoding responses are somewhat
885
 
    # conflated into one class here.  The protocol is half-duplex, so combining
886
 
    # them just makes the code needlessly ugly.
887
 
 
888
 
    def _write_prefixed_bencode(self, structure):
889
 
        bytes = bencode(structure)
890
 
        self._request.accept_bytes(struct.pack('!L', len(bytes)))
891
 
        self._request.accept_bytes(bytes)
892
 
 
893
 
    def _write_headers(self, headers=None):
894
 
        if headers is None:
895
 
            headers = {'Software version': bzrlib.__version__}
896
 
        self._write_prefixed_bencode(headers)
897
 
 
898
 
    def _write_args(self, args):
899
 
        self._request.accept_bytes('s')
900
 
        self._write_prefixed_bencode(args)
901
 
 
902
 
    def _write_end(self):
903
 
        self._request.accept_bytes('e')
904
 
 
905
 
    def _write_prefixed_body(self, bytes):
906
 
        self._request.accept_bytes('b')
907
 
        self._request.accept_bytes(struct.pack('!L', len(bytes)))
908
 
        self._request.accept_bytes(bytes)
909
 
 
910
 
    def _wait_for_request_end(self):
911
 
        while True:
912
 
            next_read_size = self.next_read_size() 
913
 
            if next_read_size == 0:
914
 
                # a complete request has been read.
915
 
                break
916
 
            bytes = self._request.read_bytes(next_read_size)
917
 
            if bytes == '':
918
 
                # end of file encountered reading from server
919
 
                raise errors.ConnectionReset(
920
 
                    "please check connectivity and permissions",
921
 
                    "(and try -Dhpss if further diagnosis is required)")
922
 
            self.accept_bytes(bytes)
923
 
 
924
 
    # these methods from SmartClientRequestProtocolOne/Two
925
 
    def call(self, *args, **kw):
926
 
        # XXX: ideally, signature would be call(self, *args, headers=None), but
927
 
        # python doesn't allow that.  So, we fake it.
928
 
        headers = None
929
 
        if 'headers' in kw:
930
 
            headers = kw.pop('headers')
931
 
        if kw != {}:
932
 
            raise TypeError('Unexpected keyword arguments: %r' % (kw,))
933
 
        if 'hpss' in debug.debug_flags:
934
 
            mutter('hpss call:   %s', repr(args)[1:-1])
935
 
            if getattr(self._request._medium, 'base', None) is not None:
936
 
                mutter('             (to %s)', self._request._medium.base)
937
 
            self._request_start_time = time.time()
938
 
        self._write_protocol_version()
939
 
        self._write_headers(headers)
940
 
        self._write_args(args)
941
 
        self._write_end()
942
 
        self._request.finished_writing()
943
 
 
944
 
    def call_with_body_bytes(self, args, body, headers=None):
945
 
        """Make a remote call of args with body bytes 'body'.
946
 
 
947
 
        After calling this, call read_response_tuple to find the result out.
948
 
        """
949
 
        if 'hpss' in debug.debug_flags:
950
 
            mutter('hpss call w/body: %s (%r...)', repr(args)[1:-1], body[:20])
951
 
            if getattr(self._request._medium, '_path', None) is not None:
952
 
                mutter('                  (to %s)', self._request._medium._path)
953
 
            mutter('              %d bytes', len(body))
954
 
            self._request_start_time = time.time()
955
 
        self._write_protocol_version()
956
 
        self._write_headers(headers)
957
 
        self._write_args(args)
958
 
        self._write_prefixed_body(body)
959
 
        self._write_end()
960
 
        self._request.finished_writing()
961
 
 
962
 
    def call_with_body_readv_array(self, args, body, headers=None):
963
 
        """Make a remote call with a readv array.
964
 
 
965
 
        The body is encoded with one line per readv offset pair. The numbers in
966
 
        each pair are separated by a comma, and no trailing \n is emitted.
967
 
        """
968
 
        if 'hpss' in debug.debug_flags:
969
 
            mutter('hpss call w/readv: %s', repr(args)[1:-1])
970
 
            if getattr(self._request._medium, '_path', None) is not None:
971
 
                mutter('                  (to %s)', self._request._medium._path)
972
 
            self._request_start_time = time.time()
973
 
        self._write_protocol_version()
974
 
        self._write_headers(headers)
975
 
        self._write_args(args)
976
 
        readv_bytes = self._serialise_offsets(body)
977
 
        self._write_prefixed_body(readv_bytes)
978
 
        self._request.finished_writing()
979
 
        if 'hpss' in debug.debug_flags:
980
 
            mutter('              %d bytes in readv request', len(readv_bytes))
981
 
 
982
 
    def cancel_read_body(self):
983
 
        """Ignored.  Not relevant to version 3 of the protocol."""
984
 
 
985
 
    def read_response_tuple(self, expect_body=False):
986
 
        """Read a response tuple from the wire.
987
 
 
988
 
        The expect_body flag is ignored.
989
 
        """
990
 
        # XXX: warn if expect_body doesn't match the response?
991
 
        self._wait_for_request_end()
992
 
        if self.response_handler.error_args is not None:
993
 
            _translate_error(self.response_handler.error_args)
994
 
            return self.response_handler.error_args
995
 
        return self.response_handler.args
996
 
 
997
 
    def read_body_bytes(self, count=-1):
998
 
        """Read bytes from the body, decoding into a byte stream.
999
 
        
1000
 
        We read all bytes at once to ensure we've checked the trailer for 
1001
 
        errors, and then feed the buffer back as read_body_bytes is called.
1002
 
        """
1003
 
        # XXX: don't buffer the full request
1004
 
        self._wait_for_request_end()
1005
 
        return self.response_handler.prefixed_body.read(count)
1006
 
 
1007
 
 
1008
 
def _translate_error(error_tuple):
1009
 
    # XXX: Hmm!  Need state from the request.  Hmm.
1010
 
    error_name = error_tuple[0]
1011
 
    error_args = error_tuple[1:]
1012
 
    if error_name == 'LockContention':
1013
 
        raise errors.LockContention('(remote lock)')
1014
 
    elif error_name == 'LockFailed':
1015
 
        raise errors.LockContention(*error_args[:2])
1016
 
    else:
1017
 
        return # XXX
1018
 
        raise errors.UnexpectedSmartServerResponse('Sucktitude: %r' %
1019
 
                (error_tuple,))
1020
 
 
1021
 
 
1022
863
class _ProtocolThreeEncoder(object):
1023
864
 
 
865
    response_marker = request_marker = MESSAGE_VERSION_THREE
 
866
 
1024
867
    def __init__(self, write_func):
1025
 
        import sys
1026
 
        def wf(bytes):
1027
 
            pr('writing:', repr(bytes))
1028
 
            return write_func(bytes)
1029
 
        self._write_func = wf
 
868
        self._write_func = write_func
1030
869
 
 
870
    def _serialise_offsets(self, offsets):
 
871
        """Serialise a readv offset list."""
 
872
        txt = []
 
873
        for start, length in offsets:
 
874
            txt.append('%d,%d' % (start, length))
 
875
        return '\n'.join(txt)
 
876
        
1031
877
    def _write_protocol_version(self):
1032
878
        self._write_func(MESSAGE_VERSION_THREE)
1033
879
 
1153
999
                mutter('                  (to %s)', path)
1154
1000
            mutter('              %d bytes', len(body))
1155
1001
            self._request_start_time = time.time()
1156
 
        pr('call_with_body_bytes: %r, %r' % (args, body))
1157
1002
        self._write_protocol_version()
1158
1003
        self._write_headers(headers)
1159
1004
        self._write_structure(args)
1205
1050
#        # XXX: don't buffer the full request
1206
1051
#        self._wait_for_request_end()
1207
1052
#        return self.response_handler.prefixed_body.read(count)
1208
 
 
1209
 
 
1210
 
from thread import get_ident
1211
 
def pr(*args):
1212
 
    return
1213
 
    print '%x' % get_ident(),
1214
 
    for arg in args:
1215
 
        print arg,
1216
 
    print