1
# Copyright (C) 2006, 2007 Canonical Ltd
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.
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.
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
17
"""Basic server-side logic for dealing with requests.
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.
25
The request_handlers registry tracks SmartServerRequest classes (rather than
26
SmartServerRequestHandler).
38
from bzrlib.lazy_import import lazy_import
39
lazy_import(globals(), """
40
from bzrlib.bundle import serializer
44
class SmartServerRequest(object):
45
"""Base class for request handlers.
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.
52
# XXX: rename this class to BaseSmartServerRequestHandler ? A request
53
# *handler* is a different concept to the request.
55
def __init__(self, backing_transport, root_client_path='/'):
58
:param backing_transport: the base transport to be used when performing
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 '/'.
66
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
74
def _check_enabled(self):
75
"""Raises DisabledMethod if this method is disabled."""
79
"""Mandatory extension point for SmartServerRequest subclasses.
81
Subclasses must implement this.
83
This should return a SmartServerResponse if this command expects to
86
raise NotImplementedError(self.do)
88
def execute(self, *args):
89
"""Public entry point to execute this request.
91
It will return a SmartServerResponse if the command does not expect a
94
:param *args: the arguments of the request.
99
def do_body(self, body_bytes):
100
"""Called if the client sends a body with the request.
102
The do() method is still called, and must have returned None.
104
Must return a SmartServerResponse.
106
raise NotImplementedError(self.do_body)
108
def do_chunk(self, chunk_bytes):
109
"""Called with each body chunk if the request has a streamed body.
111
The do() method is still called, and must have returned None.
113
raise NotImplementedError(self.do_chunk)
116
"""Called when the end of the request has been received."""
119
def translate_client_path(self, client_path):
120
"""Translate a path received from a network client into a local
123
All paths received from the client *must* be translated.
125
:param client_path: the path from the client.
126
:returns: a relpath that may be used with self._backing_transport
127
(unlike the untranslated client_path, which must not be used with
128
the backing transport).
130
if self._root_client_path is None:
131
# no translation necessary!
133
if not client_path.startswith('/'):
134
client_path = '/' + client_path
135
if client_path.startswith(self._root_client_path):
136
path = client_path[len(self._root_client_path):]
137
relpath = urlutils.joinpath('/', path)
138
if not relpath.startswith('/'):
139
raise ValueError(relpath)
142
raise errors.PathNotChild(client_path, self._root_client_path)
144
def transport_from_client_path(self, client_path):
145
"""Get a backing transport corresponding to the location referred to by
148
:seealso: translate_client_path
149
:returns: a transport cloned from self._backing_transport
151
relpath = self.translate_client_path(client_path)
152
return self._backing_transport.clone(relpath)
155
class SmartServerResponse(object):
156
"""A response to a client request.
158
This base class should not be used. Instead use
159
SuccessfulSmartServerResponse and FailedSmartServerResponse as appropriate.
162
def __init__(self, args, body=None, body_stream=None):
165
:param args: tuple of response arguments.
166
:param body: string of a response body.
167
:param body_stream: iterable of bytestrings to be streamed to the
171
if body is not None and body_stream is not None:
172
raise errors.BzrError(
173
"'body' and 'body_stream' are mutually exclusive.")
175
self.body_stream = body_stream
177
def __eq__(self, other):
180
return (other.args == self.args and
181
other.body == self.body and
182
other.body_stream is self.body_stream)
185
status = {True: 'OK', False: 'ERR'}[self.is_successful()]
186
return "<SmartServerResponse status=%s args=%r body=%r>" % (status,
187
self.args, self.body)
190
class FailedSmartServerResponse(SmartServerResponse):
191
"""A SmartServerResponse for a request which failed."""
193
def is_successful(self):
194
"""FailedSmartServerResponse are not successful."""
198
class SuccessfulSmartServerResponse(SmartServerResponse):
199
"""A SmartServerResponse for a successfully completed request."""
201
def is_successful(self):
202
"""SuccessfulSmartServerResponse are successful."""
206
class SmartServerRequestHandler(object):
207
"""Protocol logic for smart server.
209
This doesn't handle serialization at all, it just processes requests and
213
# IMPORTANT FOR IMPLEMENTORS: It is important that SmartServerRequestHandler
214
# not contain encoding or decoding logic to allow the wire protocol to vary
215
# from the object protocol: we will want to tweak the wire protocol separate
216
# from the object model, and ideally we will be able to do that without
217
# having a SmartServerRequestHandler subclass for each wire protocol, rather
218
# just a Protocol subclass.
220
# TODO: Better way of representing the body for commands that take it,
221
# and allow it to be streamed into the server.
223
def __init__(self, backing_transport, commands, root_client_path):
226
:param backing_transport: a Transport to handle requests for.
227
:param commands: a registry mapping command names to SmartServerRequest
228
subclasses. e.g. bzrlib.transport.smart.vfs.vfs_commands.
230
self._backing_transport = backing_transport
231
self._root_client_path = root_client_path
232
self._commands = commands
233
self._body_bytes = ''
235
self.finished_reading = False
238
def accept_body(self, bytes):
239
"""Accept body data."""
241
# TODO: This should be overriden for each command that desired body data
242
# to handle the right format of that data, i.e. plain bytes, a bundle,
243
# etc. The deserialisation into that format should be done in the
246
# default fallback is to accumulate bytes.
247
self._body_bytes += bytes
249
def end_of_body(self):
250
"""No more body data will be received."""
251
self._run_handler_code(self._command.do_body, (self._body_bytes,), {})
252
# cannot read after this.
253
self.finished_reading = True
255
def dispatch_command(self, cmd, args):
256
"""Deprecated compatibility method.""" # XXX XXX
258
command = self._commands.get(cmd)
260
raise errors.UnknownSmartMethod(cmd)
261
self._command = command(self._backing_transport, self._root_client_path)
262
self._run_handler_code(self._command.execute, args, {})
264
def _run_handler_code(self, callable, args, kwargs):
265
"""Run some handler specific code 'callable'.
267
If a result is returned, it is considered to be the commands response,
268
and finished_reading is set true, and its assigned to self.response.
270
Any exceptions caught are translated and a response object created
273
result = self._call_converting_errors(callable, args, kwargs)
275
if result is not None:
276
self.response = result
277
self.finished_reading = True
279
def _call_converting_errors(self, callable, args, kwargs):
280
"""Call callable converting errors to Response objects."""
281
# XXX: most of this error conversion is VFS-related, and thus ought to
282
# be in SmartServerVFSRequestHandler somewhere.
284
return callable(*args, **kwargs)
285
except errors.NoSuchFile, e:
286
return FailedSmartServerResponse(('NoSuchFile', e.path))
287
except errors.FileExists, e:
288
return FailedSmartServerResponse(('FileExists', e.path))
289
except errors.DirectoryNotEmpty, e:
290
return FailedSmartServerResponse(('DirectoryNotEmpty', e.path))
291
except errors.ShortReadvError, e:
292
return FailedSmartServerResponse(('ShortReadvError',
293
e.path, str(e.offset), str(e.length), str(e.actual)))
294
except UnicodeError, e:
295
# If it is a DecodeError, than most likely we are starting
296
# with a plain string
297
str_or_unicode = e.object
298
if isinstance(str_or_unicode, unicode):
299
# XXX: UTF-8 might have \x01 (our seperator byte) in it. We
300
# should escape it somehow.
301
val = 'u:' + str_or_unicode.encode('utf-8')
303
val = 's:' + str_or_unicode.encode('base64')
304
# This handles UnicodeEncodeError or UnicodeDecodeError
305
return FailedSmartServerResponse((e.__class__.__name__,
306
e.encoding, val, str(e.start), str(e.end), e.reason))
307
except errors.TransportNotPossible, e:
308
if e.msg == "readonly transport":
309
return FailedSmartServerResponse(('ReadOnlyError', ))
313
def headers_received(self, headers):
314
# Just a no-op at the moment.
317
def args_received(self, args):
321
command = self._commands.get(cmd)
323
raise errors.UnknownSmartMethod(cmd)
324
self._command = command(self._backing_transport)
325
self._run_handler_code(self._command.execute, args, {})
327
def prefixed_body_received(self, body_bytes):
328
"""No more body data will be received."""
329
self._run_handler_code(self._command.do_body, (body_bytes,), {})
330
# cannot read after this.
331
self.finished_reading = True
333
def body_chunk_received(self, chunk_bytes):
334
self._run_handler_code(self._command.do_chunk, (chunk_bytes,), {})
336
def end_received(self):
337
self._run_handler_code(self._command.do_end, (), {})
340
class HelloRequest(SmartServerRequest):
341
"""Answer a version request with the highest protocol version this server
346
return SuccessfulSmartServerResponse(('ok', '2'))
349
class GetBundleRequest(SmartServerRequest):
350
"""Get a bundle of from the null revision to the specified revision."""
352
def do(self, path, revision_id):
353
# open transport relative to our base
354
t = self.transport_from_client_path(path)
355
control, extra_path = bzrdir.BzrDir.open_containing_from_transport(t)
356
repo = control.open_repository()
357
tmpf = tempfile.TemporaryFile()
358
base_revision = revision.NULL_REVISION
359
serializer.write_bundle(repo, revision_id, base_revision, tmpf)
361
return SuccessfulSmartServerResponse((), tmpf.read())
364
class SmartServerIsReadonly(SmartServerRequest):
365
# XXX: this request method belongs somewhere else.
368
if self._backing_transport.is_readonly():
372
return SuccessfulSmartServerResponse((answer,))
375
request_handlers = registry.Registry()
376
request_handlers.register_lazy(
377
'append', 'bzrlib.smart.vfs', 'AppendRequest')
378
request_handlers.register_lazy(
379
'Branch.get_config_file', 'bzrlib.smart.branch', 'SmartServerBranchGetConfigFile')
380
request_handlers.register_lazy(
381
'Branch.last_revision_info', 'bzrlib.smart.branch', 'SmartServerBranchRequestLastRevisionInfo')
382
request_handlers.register_lazy(
383
'Branch.lock_write', 'bzrlib.smart.branch', 'SmartServerBranchRequestLockWrite')
384
request_handlers.register_lazy(
385
'Branch.revision_history', 'bzrlib.smart.branch', 'SmartServerRequestRevisionHistory')
386
request_handlers.register_lazy(
387
'Branch.set_last_revision', 'bzrlib.smart.branch', 'SmartServerBranchRequestSetLastRevision')
388
request_handlers.register_lazy(
389
'Branch.set_last_revision_info', 'bzrlib.smart.branch',
390
'SmartServerBranchRequestSetLastRevisionInfo')
391
request_handlers.register_lazy(
392
'Branch.set_last_revision_ex', 'bzrlib.smart.branch',
393
'SmartServerBranchRequestSetLastRevisionEx')
394
request_handlers.register_lazy(
395
'Branch.unlock', 'bzrlib.smart.branch', 'SmartServerBranchRequestUnlock')
396
request_handlers.register_lazy(
397
'BzrDir.find_repository', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepositoryV1')
398
request_handlers.register_lazy(
399
'BzrDir.find_repositoryV2', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepositoryV2')
400
request_handlers.register_lazy(
401
'BzrDirFormat.initialize', 'bzrlib.smart.bzrdir', 'SmartServerRequestInitializeBzrDir')
402
request_handlers.register_lazy(
403
'BzrDir.open_branch', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBranch')
404
request_handlers.register_lazy(
405
'delete', 'bzrlib.smart.vfs', 'DeleteRequest')
406
request_handlers.register_lazy(
407
'get', 'bzrlib.smart.vfs', 'GetRequest')
408
request_handlers.register_lazy(
409
'get_bundle', 'bzrlib.smart.request', 'GetBundleRequest')
410
request_handlers.register_lazy(
411
'has', 'bzrlib.smart.vfs', 'HasRequest')
412
request_handlers.register_lazy(
413
'hello', 'bzrlib.smart.request', 'HelloRequest')
414
request_handlers.register_lazy(
415
'iter_files_recursive', 'bzrlib.smart.vfs', 'IterFilesRecursiveRequest')
416
request_handlers.register_lazy(
417
'list_dir', 'bzrlib.smart.vfs', 'ListDirRequest')
418
request_handlers.register_lazy(
419
'mkdir', 'bzrlib.smart.vfs', 'MkdirRequest')
420
request_handlers.register_lazy(
421
'move', 'bzrlib.smart.vfs', 'MoveRequest')
422
request_handlers.register_lazy(
423
'put', 'bzrlib.smart.vfs', 'PutRequest')
424
request_handlers.register_lazy(
425
'put_non_atomic', 'bzrlib.smart.vfs', 'PutNonAtomicRequest')
426
request_handlers.register_lazy(
427
'readv', 'bzrlib.smart.vfs', 'ReadvRequest')
428
request_handlers.register_lazy(
429
'rename', 'bzrlib.smart.vfs', 'RenameRequest')
430
request_handlers.register_lazy('Repository.gather_stats',
431
'bzrlib.smart.repository',
432
'SmartServerRepositoryGatherStats')
433
request_handlers.register_lazy('Repository.get_parent_map',
434
'bzrlib.smart.repository',
435
'SmartServerRepositoryGetParentMap')
436
request_handlers.register_lazy(
437
'Repository.get_revision_graph', 'bzrlib.smart.repository', 'SmartServerRepositoryGetRevisionGraph')
438
request_handlers.register_lazy(
439
'Repository.has_revision', 'bzrlib.smart.repository', 'SmartServerRequestHasRevision')
440
request_handlers.register_lazy(
441
'Repository.is_shared', 'bzrlib.smart.repository', 'SmartServerRepositoryIsShared')
442
request_handlers.register_lazy(
443
'Repository.lock_write', 'bzrlib.smart.repository', 'SmartServerRepositoryLockWrite')
444
request_handlers.register_lazy(
445
'Repository.unlock', 'bzrlib.smart.repository', 'SmartServerRepositoryUnlock')
446
request_handlers.register_lazy(
447
'Repository.tarball', 'bzrlib.smart.repository',
448
'SmartServerRepositoryTarball')
449
request_handlers.register_lazy(
450
'rmdir', 'bzrlib.smart.vfs', 'RmdirRequest')
451
request_handlers.register_lazy(
452
'stat', 'bzrlib.smart.vfs', 'StatRequest')
453
request_handlers.register_lazy(
454
'Transport.is_readonly', 'bzrlib.smart.request', 'SmartServerIsReadonly')
455
request_handlers.register_lazy(
456
'BzrDir.open', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBzrDir')