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

  • Committer: Andrew Bennetts
  • Date: 2007-12-05 07:09:42 UTC
  • mto: This revision was merged to the branch mainline in revision 3320.
  • Revision ID: andrew.bennetts@canonical.com-20071205070942-3mf3s43nad5xi7if
More docstring polish

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006, 2007 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
"""Basic server-side logic for dealing with requests."""
 
18
 
 
19
 
 
20
import tempfile
 
21
 
 
22
from bzrlib import (
 
23
    bzrdir,
 
24
    errors,
 
25
    registry,
 
26
    revision,
 
27
    urlutils,
 
28
    )
 
29
from bzrlib.bundle.serializer import write_bundle
 
30
from bzrlib.trace import mutter
 
31
from bzrlib.transport import get_transport
 
32
from bzrlib.transport.chroot import ChrootServer
 
33
 
 
34
 
 
35
class SmartServerRequest(object):
 
36
    """Base class for request handlers.
 
37
    
 
38
    To define a new request, subclass this class and override the `do` method
 
39
    (and if appropriate, `do_body` as well).  Request implementors should take
 
40
    care to call `translate_client_path` and `transport_from_client_path` as
 
41
    appropriate when dealing with paths received from the client.
 
42
    """
 
43
 
 
44
    def __init__(self, backing_transport, root_client_path='/'):
 
45
        """Constructor.
 
46
 
 
47
        :param backing_transport: the base transport to be used when performing
 
48
            this request.
 
49
        :param root_client_path: the client path that maps to the root of
 
50
            backing_transport.  This is used to interpret relpaths received
 
51
            from the client.  Clients will not be able to refer to paths above
 
52
            this root.
 
53
        """
 
54
        self._backing_transport = backing_transport
 
55
        if not root_client_path.startswith('/'):
 
56
            root_client_path = '/' + root_client_path
 
57
        if not root_client_path.endswith('/'):
 
58
            root_client_path += '/'
 
59
        self._root_client_path = root_client_path
 
60
 
 
61
    def _check_enabled(self):
 
62
        """Raises DisabledMethod if this method is disabled."""
 
63
        pass
 
64
 
 
65
    def do(self, *args):
 
66
        """Mandatory extension point for SmartServerRequest subclasses.
 
67
        
 
68
        Subclasses must implement this.
 
69
        
 
70
        This should return a SmartServerResponse if this command expects to
 
71
        receive no body.
 
72
        """
 
73
        raise NotImplementedError(self.do)
 
74
 
 
75
    def execute(self, *args):
 
76
        """Public entry point to execute this request.
 
77
 
 
78
        It will return a SmartServerResponse if the command does not expect a
 
79
        body.
 
80
 
 
81
        :param *args: the arguments of the request.
 
82
        """
 
83
        self._check_enabled()
 
84
        return self.do(*args)
 
85
 
 
86
    def do_body(self, body_bytes):
 
87
        """Called if the client sends a body with the request.
 
88
        
 
89
        Must return a SmartServerResponse.
 
90
        """
 
91
        # TODO: if a client erroneously sends a request that shouldn't have a
 
92
        # body, what to do?  Probably SmartServerRequestHandler should catch
 
93
        # this NotImplementedError and translate it into a 'bad request' error
 
94
        # to send to the client.
 
95
        raise NotImplementedError(self.do_body)
 
96
    
 
97
    def translate_client_path(self, client_path):
 
98
        """Translate a path received from a network client into a local
 
99
        relpath.
 
100
 
 
101
        All paths received from the client *must* be translated.
 
102
 
 
103
        :returns: a relpath that may be used with self._backing_transport
 
104
        """
 
105
        if not client_path.startswith('/'):
 
106
            client_path = '/' + client_path
 
107
        if client_path.startswith(self._root_client_path):
 
108
            path = client_path[len(self._root_client_path):]
 
109
            relpath = urlutils.joinpath('/', path)
 
110
            assert relpath.startswith('/')
 
111
            return '.' + relpath
 
112
        else:
 
113
            raise errors.PathNotChild(client_path, self._root_client_path)
 
114
 
 
115
    def transport_from_client_path(self, client_path):
 
116
        """Get a backing transport corresponding to the location referred to by
 
117
        a network client.
 
118
 
 
119
        :seealso: translate_client_path
 
120
        :returns: a transport cloned from self._backing_transport
 
121
        """
 
122
        relpath = self.translate_client_path(client_path)
 
123
        return self._backing_transport.clone(relpath)
 
124
 
 
125
 
 
126
class SmartServerResponse(object):
 
127
    """A response to a client request.
 
128
    
 
129
    This base class should not be used. Instead use
 
130
    SuccessfulSmartServerResponse and FailedSmartServerResponse as appropriate.
 
131
    """
 
132
 
 
133
    def __init__(self, args, body=None, body_stream=None):
 
134
        """Constructor.
 
135
 
 
136
        :param args: tuple of response arguments.
 
137
        :param body: string of a response body.
 
138
        :param body_stream: iterable of bytestrings to be streamed to the
 
139
            client.
 
140
        """
 
141
        self.args = args
 
142
        if body is not None and body_stream is not None:
 
143
            raise errors.BzrError(
 
144
                "'body' and 'body_stream' are mutually exclusive.")
 
145
        self.body = body
 
146
        self.body_stream = body_stream
 
147
 
 
148
    def __eq__(self, other):
 
149
        if other is None:
 
150
            return False
 
151
        return (other.args == self.args and
 
152
                other.body == self.body and
 
153
                other.body_stream is self.body_stream)
 
154
 
 
155
    def __repr__(self):
 
156
        status = {True: 'OK', False: 'ERR'}[self.is_successful()]
 
157
        return "<SmartServerResponse status=%s args=%r body=%r>" % (status,
 
158
            self.args, self.body)
 
159
 
 
160
 
 
161
class FailedSmartServerResponse(SmartServerResponse):
 
162
    """A SmartServerResponse for a request which failed."""
 
163
 
 
164
    def is_successful(self):
 
165
        """FailedSmartServerResponse are not successful."""
 
166
        return False
 
167
 
 
168
 
 
169
class SuccessfulSmartServerResponse(SmartServerResponse):
 
170
    """A SmartServerResponse for a successfully completed request."""
 
171
 
 
172
    def is_successful(self):
 
173
        """SuccessfulSmartServerResponse are successful."""
 
174
        return True
 
175
 
 
176
 
 
177
class SmartServerRequestHandler(object):
 
178
    """Protocol logic for smart server.
 
179
    
 
180
    This doesn't handle serialization at all, it just processes requests and
 
181
    creates responses.
 
182
    """
 
183
 
 
184
    # IMPORTANT FOR IMPLEMENTORS: It is important that SmartServerRequestHandler
 
185
    # not contain encoding or decoding logic to allow the wire protocol to vary
 
186
    # from the object protocol: we will want to tweak the wire protocol separate
 
187
    # from the object model, and ideally we will be able to do that without
 
188
    # having a SmartServerRequestHandler subclass for each wire protocol, rather
 
189
    # just a Protocol subclass.
 
190
 
 
191
    # TODO: Better way of representing the body for commands that take it,
 
192
    # and allow it to be streamed into the server.
 
193
 
 
194
    def __init__(self, backing_transport, commands, root_client_path):
 
195
        """Constructor.
 
196
 
 
197
        :param backing_transport: a Transport to handle requests for.
 
198
        :param commands: a registry mapping command names to SmartServerRequest
 
199
            subclasses. e.g. bzrlib.transport.smart.vfs.vfs_commands.
 
200
        """
 
201
        self._backing_transport = backing_transport
 
202
        self._root_client_path = root_client_path
 
203
        self._commands = commands
 
204
        self._body_bytes = ''
 
205
        self.response = None
 
206
        self.finished_reading = False
 
207
        self._command = None
 
208
 
 
209
    def accept_body(self, bytes):
 
210
        """Accept body data."""
 
211
 
 
212
        # TODO: This should be overriden for each command that desired body data
 
213
        # to handle the right format of that data, i.e. plain bytes, a bundle,
 
214
        # etc.  The deserialisation into that format should be done in the
 
215
        # Protocol object.
 
216
 
 
217
        # default fallback is to accumulate bytes.
 
218
        self._body_bytes += bytes
 
219
        
 
220
    def end_of_body(self):
 
221
        """No more body data will be received."""
 
222
        self._run_handler_code(self._command.do_body, (self._body_bytes,), {})
 
223
        # cannot read after this.
 
224
        self.finished_reading = True
 
225
 
 
226
    def dispatch_command(self, cmd, args):
 
227
        """Deprecated compatibility method.""" # XXX XXX
 
228
        try:
 
229
            command = self._commands.get(cmd)
 
230
        except LookupError:
 
231
            raise errors.SmartProtocolError("bad request %r" % (cmd,))
 
232
        self._command = command(self._backing_transport, self._root_client_path)
 
233
        self._run_handler_code(self._command.execute, args, {})
 
234
 
 
235
    def _run_handler_code(self, callable, args, kwargs):
 
236
        """Run some handler specific code 'callable'.
 
237
 
 
238
        If a result is returned, it is considered to be the commands response,
 
239
        and finished_reading is set true, and its assigned to self.response.
 
240
 
 
241
        Any exceptions caught are translated and a response object created
 
242
        from them.
 
243
        """
 
244
        result = self._call_converting_errors(callable, args, kwargs)
 
245
 
 
246
        if result is not None:
 
247
            self.response = result
 
248
            self.finished_reading = True
 
249
 
 
250
    def _call_converting_errors(self, callable, args, kwargs):
 
251
        """Call callable converting errors to Response objects."""
 
252
        # XXX: most of this error conversion is VFS-related, and thus ought to
 
253
        # be in SmartServerVFSRequestHandler somewhere.
 
254
        try:
 
255
            return callable(*args, **kwargs)
 
256
        except errors.NoSuchFile, e:
 
257
            return FailedSmartServerResponse(('NoSuchFile', e.path))
 
258
        except errors.FileExists, e:
 
259
            return FailedSmartServerResponse(('FileExists', e.path))
 
260
        except errors.DirectoryNotEmpty, e:
 
261
            return FailedSmartServerResponse(('DirectoryNotEmpty', e.path))
 
262
        except errors.ShortReadvError, e:
 
263
            return FailedSmartServerResponse(('ShortReadvError',
 
264
                e.path, str(e.offset), str(e.length), str(e.actual)))
 
265
        except UnicodeError, e:
 
266
            # If it is a DecodeError, than most likely we are starting
 
267
            # with a plain string
 
268
            str_or_unicode = e.object
 
269
            if isinstance(str_or_unicode, unicode):
 
270
                # XXX: UTF-8 might have \x01 (our seperator byte) in it.  We
 
271
                # should escape it somehow.
 
272
                val = 'u:' + str_or_unicode.encode('utf-8')
 
273
            else:
 
274
                val = 's:' + str_or_unicode.encode('base64')
 
275
            # This handles UnicodeEncodeError or UnicodeDecodeError
 
276
            return FailedSmartServerResponse((e.__class__.__name__,
 
277
                    e.encoding, val, str(e.start), str(e.end), e.reason))
 
278
        except errors.TransportNotPossible, e:
 
279
            if e.msg == "readonly transport":
 
280
                return FailedSmartServerResponse(('ReadOnlyError', ))
 
281
            else:
 
282
                raise
 
283
 
 
284
 
 
285
class HelloRequest(SmartServerRequest):
 
286
    """Answer a version request with the highest protocol version this server
 
287
    supports.
 
288
    """
 
289
 
 
290
    def do(self):
 
291
        return SuccessfulSmartServerResponse(('ok', '2'))
 
292
 
 
293
 
 
294
class GetBundleRequest(SmartServerRequest):
 
295
    """Get a bundle of from the null revision to the specified revision."""
 
296
 
 
297
    def do(self, path, revision_id):
 
298
        # open transport relative to our base
 
299
        t = self.transport_from_client_path(path)
 
300
        control, extra_path = bzrdir.BzrDir.open_containing_from_transport(t)
 
301
        repo = control.open_repository()
 
302
        tmpf = tempfile.TemporaryFile()
 
303
        base_revision = revision.NULL_REVISION
 
304
        write_bundle(repo, revision_id, base_revision, tmpf)
 
305
        tmpf.seek(0)
 
306
        return SuccessfulSmartServerResponse((), tmpf.read())
 
307
 
 
308
 
 
309
class SmartServerIsReadonly(SmartServerRequest):
 
310
    # XXX: this request method belongs somewhere else.
 
311
 
 
312
    def do(self):
 
313
        if self._backing_transport.is_readonly():
 
314
            answer = 'yes'
 
315
        else:
 
316
            answer = 'no'
 
317
        return SuccessfulSmartServerResponse((answer,))
 
318
 
 
319
 
 
320
request_handlers = registry.Registry()
 
321
request_handlers.register_lazy(
 
322
    'append', 'bzrlib.smart.vfs', 'AppendRequest')
 
323
request_handlers.register_lazy(
 
324
    'Branch.get_config_file', 'bzrlib.smart.branch', 'SmartServerBranchGetConfigFile')
 
325
request_handlers.register_lazy(
 
326
    'Branch.last_revision_info', 'bzrlib.smart.branch', 'SmartServerBranchRequestLastRevisionInfo')
 
327
request_handlers.register_lazy(
 
328
    'Branch.lock_write', 'bzrlib.smart.branch', 'SmartServerBranchRequestLockWrite')
 
329
request_handlers.register_lazy(
 
330
    'Branch.revision_history', 'bzrlib.smart.branch', 'SmartServerRequestRevisionHistory')
 
331
request_handlers.register_lazy(
 
332
    'Branch.set_last_revision', 'bzrlib.smart.branch', 'SmartServerBranchRequestSetLastRevision')
 
333
request_handlers.register_lazy(
 
334
    'Branch.unlock', 'bzrlib.smart.branch', 'SmartServerBranchRequestUnlock')
 
335
request_handlers.register_lazy(
 
336
    'BzrDir.find_repository', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepository')
 
337
request_handlers.register_lazy(
 
338
    'BzrDirFormat.initialize', 'bzrlib.smart.bzrdir', 'SmartServerRequestInitializeBzrDir')
 
339
request_handlers.register_lazy(
 
340
    'BzrDir.open_branch', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBranch')
 
341
request_handlers.register_lazy(
 
342
    'delete', 'bzrlib.smart.vfs', 'DeleteRequest')
 
343
request_handlers.register_lazy(
 
344
    'get', 'bzrlib.smart.vfs', 'GetRequest')
 
345
request_handlers.register_lazy(
 
346
    'get_bundle', 'bzrlib.smart.request', 'GetBundleRequest')
 
347
request_handlers.register_lazy(
 
348
    'has', 'bzrlib.smart.vfs', 'HasRequest')
 
349
request_handlers.register_lazy(
 
350
    'hello', 'bzrlib.smart.request', 'HelloRequest')
 
351
request_handlers.register_lazy(
 
352
    'iter_files_recursive', 'bzrlib.smart.vfs', 'IterFilesRecursiveRequest')
 
353
request_handlers.register_lazy(
 
354
    'list_dir', 'bzrlib.smart.vfs', 'ListDirRequest')
 
355
request_handlers.register_lazy(
 
356
    'mkdir', 'bzrlib.smart.vfs', 'MkdirRequest')
 
357
request_handlers.register_lazy(
 
358
    'move', 'bzrlib.smart.vfs', 'MoveRequest')
 
359
request_handlers.register_lazy(
 
360
    'put', 'bzrlib.smart.vfs', 'PutRequest')
 
361
request_handlers.register_lazy(
 
362
    'put_non_atomic', 'bzrlib.smart.vfs', 'PutNonAtomicRequest')
 
363
request_handlers.register_lazy(
 
364
    'readv', 'bzrlib.smart.vfs', 'ReadvRequest')
 
365
request_handlers.register_lazy(
 
366
    'rename', 'bzrlib.smart.vfs', 'RenameRequest')
 
367
request_handlers.register_lazy('Repository.gather_stats',
 
368
                               'bzrlib.smart.repository',
 
369
                               'SmartServerRepositoryGatherStats')
 
370
request_handlers.register_lazy(
 
371
    'Repository.stream_knit_data_for_revisions', 'bzrlib.smart.repository',
 
372
    'SmartServerRepositoryStreamKnitDataForRevisions')
 
373
request_handlers.register_lazy(
 
374
    'Repository.get_revision_graph', 'bzrlib.smart.repository', 'SmartServerRepositoryGetRevisionGraph')
 
375
request_handlers.register_lazy(
 
376
    'Repository.has_revision', 'bzrlib.smart.repository', 'SmartServerRequestHasRevision')
 
377
request_handlers.register_lazy(
 
378
    'Repository.is_shared', 'bzrlib.smart.repository', 'SmartServerRepositoryIsShared')
 
379
request_handlers.register_lazy(
 
380
    'Repository.lock_write', 'bzrlib.smart.repository', 'SmartServerRepositoryLockWrite')
 
381
request_handlers.register_lazy(
 
382
    'Repository.unlock', 'bzrlib.smart.repository', 'SmartServerRepositoryUnlock')
 
383
request_handlers.register_lazy(
 
384
    'Repository.tarball', 'bzrlib.smart.repository',
 
385
    'SmartServerRepositoryTarball')
 
386
request_handlers.register_lazy(
 
387
    'rmdir', 'bzrlib.smart.vfs', 'RmdirRequest')
 
388
request_handlers.register_lazy(
 
389
    'stat', 'bzrlib.smart.vfs', 'StatRequest')
 
390
request_handlers.register_lazy(
 
391
    'Transport.is_readonly', 'bzrlib.smart.request', 'SmartServerIsReadonly')
 
392
request_handlers.register_lazy(
 
393
    'BzrDir.open', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBzrDir')