/breezy/unstable

To get this branch, use:
bzr branch https://code.breezy-vcs.org/breezy/unstable

« back to all changes in this revision

Viewing changes to breezy/smart/protocol.py

  • Committer: Jelmer Vernooij
  • Date: 2017-05-24 01:39:33 UTC
  • mfrom: (3815.3776.6)
  • Revision ID: jelmer@jelmer.uk-20170524013933-ir4y4tqtrsiz2ka2
New upstream snapshot.

Show diffs side-by-side

added added

removed removed

Lines of Context:
21
21
from __future__ import absolute_import
22
22
 
23
23
import collections
24
 
from cStringIO import StringIO
25
24
import struct
26
25
import sys
27
 
import thread
 
26
try:
 
27
    import _thread
 
28
except ImportError:
 
29
    import thread as _thread
28
30
import time
29
31
 
30
 
import bzrlib
31
 
from bzrlib import (
 
32
import breezy
 
33
from .. import (
32
34
    debug,
33
35
    errors,
34
36
    osutils,
35
37
    )
36
 
from bzrlib.smart import message, request
37
 
from bzrlib.trace import log_exception_quietly, mutter
38
 
from bzrlib.bencode import bdecode_as_tuple, bencode
 
38
from ..sixish import (
 
39
    BytesIO,
 
40
    reraise,
 
41
)
 
42
from . import message, request
 
43
from ..trace import log_exception_quietly, mutter
 
44
from ..bencode import bdecode_as_tuple, bencode
39
45
 
40
46
 
41
47
# Protocol version strings.  These are sent as prefixes of bzr requests and
64
70
def _encode_tuple(args):
65
71
    """Encode the tuple args to a bytestream."""
66
72
    joined = '\x01'.join(args) + '\n'
67
 
    if type(joined) is unicode:
 
73
    if isinstance(joined, unicode):
68
74
        # XXX: We should fix things so this never happens!  -AJB, 20100304
69
75
        mutter('response args contain unicode, should be only bytes: %r',
70
76
               joined)
168
174
                    self._send_response(self.request.response)
169
175
            except KeyboardInterrupt:
170
176
                raise
171
 
            except errors.UnknownSmartMethod, err:
 
177
            except errors.UnknownSmartMethod as err:
172
178
                protocol_error = errors.SmartProtocolError(
173
179
                    "bad request %r" % (err.verb,))
174
180
                failure = request.FailedSmartServerResponse(
175
181
                    ('error', str(protocol_error)))
176
182
                self._send_response(failure)
177
183
                return
178
 
            except Exception, exception:
 
184
            except Exception as exception:
179
185
                # everything else: pass to client, flush, and quit
180
186
                log_exception_quietly()
181
187
                self._send_response(request.FailedSmartServerResponse(
409
415
                #     _NeedMoreBytes).
410
416
                current_state = self.state_accept
411
417
                self.state_accept()
412
 
        except _NeedMoreBytes, e:
 
418
        except _NeedMoreBytes as e:
413
419
            self._number_needed_bytes = e.count
414
420
 
415
421
 
776
782
                    "Connection lost while reading response body.")
777
783
            _body_decoder.accept_bytes(bytes)
778
784
        self._request.finished_reading()
779
 
        self._body_buffer = StringIO(_body_decoder.read_pending_data())
 
785
        self._body_buffer = BytesIO(_body_decoder.read_pending_data())
780
786
        # XXX: TODO check the trailer result.
781
787
        if 'hpss' in debug.debug_flags:
782
788
            mutter('              %d body bytes read',
865
871
                    "Connection lost while reading streamed body.")
866
872
            _body_decoder.accept_bytes(bytes)
867
873
            for body_bytes in iter(_body_decoder.read_next_chunk, None):
868
 
                if 'hpss' in debug.debug_flags and type(body_bytes) is str:
 
874
                if 'hpss' in debug.debug_flags and isinstance(body_bytes, str):
869
875
                    mutter('              %d byte chunk read',
870
876
                           len(body_bytes))
871
877
                yield body_bytes
908
914
            _StatefulDecoder.accept_bytes(self, bytes)
909
915
        except KeyboardInterrupt:
910
916
            raise
911
 
        except errors.SmartMessageHandlerError, exception:
 
917
        except errors.SmartMessageHandlerError as exception:
912
918
            # We do *not* set self.decoding_failed here.  The message handler
913
919
            # has raised an error, but the decoder is still able to parse bytes
914
920
            # and determine when this message ends.
919
925
            # exception has interrupted the loop that runs the state machine.
920
926
            # So we call accept_bytes again to restart it.
921
927
            self.accept_bytes('')
922
 
        except Exception, exception:
 
928
        except Exception as exception:
923
929
            # The decoder itself has raised an exception.  We cannot continue
924
930
            # decoding.
925
931
            self.decoding_failed = True
993
999
 
994
1000
    def _state_accept_expecting_headers(self):
995
1001
        decoded = self._extract_prefixed_bencoded_data()
996
 
        if type(decoded) is not dict:
 
1002
        if not isinstance(decoded, dict):
997
1003
            raise errors.SmartProtocolError(
998
1004
                'Header object %r is not a dict' % (decoded,))
999
1005
        self.state_accept = self._state_accept_expecting_message_part
1120
1126
        self._write_func('s')
1121
1127
        utf8_args = []
1122
1128
        for arg in args:
1123
 
            if type(arg) is unicode:
 
1129
            if isinstance(arg, unicode):
1124
1130
                utf8_args.append(arg.encode('utf8'))
1125
1131
            else:
1126
1132
                utf8_args.append(arg)
1150
1156
    def __init__(self, write_func):
1151
1157
        _ProtocolThreeEncoder.__init__(self, write_func)
1152
1158
        self.response_sent = False
1153
 
        self._headers = {'Software version': bzrlib.__version__}
 
1159
        self._headers = {'Software version': breezy.__version__}
1154
1160
        if 'hpss' in debug.debug_flags:
1155
 
            self._thread_id = thread.get_ident()
 
1161
            self._thread_id = _thread.get_ident()
1156
1162
            self._response_start_time = None
1157
1163
 
1158
1164
    def _trace(self, action, message, extra_bytes=None, include_time=False):
1376
1382
                self._write_structure(('error',))
1377
1383
                self._write_end()
1378
1384
                self._medium_request.finished_writing()
1379
 
                raise exc_info[0], exc_info[1], exc_info[2]
 
1385
                try:
 
1386
                    reraise(*exc_info)
 
1387
                finally:
 
1388
                    del exc_info
1380
1389
            else:
1381
1390
                self._write_prefixed_body(part)
1382
1391
                self.flush()