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."""
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
35
class SmartServerRequest(object):
36
"""Base class for request handlers.
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.
44
def __init__(self, backing_transport, root_client_path='/'):
47
:param backing_transport: the base transport to be used when performing
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
54
self._backing_transport = backing_transport
55
if root_client_path is not None:
56
if not root_client_path.startswith('/'):
57
root_client_path = '/' + root_client_path
58
if not root_client_path.endswith('/'):
59
root_client_path += '/'
60
self._root_client_path = root_client_path
62
def _check_enabled(self):
63
"""Raises DisabledMethod if this method is disabled."""
67
"""Mandatory extension point for SmartServerRequest subclasses.
69
Subclasses must implement this.
71
This should return a SmartServerResponse if this command expects to
74
raise NotImplementedError(self.do)
76
def execute(self, *args):
77
"""Public entry point to execute this request.
79
It will return a SmartServerResponse if the command does not expect a
82
:param *args: the arguments of the request.
87
def do_body(self, body_bytes):
88
"""Called if the client sends a body with the request.
90
Must return a SmartServerResponse.
92
# TODO: if a client erroneously sends a request that shouldn't have a
93
# body, what to do? Probably SmartServerRequestHandler should catch
94
# this NotImplementedError and translate it into a 'bad request' error
95
# to send to the client.
96
raise NotImplementedError(self.do_body)
98
def translate_client_path(self, client_path):
99
"""Translate a path received from a network client into a local
102
All paths received from the client *must* be translated.
104
:param client_path: the path from the client.
105
:returns: a relpath that may be used with self._backing_transport
106
(unlike the untranslated client_path, which must not be used with
107
the backing transport).
109
if self._root_client_path is None:
110
# no translation necessary!
112
if not client_path.startswith('/'):
113
client_path = '/' + client_path
114
if client_path.startswith(self._root_client_path):
115
path = client_path[len(self._root_client_path):]
116
relpath = urlutils.joinpath('/', path)
117
assert relpath.startswith('/')
118
mutter('translate_client_path(%r) [rcp=%r, backing=%r] -> %r',
119
client_path, self._root_client_path, self._backing_transport,
123
raise errors.PathNotChild(client_path, self._root_client_path)
125
def transport_from_client_path(self, client_path):
126
"""Get a backing transport corresponding to the location referred to by
129
:seealso: translate_client_path
130
:returns: a transport cloned from self._backing_transport
132
relpath = self.translate_client_path(client_path)
133
result = self._backing_transport.clone(relpath)
134
mutter('transport_from_client_path -> %r', result)
138
class SmartServerResponse(object):
139
"""A response to a client request.
141
This base class should not be used. Instead use
142
SuccessfulSmartServerResponse and FailedSmartServerResponse as appropriate.
145
def __init__(self, args, body=None, body_stream=None):
148
:param args: tuple of response arguments.
149
:param body: string of a response body.
150
:param body_stream: iterable of bytestrings to be streamed to the
154
if body is not None and body_stream is not None:
155
raise errors.BzrError(
156
"'body' and 'body_stream' are mutually exclusive.")
158
self.body_stream = body_stream
160
def __eq__(self, other):
163
return (other.args == self.args and
164
other.body == self.body and
165
other.body_stream is self.body_stream)
168
status = {True: 'OK', False: 'ERR'}[self.is_successful()]
169
return "<SmartServerResponse status=%s args=%r body=%r>" % (status,
170
self.args, self.body)
173
class FailedSmartServerResponse(SmartServerResponse):
174
"""A SmartServerResponse for a request which failed."""
176
def is_successful(self):
177
"""FailedSmartServerResponse are not successful."""
181
class SuccessfulSmartServerResponse(SmartServerResponse):
182
"""A SmartServerResponse for a successfully completed request."""
184
def is_successful(self):
185
"""SuccessfulSmartServerResponse are successful."""
189
class SmartServerRequestHandler(object):
190
"""Protocol logic for smart server.
192
This doesn't handle serialization at all, it just processes requests and
196
# IMPORTANT FOR IMPLEMENTORS: It is important that SmartServerRequestHandler
197
# not contain encoding or decoding logic to allow the wire protocol to vary
198
# from the object protocol: we will want to tweak the wire protocol separate
199
# from the object model, and ideally we will be able to do that without
200
# having a SmartServerRequestHandler subclass for each wire protocol, rather
201
# just a Protocol subclass.
203
# TODO: Better way of representing the body for commands that take it,
204
# and allow it to be streamed into the server.
206
def __init__(self, backing_transport, commands, root_client_path):
209
:param backing_transport: a Transport to handle requests for.
210
:param commands: a registry mapping command names to SmartServerRequest
211
subclasses. e.g. bzrlib.transport.smart.vfs.vfs_commands.
213
self._backing_transport = backing_transport
214
self._root_client_path = root_client_path
215
self._commands = commands
216
self._body_bytes = ''
218
self.finished_reading = False
221
def accept_body(self, bytes):
222
"""Accept body data."""
224
# TODO: This should be overriden for each command that desired body data
225
# to handle the right format of that data, i.e. plain bytes, a bundle,
226
# etc. The deserialisation into that format should be done in the
229
# default fallback is to accumulate bytes.
230
self._body_bytes += bytes
232
def end_of_body(self):
233
"""No more body data will be received."""
234
self._run_handler_code(self._command.do_body, (self._body_bytes,), {})
235
# cannot read after this.
236
self.finished_reading = True
238
def dispatch_command(self, cmd, args):
239
"""Deprecated compatibility method.""" # XXX XXX
241
command = self._commands.get(cmd)
243
raise errors.SmartProtocolError("bad request %r" % (cmd,))
244
self._command = command(self._backing_transport, self._root_client_path)
245
self._run_handler_code(self._command.execute, args, {})
247
def _run_handler_code(self, callable, args, kwargs):
248
"""Run some handler specific code 'callable'.
250
If a result is returned, it is considered to be the commands response,
251
and finished_reading is set true, and its assigned to self.response.
253
Any exceptions caught are translated and a response object created
256
result = self._call_converting_errors(callable, args, kwargs)
258
if result is not None:
259
self.response = result
260
self.finished_reading = True
262
def _call_converting_errors(self, callable, args, kwargs):
263
"""Call callable converting errors to Response objects."""
264
# XXX: most of this error conversion is VFS-related, and thus ought to
265
# be in SmartServerVFSRequestHandler somewhere.
267
return callable(*args, **kwargs)
268
except errors.NoSuchFile, e:
269
return FailedSmartServerResponse(('NoSuchFile', e.path))
270
except errors.FileExists, e:
271
return FailedSmartServerResponse(('FileExists', e.path))
272
except errors.DirectoryNotEmpty, e:
273
return FailedSmartServerResponse(('DirectoryNotEmpty', e.path))
274
except errors.ShortReadvError, e:
275
return FailedSmartServerResponse(('ShortReadvError',
276
e.path, str(e.offset), str(e.length), str(e.actual)))
277
except UnicodeError, e:
278
# If it is a DecodeError, than most likely we are starting
279
# with a plain string
280
str_or_unicode = e.object
281
if isinstance(str_or_unicode, unicode):
282
# XXX: UTF-8 might have \x01 (our seperator byte) in it. We
283
# should escape it somehow.
284
val = 'u:' + str_or_unicode.encode('utf-8')
286
val = 's:' + str_or_unicode.encode('base64')
287
# This handles UnicodeEncodeError or UnicodeDecodeError
288
return FailedSmartServerResponse((e.__class__.__name__,
289
e.encoding, val, str(e.start), str(e.end), e.reason))
290
except errors.TransportNotPossible, e:
291
if e.msg == "readonly transport":
292
return FailedSmartServerResponse(('ReadOnlyError', ))
297
class HelloRequest(SmartServerRequest):
298
"""Answer a version request with the highest protocol version this server
303
return SuccessfulSmartServerResponse(('ok', '2'))
306
class GetBundleRequest(SmartServerRequest):
307
"""Get a bundle of from the null revision to the specified revision."""
309
def do(self, path, revision_id):
310
# open transport relative to our base
311
t = self.transport_from_client_path(path)
312
control, extra_path = bzrdir.BzrDir.open_containing_from_transport(t)
313
repo = control.open_repository()
314
tmpf = tempfile.TemporaryFile()
315
base_revision = revision.NULL_REVISION
316
write_bundle(repo, revision_id, base_revision, tmpf)
318
return SuccessfulSmartServerResponse((), tmpf.read())
321
class SmartServerIsReadonly(SmartServerRequest):
322
# XXX: this request method belongs somewhere else.
325
if self._backing_transport.is_readonly():
329
return SuccessfulSmartServerResponse((answer,))
332
request_handlers = registry.Registry()
333
request_handlers.register_lazy(
334
'append', 'bzrlib.smart.vfs', 'AppendRequest')
335
request_handlers.register_lazy(
336
'Branch.get_config_file', 'bzrlib.smart.branch', 'SmartServerBranchGetConfigFile')
337
request_handlers.register_lazy(
338
'Branch.last_revision_info', 'bzrlib.smart.branch', 'SmartServerBranchRequestLastRevisionInfo')
339
request_handlers.register_lazy(
340
'Branch.lock_write', 'bzrlib.smart.branch', 'SmartServerBranchRequestLockWrite')
341
request_handlers.register_lazy(
342
'Branch.revision_history', 'bzrlib.smart.branch', 'SmartServerRequestRevisionHistory')
343
request_handlers.register_lazy(
344
'Branch.set_last_revision', 'bzrlib.smart.branch', 'SmartServerBranchRequestSetLastRevision')
345
request_handlers.register_lazy(
346
'Branch.unlock', 'bzrlib.smart.branch', 'SmartServerBranchRequestUnlock')
347
request_handlers.register_lazy(
348
'BzrDir.find_repository', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepository')
349
request_handlers.register_lazy(
350
'BzrDirFormat.initialize', 'bzrlib.smart.bzrdir', 'SmartServerRequestInitializeBzrDir')
351
request_handlers.register_lazy(
352
'BzrDir.open_branch', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBranch')
353
request_handlers.register_lazy(
354
'delete', 'bzrlib.smart.vfs', 'DeleteRequest')
355
request_handlers.register_lazy(
356
'get', 'bzrlib.smart.vfs', 'GetRequest')
357
request_handlers.register_lazy(
358
'get_bundle', 'bzrlib.smart.request', 'GetBundleRequest')
359
request_handlers.register_lazy(
360
'has', 'bzrlib.smart.vfs', 'HasRequest')
361
request_handlers.register_lazy(
362
'hello', 'bzrlib.smart.request', 'HelloRequest')
363
request_handlers.register_lazy(
364
'iter_files_recursive', 'bzrlib.smart.vfs', 'IterFilesRecursiveRequest')
365
request_handlers.register_lazy(
366
'list_dir', 'bzrlib.smart.vfs', 'ListDirRequest')
367
request_handlers.register_lazy(
368
'mkdir', 'bzrlib.smart.vfs', 'MkdirRequest')
369
request_handlers.register_lazy(
370
'move', 'bzrlib.smart.vfs', 'MoveRequest')
371
request_handlers.register_lazy(
372
'put', 'bzrlib.smart.vfs', 'PutRequest')
373
request_handlers.register_lazy(
374
'put_non_atomic', 'bzrlib.smart.vfs', 'PutNonAtomicRequest')
375
request_handlers.register_lazy(
376
'readv', 'bzrlib.smart.vfs', 'ReadvRequest')
377
request_handlers.register_lazy(
378
'rename', 'bzrlib.smart.vfs', 'RenameRequest')
379
request_handlers.register_lazy('Repository.gather_stats',
380
'bzrlib.smart.repository',
381
'SmartServerRepositoryGatherStats')
382
request_handlers.register_lazy(
383
'Repository.stream_knit_data_for_revisions', 'bzrlib.smart.repository',
384
'SmartServerRepositoryStreamKnitDataForRevisions')
385
request_handlers.register_lazy(
386
'Repository.get_revision_graph', 'bzrlib.smart.repository', 'SmartServerRepositoryGetRevisionGraph')
387
request_handlers.register_lazy(
388
'Repository.has_revision', 'bzrlib.smart.repository', 'SmartServerRequestHasRevision')
389
request_handlers.register_lazy(
390
'Repository.is_shared', 'bzrlib.smart.repository', 'SmartServerRepositoryIsShared')
391
request_handlers.register_lazy(
392
'Repository.lock_write', 'bzrlib.smart.repository', 'SmartServerRepositoryLockWrite')
393
request_handlers.register_lazy(
394
'Repository.unlock', 'bzrlib.smart.repository', 'SmartServerRepositoryUnlock')
395
request_handlers.register_lazy(
396
'Repository.tarball', 'bzrlib.smart.repository',
397
'SmartServerRepositoryTarball')
398
request_handlers.register_lazy(
399
'rmdir', 'bzrlib.smart.vfs', 'RmdirRequest')
400
request_handlers.register_lazy(
401
'stat', 'bzrlib.smart.vfs', 'StatRequest')
402
request_handlers.register_lazy(
403
'Transport.is_readonly', 'bzrlib.smart.request', 'SmartServerIsReadonly')
404
request_handlers.register_lazy(
405
'BzrDir.open', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBzrDir')