/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/message.py

Merge from bzr.dev.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2008 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
import collections
 
18
from cStringIO import StringIO
 
19
 
 
20
from bzrlib import (
 
21
    debug,
 
22
    errors,
 
23
    )
 
24
from bzrlib.trace import mutter
 
25
 
 
26
 
 
27
class MessageHandler(object):
 
28
    """Base class for handling messages received via the smart protocol.
 
29
 
 
30
    As parts of a message are received, the corresponding PART_received method
 
31
    will be called.
 
32
    """
 
33
 
 
34
    def __init__(self):
 
35
        self.headers = None
 
36
 
 
37
    def headers_received(self, headers):
 
38
        """Called when message headers are received.
 
39
        
 
40
        This default implementation just stores them in self.headers.
 
41
        """
 
42
        self.headers = headers
 
43
 
 
44
    def byte_part_received(self, byte):
 
45
        """Called when a 'byte' part is received.
 
46
 
 
47
        Note that a 'byte' part is a message part consisting of exactly one
 
48
        byte.
 
49
        """
 
50
        raise NotImplementedError(self.byte_received)
 
51
 
 
52
    def bytes_part_received(self, bytes):
 
53
        """Called when a 'bytes' part is received.
 
54
 
 
55
        A 'bytes' message part can contain any number of bytes.  It should not
 
56
        be confused with a 'byte' part, which is always a single byte.
 
57
        """
 
58
        raise NotImplementedError(self.bytes_received)
 
59
 
 
60
    def structure_part_received(self, structure):
 
61
        """Called when a 'structure' part is received.
 
62
 
 
63
        :param structure: some structured data, which will be some combination
 
64
            of list, dict, int, and str objects.
 
65
        """
 
66
        raise NotImplementedError(self.bytes_received)
 
67
 
 
68
    def protocol_error(self, exception):
 
69
        """Called when there is a protocol decoding error.
 
70
        
 
71
        The default implementation just re-raises the exception.
 
72
        """
 
73
        raise
 
74
    
 
75
    def end_received(self):
 
76
        """Called when the end of the message is received."""
 
77
        # No-op by default.
 
78
        pass
 
79
 
 
80
 
 
81
class ConventionalRequestHandler(MessageHandler):
 
82
    """A message handler for "conventional" requests.
 
83
 
 
84
    "Conventional" is used in the sense described in
 
85
    doc/developers/network-protocol.txt: a simple message with arguments and an
 
86
    optional body.
 
87
    """
 
88
 
 
89
    def __init__(self, request_handler, responder):
 
90
        MessageHandler.__init__(self)
 
91
        self.request_handler = request_handler
 
92
        self.responder = responder
 
93
        self.args_received = False
 
94
 
 
95
    def protocol_error(self, exception):
 
96
        self.responder.send_error(exception)
 
97
 
 
98
    def byte_part_received(self, byte):
 
99
        raise errors.SmartProtocolError(
 
100
            'Unexpected message part: byte(%r)' % (byte,))
 
101
 
 
102
    def structure_part_received(self, structure):
 
103
        if self.args_received:
 
104
            raise errors.SmartProtocolError(
 
105
                'Unexpected message part: structure(%r)' % (structure,))
 
106
        self.args_received = True
 
107
        self.request_handler.dispatch_command(structure[0], structure[1:])
 
108
        if self.request_handler.finished_reading:
 
109
            self.responder.send_response(self.request_handler.response)
 
110
 
 
111
    def bytes_part_received(self, bytes):
 
112
        # Note that there's no intrinsic way to distinguish a monolithic body
 
113
        # from a chunk stream.  A request handler knows which it is expecting
 
114
        # (once the args have been received), so it should be able to do the
 
115
        # right thing.
 
116
        self.request_handler.accept_body(bytes)
 
117
        self.request_handler.end_of_body()
 
118
        if not self.request_handler.finished_reading:
 
119
            raise SmartProtocolError(
 
120
                "Conventional request body was received, but request handler "
 
121
                "has not finished reading.")
 
122
        self.responder.send_response(self.request_handler.response)
 
123
 
 
124
 
 
125
class ResponseHandler(object):
 
126
    """Abstract base class for an object that handles a smart response."""
 
127
 
 
128
    def read_response_tuple(self, expect_body=False):
 
129
        """Reads and returns the response tuple for the current request.
 
130
        
 
131
        :keyword expect_body: a boolean indicating if a body is expected in the
 
132
            response.  Some protocol versions needs this information to know
 
133
            when a response is finished.  If False, read_body_bytes should
 
134
            *not* be called afterwards.  Defaults to False.
 
135
        :returns: tuple of response arguments.
 
136
        """
 
137
        raise NotImplementedError(self.read_response_tuple)
 
138
 
 
139
    def read_body_bytes(self, count=-1):
 
140
        """Read and return some bytes from the body.
 
141
 
 
142
        :param count: if specified, read up to this many bytes.  By default,
 
143
            reads the entire body.
 
144
        :returns: str of bytes from the response body.
 
145
        """
 
146
        raise NotImplementedError(self.read_body_bytes)
 
147
 
 
148
    def read_streamed_body(self):
 
149
        """Returns an iterable that reads and returns a series of body chunks.
 
150
        """
 
151
        raise NotImplementedError(self.read_streamed_body)
 
152
 
 
153
    def cancel_read_body(self):
 
154
        """Stop expecting a body for this response.
 
155
 
 
156
        If expect_body was passed to read_response_tuple, this cancels that
 
157
        expectation (and thus finishes reading the response, allowing a new
 
158
        request to be issued).  This is useful if a response turns out to be an
 
159
        error rather than a normal result with a body.
 
160
        """
 
161
        raise NotImplementedError(self.cancel_read_body)
 
162
 
 
163
 
 
164
class ConventionalResponseHandler(MessageHandler, ResponseHandler):
 
165
 
 
166
    def __init__(self):
 
167
        MessageHandler.__init__(self)
 
168
        self.status = None
 
169
        self.args = None
 
170
        self._bytes_parts = collections.deque()
 
171
        self._body_started = False
 
172
        self._body_stream_status = None
 
173
        self._body = None
 
174
        self._body_error_args = None
 
175
        self.finished_reading = False
 
176
 
 
177
    def setProtoAndMediumRequest(self, protocol_decoder, medium_request):
 
178
        self._protocol_decoder = protocol_decoder
 
179
        self._medium_request = medium_request
 
180
 
 
181
    def byte_part_received(self, byte):
 
182
        if byte not in ['E', 'S']:
 
183
            raise errors.SmartProtocolError(
 
184
                'Unknown response status: %r' % (byte,))
 
185
        if self._body_started:
 
186
            if self._body_stream_status is not None:
 
187
                raise errors.SmartProtocolError(
 
188
                    'Unexpected byte part received: %r' % (byte,))
 
189
            self._body_stream_status = byte
 
190
        else:
 
191
            if self.status is not None:
 
192
                raise errors.SmartProtocolError(
 
193
                    'Unexpected byte part received: %r' % (byte,))
 
194
            self.status = byte
 
195
 
 
196
    def bytes_part_received(self, bytes):
 
197
        self._body_started = True
 
198
        self._bytes_parts.append(bytes)
 
199
 
 
200
    def structure_part_received(self, structure):
 
201
        if type(structure) is not list:
 
202
            raise errors.SmartProtocolError(
 
203
                'Args structure is not a sequence: %r' % (structure,))
 
204
        structure = tuple(structure)
 
205
        if not self._body_started:
 
206
            if self.args is not None:
 
207
                raise errors.SmartProtocolError(
 
208
                    'Unexpected structure received: %r (already got %r)'
 
209
                    % (structure, self.args))
 
210
            self.args = structure
 
211
        else:
 
212
            if self._body_stream_status != 'E':
 
213
                raise errors.SmartProtocolError(
 
214
                    'Unexpected structure received after body: %r'
 
215
                    % (structure,))
 
216
            self._body_error_args = structure
 
217
 
 
218
    def _wait_for_response_args(self):
 
219
        while self.args is None and not self.finished_reading:
 
220
            self._read_more()
 
221
 
 
222
    def _wait_for_response_end(self):
 
223
        while not self.finished_reading:
 
224
            self._read_more()
 
225
 
 
226
    def _read_more(self):
 
227
        next_read_size = self._protocol_decoder.next_read_size()
 
228
        if next_read_size == 0:
 
229
            # a complete request has been read.
 
230
            self.finished_reading = True
 
231
            self._medium_request.finished_reading()
 
232
            return
 
233
        bytes = self._medium_request.read_bytes(next_read_size)
 
234
        if bytes == '':
 
235
            # end of file encountered reading from server
 
236
            raise errors.ConnectionReset(
 
237
                "please check connectivity and permissions",
 
238
                "(and try -Dhpss if further diagnosis is required)")
 
239
        self._protocol_decoder.accept_bytes(bytes)
 
240
 
 
241
    def read_response_tuple(self, expect_body=False):
 
242
        """Read a response tuple from the wire."""
 
243
        self._wait_for_response_args()
 
244
        if not expect_body:
 
245
            self._wait_for_response_end()
 
246
        if 'hpss' in debug.debug_flags:
 
247
            mutter('   result:   %r', self.args)
 
248
        if self.status == 'E':
 
249
            self._wait_for_response_end()
 
250
            _translate_error(self.args)
 
251
        return tuple(self.args)
 
252
 
 
253
    def read_body_bytes(self, count=-1):
 
254
        """Read bytes from the body, decoding into a byte stream.
 
255
        
 
256
        We read all bytes at once to ensure we've checked the trailer for 
 
257
        errors, and then feed the buffer back as read_body_bytes is called.
 
258
 
 
259
        Like the builtin file.read in Python, a count of -1 (the default) means
 
260
        read the entire body.
 
261
        """
 
262
        # TODO: we don't necessarily need to buffer the full request if count
 
263
        # != -1.  (2008/04/30, Andrew Bennetts)
 
264
        if self._body is None:
 
265
            self._wait_for_response_end()
 
266
            body_bytes = ''.join(self._bytes_parts)
 
267
            if 'hpss' in debug.debug_flags:
 
268
                mutter('              %d body bytes read', len(body_bytes))
 
269
            self._body = StringIO(body_bytes)
 
270
            self._bytes_parts = None
 
271
        return self._body.read(count)
 
272
 
 
273
    def read_streamed_body(self):
 
274
        while not self.finished_reading:
 
275
            while self._bytes_parts:
 
276
                bytes_part = self._bytes_parts.popleft()
 
277
                if 'hpss' in debug.debug_flags:
 
278
                    mutter('              %d byte part read', len(bytes_part))
 
279
                yield bytes_part
 
280
            self._read_more()
 
281
        if self._body_stream_status == 'E':
 
282
            _translate_error(self._body_error_args)
 
283
 
 
284
    def cancel_read_body(self):
 
285
        self._wait_for_response_end()
 
286
 
 
287
 
 
288
def _translate_error(error_tuple):
 
289
    # Many exceptions need some state from the requestor to be properly
 
290
    # translated (e.g. they need a branch object).  So this only translates a
 
291
    # few errors, and the rest are turned into a generic ErrorFromSmartServer.
 
292
    error_name = error_tuple[0]
 
293
    error_args = error_tuple[1:]
 
294
    if error_name == 'UnknownMethod':
 
295
        raise errors.UnknownSmartMethod(error_args[0])
 
296
    if error_name == 'LockContention':
 
297
        raise errors.LockContention('(remote lock)')
 
298
    elif error_name == 'LockFailed':
 
299
        raise errors.LockFailed(*error_args[:2])
 
300
    else:
 
301
        raise errors.ErrorFromSmartServer(error_tuple)