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.transport import get_transport
31
from bzrlib.transport.chroot import ChrootServer
34
class SmartServerRequest(object):
35
"""Base class for request handlers.
37
To define a new request, subclass this class and override the `do` method
38
(and if appropriate, `do_body` as well). Request implementors should take
39
care to call `translate_client_path` and `transport_from_client_path` as
40
appropriate when dealing with paths received from the client.
43
def __init__(self, backing_transport, root_client_path='/'):
46
:param backing_transport: the base transport to be used when performing
48
:param root_client_path: the client path that maps to the root of
49
backing_transport. This is used to interpret relpaths received
50
from the client. Clients will not be able to refer to paths above
51
this root. If root_client_path is None, then no translation will
52
be performed on client paths. Default is '/'.
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('/')
120
raise errors.PathNotChild(client_path, self._root_client_path)
122
def transport_from_client_path(self, client_path):
123
"""Get a backing transport corresponding to the location referred to by
126
:seealso: translate_client_path
127
:returns: a transport cloned from self._backing_transport
129
relpath = self.translate_client_path(client_path)
130
return self._backing_transport.clone(relpath)
133
class SmartServerResponse(object):
134
"""A response to a client request.
136
This base class should not be used. Instead use
137
SuccessfulSmartServerResponse and FailedSmartServerResponse as appropriate.
140
def __init__(self, args, body=None, body_stream=None):
143
:param args: tuple of response arguments.
144
:param body: string of a response body.
145
:param body_stream: iterable of bytestrings to be streamed to the
149
if body is not None and body_stream is not None:
150
raise errors.BzrError(
151
"'body' and 'body_stream' are mutually exclusive.")
153
self.body_stream = body_stream
155
def __eq__(self, other):
158
return (other.args == self.args and
159
other.body == self.body and
160
other.body_stream is self.body_stream)
163
status = {True: 'OK', False: 'ERR'}[self.is_successful()]
164
return "<SmartServerResponse status=%s args=%r body=%r>" % (status,
165
self.args, self.body)
168
class FailedSmartServerResponse(SmartServerResponse):
169
"""A SmartServerResponse for a request which failed."""
171
def is_successful(self):
172
"""FailedSmartServerResponse are not successful."""
176
class SuccessfulSmartServerResponse(SmartServerResponse):
177
"""A SmartServerResponse for a successfully completed request."""
179
def is_successful(self):
180
"""SuccessfulSmartServerResponse are successful."""
184
class SmartServerRequestHandler(object):
185
"""Protocol logic for smart server.
187
This doesn't handle serialization at all, it just processes requests and
191
# IMPORTANT FOR IMPLEMENTORS: It is important that SmartServerRequestHandler
192
# not contain encoding or decoding logic to allow the wire protocol to vary
193
# from the object protocol: we will want to tweak the wire protocol separate
194
# from the object model, and ideally we will be able to do that without
195
# having a SmartServerRequestHandler subclass for each wire protocol, rather
196
# just a Protocol subclass.
198
# TODO: Better way of representing the body for commands that take it,
199
# and allow it to be streamed into the server.
201
def __init__(self, backing_transport, commands, root_client_path):
204
:param backing_transport: a Transport to handle requests for.
205
:param commands: a registry mapping command names to SmartServerRequest
206
subclasses. e.g. bzrlib.transport.smart.vfs.vfs_commands.
208
self._backing_transport = backing_transport
209
self._root_client_path = root_client_path
210
self._commands = commands
211
self._body_bytes = ''
213
self.finished_reading = False
216
def accept_body(self, bytes):
217
"""Accept body data."""
219
# TODO: This should be overriden for each command that desired body data
220
# to handle the right format of that data, i.e. plain bytes, a bundle,
221
# etc. The deserialisation into that format should be done in the
224
# default fallback is to accumulate bytes.
225
self._body_bytes += bytes
227
def end_of_body(self):
228
"""No more body data will be received."""
229
self._run_handler_code(self._command.do_body, (self._body_bytes,), {})
230
# cannot read after this.
231
self.finished_reading = True
233
def dispatch_command(self, cmd, args):
234
"""Deprecated compatibility method.""" # XXX XXX
236
command = self._commands.get(cmd)
238
raise errors.SmartProtocolError("bad request %r" % (cmd,))
239
self._command = command(self._backing_transport, self._root_client_path)
240
self._run_handler_code(self._command.execute, args, {})
242
def _run_handler_code(self, callable, args, kwargs):
243
"""Run some handler specific code 'callable'.
245
If a result is returned, it is considered to be the commands response,
246
and finished_reading is set true, and its assigned to self.response.
248
Any exceptions caught are translated and a response object created
251
result = self._call_converting_errors(callable, args, kwargs)
253
if result is not None:
254
self.response = result
255
self.finished_reading = True
257
def _call_converting_errors(self, callable, args, kwargs):
258
"""Call callable converting errors to Response objects."""
259
# XXX: most of this error conversion is VFS-related, and thus ought to
260
# be in SmartServerVFSRequestHandler somewhere.
262
return callable(*args, **kwargs)
263
except errors.NoSuchFile, e:
264
return FailedSmartServerResponse(('NoSuchFile', e.path))
265
except errors.FileExists, e:
266
return FailedSmartServerResponse(('FileExists', e.path))
267
except errors.DirectoryNotEmpty, e:
268
return FailedSmartServerResponse(('DirectoryNotEmpty', e.path))
269
except errors.ShortReadvError, e:
270
return FailedSmartServerResponse(('ShortReadvError',
271
e.path, str(e.offset), str(e.length), str(e.actual)))
272
except UnicodeError, e:
273
# If it is a DecodeError, than most likely we are starting
274
# with a plain string
275
str_or_unicode = e.object
276
if isinstance(str_or_unicode, unicode):
277
# XXX: UTF-8 might have \x01 (our seperator byte) in it. We
278
# should escape it somehow.
279
val = 'u:' + str_or_unicode.encode('utf-8')
281
val = 's:' + str_or_unicode.encode('base64')
282
# This handles UnicodeEncodeError or UnicodeDecodeError
283
return FailedSmartServerResponse((e.__class__.__name__,
284
e.encoding, val, str(e.start), str(e.end), e.reason))
285
except errors.TransportNotPossible, e:
286
if e.msg == "readonly transport":
287
return FailedSmartServerResponse(('ReadOnlyError', ))
292
class HelloRequest(SmartServerRequest):
293
"""Answer a version request with the highest protocol version this server
298
return SuccessfulSmartServerResponse(('ok', '2'))
301
class GetBundleRequest(SmartServerRequest):
302
"""Get a bundle of from the null revision to the specified revision."""
304
def do(self, path, revision_id):
305
# open transport relative to our base
306
t = self.transport_from_client_path(path)
307
control, extra_path = bzrdir.BzrDir.open_containing_from_transport(t)
308
repo = control.open_repository()
309
tmpf = tempfile.TemporaryFile()
310
base_revision = revision.NULL_REVISION
311
write_bundle(repo, revision_id, base_revision, tmpf)
313
return SuccessfulSmartServerResponse((), tmpf.read())
316
class SmartServerIsReadonly(SmartServerRequest):
317
# XXX: this request method belongs somewhere else.
320
if self._backing_transport.is_readonly():
324
return SuccessfulSmartServerResponse((answer,))
327
request_handlers = registry.Registry()
328
request_handlers.register_lazy(
329
'append', 'bzrlib.smart.vfs', 'AppendRequest')
330
request_handlers.register_lazy(
331
'Branch.get_config_file', 'bzrlib.smart.branch', 'SmartServerBranchGetConfigFile')
332
request_handlers.register_lazy(
333
'Branch.last_revision_info', 'bzrlib.smart.branch', 'SmartServerBranchRequestLastRevisionInfo')
334
request_handlers.register_lazy(
335
'Branch.lock_write', 'bzrlib.smart.branch', 'SmartServerBranchRequestLockWrite')
336
request_handlers.register_lazy(
337
'Branch.revision_history', 'bzrlib.smart.branch', 'SmartServerRequestRevisionHistory')
338
request_handlers.register_lazy(
339
'Branch.set_last_revision', 'bzrlib.smart.branch', 'SmartServerBranchRequestSetLastRevision')
340
request_handlers.register_lazy(
341
'Branch.unlock', 'bzrlib.smart.branch', 'SmartServerBranchRequestUnlock')
342
request_handlers.register_lazy(
343
'BzrDir.find_repository', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepository')
344
request_handlers.register_lazy(
345
'BzrDirFormat.initialize', 'bzrlib.smart.bzrdir', 'SmartServerRequestInitializeBzrDir')
346
request_handlers.register_lazy(
347
'BzrDir.open_branch', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBranch')
348
request_handlers.register_lazy(
349
'delete', 'bzrlib.smart.vfs', 'DeleteRequest')
350
request_handlers.register_lazy(
351
'get', 'bzrlib.smart.vfs', 'GetRequest')
352
request_handlers.register_lazy(
353
'get_bundle', 'bzrlib.smart.request', 'GetBundleRequest')
354
request_handlers.register_lazy(
355
'has', 'bzrlib.smart.vfs', 'HasRequest')
356
request_handlers.register_lazy(
357
'hello', 'bzrlib.smart.request', 'HelloRequest')
358
request_handlers.register_lazy(
359
'iter_files_recursive', 'bzrlib.smart.vfs', 'IterFilesRecursiveRequest')
360
request_handlers.register_lazy(
361
'list_dir', 'bzrlib.smart.vfs', 'ListDirRequest')
362
request_handlers.register_lazy(
363
'mkdir', 'bzrlib.smart.vfs', 'MkdirRequest')
364
request_handlers.register_lazy(
365
'move', 'bzrlib.smart.vfs', 'MoveRequest')
366
request_handlers.register_lazy(
367
'put', 'bzrlib.smart.vfs', 'PutRequest')
368
request_handlers.register_lazy(
369
'put_non_atomic', 'bzrlib.smart.vfs', 'PutNonAtomicRequest')
370
request_handlers.register_lazy(
371
'readv', 'bzrlib.smart.vfs', 'ReadvRequest')
372
request_handlers.register_lazy(
373
'rename', 'bzrlib.smart.vfs', 'RenameRequest')
374
request_handlers.register_lazy('Repository.gather_stats',
375
'bzrlib.smart.repository',
376
'SmartServerRepositoryGatherStats')
377
request_handlers.register_lazy(
378
'Repository.stream_knit_data_for_revisions', 'bzrlib.smart.repository',
379
'SmartServerRepositoryStreamKnitDataForRevisions')
380
request_handlers.register_lazy(
381
'Repository.get_revision_graph', 'bzrlib.smart.repository', 'SmartServerRepositoryGetRevisionGraph')
382
request_handlers.register_lazy(
383
'Repository.has_revision', 'bzrlib.smart.repository', 'SmartServerRequestHasRevision')
384
request_handlers.register_lazy(
385
'Repository.is_shared', 'bzrlib.smart.repository', 'SmartServerRepositoryIsShared')
386
request_handlers.register_lazy(
387
'Repository.lock_write', 'bzrlib.smart.repository', 'SmartServerRepositoryLockWrite')
388
request_handlers.register_lazy(
389
'Repository.unlock', 'bzrlib.smart.repository', 'SmartServerRepositoryUnlock')
390
request_handlers.register_lazy(
391
'Repository.tarball', 'bzrlib.smart.repository',
392
'SmartServerRepositoryTarball')
393
request_handlers.register_lazy(
394
'rmdir', 'bzrlib.smart.vfs', 'RmdirRequest')
395
request_handlers.register_lazy(
396
'stat', 'bzrlib.smart.vfs', 'StatRequest')
397
request_handlers.register_lazy(
398
'Transport.is_readonly', 'bzrlib.smart.request', 'SmartServerIsReadonly')
399
request_handlers.register_lazy(
400
'BzrDir.open', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBzrDir')