~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/smart/request.py

  • Committer: Aaron Bentley
  • Date: 2008-03-03 16:52:41 UTC
  • mfrom: (3144.3.11 fix-conflict-handling)
  • mto: This revision was merged to the branch mainline in revision 3250.
  • Revision ID: aaron@aaronbentley.com-20080303165241-0k2c7ggs6kr9q6hf
Merge with fix-conflict-handling

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
 
"""Basic server-side logic for dealing with requests.
18
 
 
19
 
**XXX**:
20
 
 
21
 
The class names are a little confusing: the protocol will instantiate a
22
 
SmartServerRequestHandler, whose dispatch_command method creates an instance of
23
 
a SmartServerRequest subclass.
24
 
 
25
 
The request_handlers registry tracks SmartServerRequest classes (rather than
26
 
SmartServerRequestHandler).
27
 
"""
 
17
"""Basic server-side logic for dealing with requests."""
 
18
 
28
19
 
29
20
import tempfile
30
21
 
33
24
    errors,
34
25
    registry,
35
26
    revision,
36
 
    urlutils,
37
27
    )
38
 
from bzrlib.lazy_import import lazy_import
39
 
lazy_import(globals(), """
40
 
from bzrlib.bundle import serializer
41
 
""")
 
28
from bzrlib.bundle.serializer import write_bundle
42
29
 
43
30
 
44
31
class SmartServerRequest(object):
45
 
    """Base class for request handlers.
46
 
    
47
 
    To define a new request, subclass this class and override the `do` method
48
 
    (and if appropriate, `do_body` as well).  Request implementors should take
49
 
    care to call `translate_client_path` and `transport_from_client_path` as
50
 
    appropriate when dealing with paths received from the client.
51
 
    """
52
 
    # XXX: rename this class to BaseSmartServerRequestHandler ?  A request
53
 
    # *handler* is a different concept to the request.
 
32
    """Base class for request handlers."""
54
33
 
55
 
    def __init__(self, backing_transport, root_client_path='/'):
 
34
    def __init__(self, backing_transport):
56
35
        """Constructor.
57
36
 
58
37
        :param backing_transport: the base transport to be used when performing
59
38
            this request.
60
 
        :param root_client_path: the client path that maps to the root of
61
 
            backing_transport.  This is used to interpret relpaths received
62
 
            from the client.  Clients will not be able to refer to paths above
63
 
            this root.  If root_client_path is None, then no translation will
64
 
            be performed on client paths.  Default is '/'.
65
39
        """
66
40
        self._backing_transport = backing_transport
67
 
        if root_client_path is not None:
68
 
            if not root_client_path.startswith('/'):
69
 
                root_client_path = '/' + root_client_path
70
 
            if not root_client_path.endswith('/'):
71
 
                root_client_path += '/'
72
 
        self._root_client_path = root_client_path
73
 
        self._body_chunks = []
74
41
 
75
42
    def _check_enabled(self):
76
43
        """Raises DisabledMethod if this method is disabled."""
104
71
        
105
72
        Must return a SmartServerResponse.
106
73
        """
107
 
        if body_bytes != '':
108
 
            raise errors.SmartProtocolError('Request does not expect a body')
109
 
 
110
 
    def do_chunk(self, chunk_bytes):
111
 
        """Called with each body chunk if the request has a streamed body.
112
 
 
113
 
        The do() method is still called, and must have returned None.
114
 
        """
115
 
        self._body_chunks.append(chunk_bytes)
116
 
 
117
 
    def do_end(self):
118
 
        """Called when the end of the request has been received."""
119
 
        body_bytes = ''.join(self._body_chunks)
120
 
        self._body_chunks = None
121
 
        return self.do_body(body_bytes)
122
 
    
123
 
    def translate_client_path(self, client_path):
124
 
        """Translate a path received from a network client into a local
125
 
        relpath.
126
 
 
127
 
        All paths received from the client *must* be translated.
128
 
 
129
 
        :param client_path: the path from the client.
130
 
        :returns: a relpath that may be used with self._backing_transport
131
 
            (unlike the untranslated client_path, which must not be used with
132
 
            the backing transport).
133
 
        """
134
 
        if self._root_client_path is None:
135
 
            # no translation necessary!
136
 
            return client_path
137
 
        if not client_path.startswith('/'):
138
 
            client_path = '/' + client_path
139
 
        if client_path.startswith(self._root_client_path):
140
 
            path = client_path[len(self._root_client_path):]
141
 
            relpath = urlutils.joinpath('/', path)
142
 
            if not relpath.startswith('/'):
143
 
                raise ValueError(relpath)
144
 
            return '.' + relpath
145
 
        else:
146
 
            raise errors.PathNotChild(client_path, self._root_client_path)
147
 
 
148
 
    def transport_from_client_path(self, client_path):
149
 
        """Get a backing transport corresponding to the location referred to by
150
 
        a network client.
151
 
 
152
 
        :seealso: translate_client_path
153
 
        :returns: a transport cloned from self._backing_transport
154
 
        """
155
 
        relpath = self.translate_client_path(client_path)
156
 
        return self._backing_transport.clone(relpath)
 
74
        # TODO: if a client erroneously sends a request that shouldn't have a
 
75
        # body, what to do?  Probably SmartServerRequestHandler should catch
 
76
        # this NotImplementedError and translate it into a 'bad request' error
 
77
        # to send to the client.
 
78
        raise NotImplementedError(self.do_body)
157
79
 
158
80
 
159
81
class SmartServerResponse(object):
186
108
                other.body_stream is self.body_stream)
187
109
 
188
110
    def __repr__(self):
189
 
        return "<%s args=%r body=%r>" % (self.__class__.__name__,
190
 
            self.args, self.body)
 
111
        return ("<SmartServerResponse successful=%s args=%r body=%r>"
 
112
                % (self.is_successful(), self.args, self.body))
191
113
 
192
114
 
193
115
class FailedSmartServerResponse(SmartServerResponse):
223
145
    # TODO: Better way of representing the body for commands that take it,
224
146
    # and allow it to be streamed into the server.
225
147
 
226
 
    def __init__(self, backing_transport, commands, root_client_path):
 
148
    def __init__(self, backing_transport, commands):
227
149
        """Constructor.
228
150
 
229
151
        :param backing_transport: a Transport to handle requests for.
231
153
            subclasses. e.g. bzrlib.transport.smart.vfs.vfs_commands.
232
154
        """
233
155
        self._backing_transport = backing_transport
234
 
        self._root_client_path = root_client_path
235
156
        self._commands = commands
 
157
        self._body_bytes = ''
236
158
        self.response = None
237
159
        self.finished_reading = False
238
160
        self._command = None
239
161
 
240
162
    def accept_body(self, bytes):
241
163
        """Accept body data."""
242
 
        self._run_handler_code(self._command.do_chunk, (bytes,), {})
 
164
 
 
165
        # TODO: This should be overriden for each command that desired body data
 
166
        # to handle the right format of that data, i.e. plain bytes, a bundle,
 
167
        # etc.  The deserialisation into that format should be done in the
 
168
        # Protocol object.
 
169
 
 
170
        # default fallback is to accumulate bytes.
 
171
        self._body_bytes += bytes
243
172
        
244
173
    def end_of_body(self):
245
174
        """No more body data will be received."""
246
 
        self._run_handler_code(self._command.do_end, (), {})
 
175
        self._run_handler_code(self._command.do_body, (self._body_bytes,), {})
247
176
        # cannot read after this.
248
177
        self.finished_reading = True
249
178
 
252
181
        try:
253
182
            command = self._commands.get(cmd)
254
183
        except LookupError:
255
 
            raise errors.UnknownSmartMethod(cmd)
256
 
        self._command = command(self._backing_transport, self._root_client_path)
 
184
            raise errors.SmartProtocolError("bad request %r" % (cmd,))
 
185
        self._command = command(self._backing_transport)
257
186
        self._run_handler_code(self._command.execute, args, {})
258
187
 
259
188
    def _run_handler_code(self, callable, args, kwargs):
286
215
        except errors.ShortReadvError, e:
287
216
            return FailedSmartServerResponse(('ShortReadvError',
288
217
                e.path, str(e.offset), str(e.length), str(e.actual)))
289
 
        except errors.UnstackableRepositoryFormat, e:
290
 
            return FailedSmartServerResponse(('UnstackableRepositoryFormat',
291
 
                str(e.format), e.url))
292
 
        except errors.UnstackableBranchFormat, e:
293
 
            return FailedSmartServerResponse(('UnstackableBranchFormat',
294
 
                str(e.format), e.url))
295
 
        except errors.NotStacked, e:
296
 
            return FailedSmartServerResponse(('NotStacked',))
297
218
        except UnicodeError, e:
298
219
            # If it is a DecodeError, than most likely we are starting
299
220
            # with a plain string
300
221
            str_or_unicode = e.object
301
222
            if isinstance(str_or_unicode, unicode):
302
 
                # XXX: UTF-8 might have \x01 (our protocol v1 and v2 seperator
303
 
                # byte) in it, so this encoding could cause broken responses.
304
 
                # Newer clients use protocol v3, so will be fine.
 
223
                # XXX: UTF-8 might have \x01 (our seperator byte) in it.  We
 
224
                # should escape it somehow.
305
225
                val = 'u:' + str_or_unicode.encode('utf-8')
306
226
            else:
307
227
                val = 's:' + str_or_unicode.encode('base64')
313
233
                return FailedSmartServerResponse(('ReadOnlyError', ))
314
234
            else:
315
235
                raise
316
 
        except errors.ReadError, e:
317
 
            # cannot read the file
318
 
            return FailedSmartServerResponse(('ReadError', e.path))
319
 
        except errors.PermissionDenied, e:
320
 
            return FailedSmartServerResponse(
321
 
                ('PermissionDenied', e.path, e.extra))
322
 
 
323
 
    def headers_received(self, headers):
324
 
        # Just a no-op at the moment.
325
 
        pass
326
 
 
327
 
    def args_received(self, args):
328
 
        cmd = args[0]
329
 
        args = args[1:]
330
 
        try:
331
 
            command = self._commands.get(cmd)
332
 
        except LookupError:
333
 
            raise errors.UnknownSmartMethod(cmd)
334
 
        self._command = command(self._backing_transport)
335
 
        self._run_handler_code(self._command.execute, args, {})
336
 
 
337
 
    def end_received(self):
338
 
        self._run_handler_code(self._command.do_end, (), {})
339
 
 
340
 
    def post_body_error_received(self, error_args):
341
 
        # Just a no-op at the moment.
342
 
        pass
343
236
 
344
237
 
345
238
class HelloRequest(SmartServerRequest):
356
249
 
357
250
    def do(self, path, revision_id):
358
251
        # open transport relative to our base
359
 
        t = self.transport_from_client_path(path)
 
252
        t = self._backing_transport.clone(path)
360
253
        control, extra_path = bzrdir.BzrDir.open_containing_from_transport(t)
361
254
        repo = control.open_repository()
362
255
        tmpf = tempfile.TemporaryFile()
363
256
        base_revision = revision.NULL_REVISION
364
 
        serializer.write_bundle(repo, revision_id, base_revision, tmpf)
 
257
        write_bundle(repo, revision_id, base_revision, tmpf)
365
258
        tmpf.seek(0)
366
259
        return SuccessfulSmartServerResponse((), tmpf.read())
367
260
 
383
276
request_handlers.register_lazy(
384
277
    'Branch.get_config_file', 'bzrlib.smart.branch', 'SmartServerBranchGetConfigFile')
385
278
request_handlers.register_lazy(
386
 
    'Branch.get_stacked_on_url', 'bzrlib.smart.branch', 'SmartServerBranchRequestGetStackedOnURL')
387
 
request_handlers.register_lazy(
388
279
    'Branch.last_revision_info', 'bzrlib.smart.branch', 'SmartServerBranchRequestLastRevisionInfo')
389
280
request_handlers.register_lazy(
390
281
    'Branch.lock_write', 'bzrlib.smart.branch', 'SmartServerBranchRequestLockWrite')
393
284
request_handlers.register_lazy(
394
285
    'Branch.set_last_revision', 'bzrlib.smart.branch', 'SmartServerBranchRequestSetLastRevision')
395
286
request_handlers.register_lazy(
396
 
    'Branch.set_last_revision_info', 'bzrlib.smart.branch',
397
 
    'SmartServerBranchRequestSetLastRevisionInfo')
398
 
request_handlers.register_lazy(
399
 
    'Branch.set_last_revision_ex', 'bzrlib.smart.branch',
400
 
    'SmartServerBranchRequestSetLastRevisionEx')
401
 
request_handlers.register_lazy(
402
287
    'Branch.unlock', 'bzrlib.smart.branch', 'SmartServerBranchRequestUnlock')
403
288
request_handlers.register_lazy(
404
289
    'BzrDir.find_repository', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepositoryV1')
434
319
    'readv', 'bzrlib.smart.vfs', 'ReadvRequest')
435
320
request_handlers.register_lazy(
436
321
    'rename', 'bzrlib.smart.vfs', 'RenameRequest')
437
 
request_handlers.register_lazy(
438
 
    'PackRepository.autopack', 'bzrlib.smart.packrepository',
439
 
    'SmartServerPackRepositoryAutopack')
440
322
request_handlers.register_lazy('Repository.gather_stats',
441
323
                               'bzrlib.smart.repository',
442
324
                               'SmartServerRepositoryGatherStats')
444
326
                               'bzrlib.smart.repository',
445
327
                               'SmartServerRepositoryGetParentMap')
446
328
request_handlers.register_lazy(
 
329
    'Repository.stream_knit_data_for_revisions',
 
330
    'bzrlib.smart.repository',
 
331
    'SmartServerRepositoryStreamKnitDataForRevisions')
 
332
request_handlers.register_lazy(
 
333
    'Repository.stream_revisions_chunked',
 
334
    'bzrlib.smart.repository',
 
335
    'SmartServerRepositoryStreamRevisionsChunked')
 
336
request_handlers.register_lazy(
447
337
    'Repository.get_revision_graph', 'bzrlib.smart.repository', 'SmartServerRepositoryGetRevisionGraph')
448
338
request_handlers.register_lazy(
449
339
    'Repository.has_revision', 'bzrlib.smart.repository', 'SmartServerRequestHasRevision')