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
73
self._body_chunks = []
75
def _check_enabled(self):
76
"""Raises DisabledMethod if this method is disabled."""
80
"""Mandatory extension point for SmartServerRequest subclasses.
82
Subclasses must implement this.
84
This should return a SmartServerResponse if this command expects to
87
raise NotImplementedError(self.do)
89
def execute(self, *args):
90
"""Public entry point to execute this request.
92
It will return a SmartServerResponse if the command does not expect a
95
:param *args: the arguments of the request.
100
def do_body(self, body_bytes):
101
"""Called if the client sends a body with the request.
103
The do() method is still called, and must have returned None.
105
Must return a SmartServerResponse.
108
raise errors.SmartProtocolError('Request does not expect a body')
110
def do_chunk(self, chunk_bytes):
111
"""Called with each body chunk if the request has a streamed body.
113
The do() method is still called, and must have returned None.
115
self._body_chunks.append(chunk_bytes)
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)
123
def translate_client_path(self, client_path):
124
"""Translate a path received from a network client into a local
127
All paths received from the client *must* be translated.
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).
134
if self._root_client_path is None:
135
# no translation necessary!
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)
146
raise errors.PathNotChild(client_path, self._root_client_path)
148
def transport_from_client_path(self, client_path):
149
"""Get a backing transport corresponding to the location referred to by
152
:seealso: translate_client_path
153
:returns: a transport cloned from self._backing_transport
155
relpath = self.translate_client_path(client_path)
156
return self._backing_transport.clone(relpath)
159
class SmartServerResponse(object):
160
"""A response to a client request.
162
This base class should not be used. Instead use
163
SuccessfulSmartServerResponse and FailedSmartServerResponse as appropriate.
166
def __init__(self, args, body=None, body_stream=None):
169
:param args: tuple of response arguments.
170
:param body: string of a response body.
171
:param body_stream: iterable of bytestrings to be streamed to the
175
if body is not None and body_stream is not None:
176
raise errors.BzrError(
177
"'body' and 'body_stream' are mutually exclusive.")
179
self.body_stream = body_stream
181
def __eq__(self, other):
184
return (other.args == self.args and
185
other.body == self.body and
186
other.body_stream is self.body_stream)
189
return "<%s args=%r body=%r>" % (self.__class__.__name__,
190
self.args, self.body)
193
class FailedSmartServerResponse(SmartServerResponse):
194
"""A SmartServerResponse for a request which failed."""
196
def is_successful(self):
197
"""FailedSmartServerResponse are not successful."""
201
class SuccessfulSmartServerResponse(SmartServerResponse):
202
"""A SmartServerResponse for a successfully completed request."""
204
def is_successful(self):
205
"""SuccessfulSmartServerResponse are successful."""
209
class SmartServerRequestHandler(object):
210
"""Protocol logic for smart server.
212
This doesn't handle serialization at all, it just processes requests and
216
# IMPORTANT FOR IMPLEMENTORS: It is important that SmartServerRequestHandler
217
# not contain encoding or decoding logic to allow the wire protocol to vary
218
# from the object protocol: we will want to tweak the wire protocol separate
219
# from the object model, and ideally we will be able to do that without
220
# having a SmartServerRequestHandler subclass for each wire protocol, rather
221
# just a Protocol subclass.
223
# TODO: Better way of representing the body for commands that take it,
224
# and allow it to be streamed into the server.
226
def __init__(self, backing_transport, commands, root_client_path):
229
:param backing_transport: a Transport to handle requests for.
230
:param commands: a registry mapping command names to SmartServerRequest
231
subclasses. e.g. bzrlib.transport.smart.vfs.vfs_commands.
233
self._backing_transport = backing_transport
234
self._root_client_path = root_client_path
235
self._commands = commands
237
self.finished_reading = False
240
def accept_body(self, bytes):
241
"""Accept body data."""
242
self._run_handler_code(self._command.do_chunk, (bytes,), {})
244
def end_of_body(self):
245
"""No more body data will be received."""
246
self._run_handler_code(self._command.do_end, (), {})
247
# cannot read after this.
248
self.finished_reading = True
250
def dispatch_command(self, cmd, args):
251
"""Deprecated compatibility method.""" # XXX XXX
253
command = self._commands.get(cmd)
255
raise errors.UnknownSmartMethod(cmd)
256
self._command = command(self._backing_transport, self._root_client_path)
257
self._run_handler_code(self._command.execute, args, {})
259
def _run_handler_code(self, callable, args, kwargs):
260
"""Run some handler specific code 'callable'.
262
If a result is returned, it is considered to be the commands response,
263
and finished_reading is set true, and its assigned to self.response.
265
Any exceptions caught are translated and a response object created
268
result = self._call_converting_errors(callable, args, kwargs)
270
if result is not None:
271
self.response = result
272
self.finished_reading = True
274
def _call_converting_errors(self, callable, args, kwargs):
275
"""Call callable converting errors to Response objects."""
276
# XXX: most of this error conversion is VFS-related, and thus ought to
277
# be in SmartServerVFSRequestHandler somewhere.
279
return callable(*args, **kwargs)
280
except errors.NoSuchFile, e:
281
return FailedSmartServerResponse(('NoSuchFile', e.path))
282
except errors.FileExists, e:
283
return FailedSmartServerResponse(('FileExists', e.path))
284
except errors.DirectoryNotEmpty, e:
285
return FailedSmartServerResponse(('DirectoryNotEmpty', e.path))
286
except errors.ShortReadvError, e:
287
return FailedSmartServerResponse(('ShortReadvError',
288
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
except UnicodeError, e:
298
# If it is a DecodeError, than most likely we are starting
299
# with a plain string
300
str_or_unicode = e.object
301
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.
305
val = 'u:' + str_or_unicode.encode('utf-8')
307
val = 's:' + str_or_unicode.encode('base64')
308
# This handles UnicodeEncodeError or UnicodeDecodeError
309
return FailedSmartServerResponse((e.__class__.__name__,
310
e.encoding, val, str(e.start), str(e.end), e.reason))
311
except errors.TransportNotPossible, e:
312
if e.msg == "readonly transport":
313
return FailedSmartServerResponse(('ReadOnlyError', ))
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))
323
def headers_received(self, headers):
324
# Just a no-op at the moment.
327
def args_received(self, args):
331
command = self._commands.get(cmd)
333
raise errors.UnknownSmartMethod(cmd)
334
self._command = command(self._backing_transport)
335
self._run_handler_code(self._command.execute, args, {})
337
def end_received(self):
338
self._run_handler_code(self._command.do_end, (), {})
340
def post_body_error_received(self, error_args):
341
# Just a no-op at the moment.
345
class HelloRequest(SmartServerRequest):
346
"""Answer a version request with the highest protocol version this server
351
return SuccessfulSmartServerResponse(('ok', '2'))
354
class GetBundleRequest(SmartServerRequest):
355
"""Get a bundle of from the null revision to the specified revision."""
357
def do(self, path, revision_id):
358
# open transport relative to our base
359
t = self.transport_from_client_path(path)
360
control, extra_path = bzrdir.BzrDir.open_containing_from_transport(t)
361
repo = control.open_repository()
362
tmpf = tempfile.TemporaryFile()
363
base_revision = revision.NULL_REVISION
364
serializer.write_bundle(repo, revision_id, base_revision, tmpf)
366
return SuccessfulSmartServerResponse((), tmpf.read())
369
class SmartServerIsReadonly(SmartServerRequest):
370
# XXX: this request method belongs somewhere else.
373
if self._backing_transport.is_readonly():
377
return SuccessfulSmartServerResponse((answer,))
380
request_handlers = registry.Registry()
381
request_handlers.register_lazy(
382
'append', 'bzrlib.smart.vfs', 'AppendRequest')
383
request_handlers.register_lazy(
384
'Branch.get_config_file', 'bzrlib.smart.branch', 'SmartServerBranchGetConfigFile')
385
request_handlers.register_lazy(
386
'Branch.get_stacked_on_url', 'bzrlib.smart.branch', 'SmartServerBranchRequestGetStackedOnURL')
387
request_handlers.register_lazy(
388
'Branch.last_revision_info', 'bzrlib.smart.branch', 'SmartServerBranchRequestLastRevisionInfo')
389
request_handlers.register_lazy(
390
'Branch.lock_write', 'bzrlib.smart.branch', 'SmartServerBranchRequestLockWrite')
391
request_handlers.register_lazy(
392
'Branch.revision_history', 'bzrlib.smart.branch', 'SmartServerRequestRevisionHistory')
393
request_handlers.register_lazy(
394
'Branch.set_last_revision', 'bzrlib.smart.branch', 'SmartServerBranchRequestSetLastRevision')
395
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
'Branch.unlock', 'bzrlib.smart.branch', 'SmartServerBranchRequestUnlock')
403
request_handlers.register_lazy(
404
'BzrDir.find_repository', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepositoryV1')
405
request_handlers.register_lazy(
406
'BzrDir.find_repositoryV2', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepositoryV2')
407
request_handlers.register_lazy(
408
'BzrDirFormat.initialize', 'bzrlib.smart.bzrdir', 'SmartServerRequestInitializeBzrDir')
409
request_handlers.register_lazy(
410
'BzrDir.open_branch', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBranch')
411
request_handlers.register_lazy(
412
'delete', 'bzrlib.smart.vfs', 'DeleteRequest')
413
request_handlers.register_lazy(
414
'get', 'bzrlib.smart.vfs', 'GetRequest')
415
request_handlers.register_lazy(
416
'get_bundle', 'bzrlib.smart.request', 'GetBundleRequest')
417
request_handlers.register_lazy(
418
'has', 'bzrlib.smart.vfs', 'HasRequest')
419
request_handlers.register_lazy(
420
'hello', 'bzrlib.smart.request', 'HelloRequest')
421
request_handlers.register_lazy(
422
'iter_files_recursive', 'bzrlib.smart.vfs', 'IterFilesRecursiveRequest')
423
request_handlers.register_lazy(
424
'list_dir', 'bzrlib.smart.vfs', 'ListDirRequest')
425
request_handlers.register_lazy(
426
'mkdir', 'bzrlib.smart.vfs', 'MkdirRequest')
427
request_handlers.register_lazy(
428
'move', 'bzrlib.smart.vfs', 'MoveRequest')
429
request_handlers.register_lazy(
430
'put', 'bzrlib.smart.vfs', 'PutRequest')
431
request_handlers.register_lazy(
432
'put_non_atomic', 'bzrlib.smart.vfs', 'PutNonAtomicRequest')
433
request_handlers.register_lazy(
434
'readv', 'bzrlib.smart.vfs', 'ReadvRequest')
435
request_handlers.register_lazy(
436
'rename', 'bzrlib.smart.vfs', 'RenameRequest')
437
request_handlers.register_lazy(
438
'PackRepository.autopack', 'bzrlib.smart.packrepository',
439
'SmartServerPackRepositoryAutopack')
440
request_handlers.register_lazy('Repository.gather_stats',
441
'bzrlib.smart.repository',
442
'SmartServerRepositoryGatherStats')
443
request_handlers.register_lazy('Repository.get_parent_map',
444
'bzrlib.smart.repository',
445
'SmartServerRepositoryGetParentMap')
446
request_handlers.register_lazy(
447
'Repository.get_revision_graph', 'bzrlib.smart.repository', 'SmartServerRepositoryGetRevisionGraph')
448
request_handlers.register_lazy(
449
'Repository.has_revision', 'bzrlib.smart.repository', 'SmartServerRequestHasRevision')
450
request_handlers.register_lazy(
451
'Repository.is_shared', 'bzrlib.smart.repository', 'SmartServerRepositoryIsShared')
452
request_handlers.register_lazy(
453
'Repository.lock_write', 'bzrlib.smart.repository', 'SmartServerRepositoryLockWrite')
454
request_handlers.register_lazy(
455
'Repository.unlock', 'bzrlib.smart.repository', 'SmartServerRepositoryUnlock')
456
request_handlers.register_lazy(
457
'Repository.tarball', 'bzrlib.smart.repository',
458
'SmartServerRepositoryTarball')
459
request_handlers.register_lazy(
460
'rmdir', 'bzrlib.smart.vfs', 'RmdirRequest')
461
request_handlers.register_lazy(
462
'stat', 'bzrlib.smart.vfs', 'StatRequest')
463
request_handlers.register_lazy(
464
'Transport.is_readonly', 'bzrlib.smart.request', 'SmartServerIsReadonly')
465
request_handlers.register_lazy(
466
'BzrDir.open', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBzrDir')