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
def __init__(self, backing_transport, root_client_path='/'):
41
:param backing_transport: the base transport to be used when performing
43
:param root_client_path: the client path that maps to the root of
44
backing_transport. This is used to interpret relpaths received from
47
self._backing_transport = backing_transport
48
if not root_client_path.startswith('/'):
49
root_client_path = '/' + root_client_path
50
if not root_client_path.endswith('/'):
51
root_client_path += '/'
52
self._root_client_path = root_client_path
54
def _check_enabled(self):
55
"""Raises DisabledMethod if this method is disabled."""
59
"""Mandatory extension point for SmartServerRequest subclasses.
61
Subclasses must implement this.
63
This should return a SmartServerResponse if this command expects to
66
raise NotImplementedError(self.do)
68
def execute(self, *args):
69
"""Public entry point to execute this request.
71
It will return a SmartServerResponse if the command does not expect a
74
:param *args: the arguments of the request.
79
def do_body(self, body_bytes):
80
"""Called if the client sends a body with the request.
82
Must return a SmartServerResponse.
84
# TODO: if a client erroneously sends a request that shouldn't have a
85
# body, what to do? Probably SmartServerRequestHandler should catch
86
# this NotImplementedError and translate it into a 'bad request' error
87
# to send to the client.
88
raise NotImplementedError(self.do_body)
90
def translate_client_path(self, client_path):
91
if not client_path.startswith('/'):
92
client_path = '/' + client_path
93
if client_path.startswith(self._root_client_path):
94
path = client_path[len(self._root_client_path):]
95
relpath = urlutils.joinpath('/', path)
96
assert relpath.startswith('/')
99
raise errors.PathNotChild(client_path, self._root_client_path)
101
def transport_from_client_path(self, client_path):
103
# * 'path': path the client sent
104
# * 'self._backing_transport': transport rooted at what we're serving
105
# * xxx: path to _backing_transport root as a client path
106
relpath = self.translate_client_path(client_path)
107
return self._backing_transport.clone(relpath)
110
class SmartServerResponse(object):
111
"""A response to a client request.
113
This base class should not be used. Instead use
114
SuccessfulSmartServerResponse and FailedSmartServerResponse as appropriate.
117
def __init__(self, args, body=None, body_stream=None):
120
:param args: tuple of response arguments.
121
:param body: string of a response body.
122
:param body_stream: iterable of bytestrings to be streamed to the
126
if body is not None and body_stream is not None:
127
raise errors.BzrError(
128
"'body' and 'body_stream' are mutually exclusive.")
130
self.body_stream = body_stream
132
def __eq__(self, other):
135
return (other.args == self.args and
136
other.body == self.body and
137
other.body_stream is self.body_stream)
140
status = {True: 'OK', False: 'ERR'}[self.is_successful()]
141
return "<SmartServerResponse status=%s args=%r body=%r>" % (status,
142
self.args, self.body)
145
class FailedSmartServerResponse(SmartServerResponse):
146
"""A SmartServerResponse for a request which failed."""
148
def is_successful(self):
149
"""FailedSmartServerResponse are not successful."""
153
class SuccessfulSmartServerResponse(SmartServerResponse):
154
"""A SmartServerResponse for a successfully completed request."""
156
def is_successful(self):
157
"""SuccessfulSmartServerResponse are successful."""
161
class SmartServerRequestHandler(object):
162
"""Protocol logic for smart server.
164
This doesn't handle serialization at all, it just processes requests and
168
# IMPORTANT FOR IMPLEMENTORS: It is important that SmartServerRequestHandler
169
# not contain encoding or decoding logic to allow the wire protocol to vary
170
# from the object protocol: we will want to tweak the wire protocol separate
171
# from the object model, and ideally we will be able to do that without
172
# having a SmartServerRequestHandler subclass for each wire protocol, rather
173
# just a Protocol subclass.
175
# TODO: Better way of representing the body for commands that take it,
176
# and allow it to be streamed into the server.
178
def __init__(self, backing_transport, commands, root_client_path):
181
:param backing_transport: a Transport to handle requests for.
182
:param commands: a registry mapping command names to SmartServerRequest
183
subclasses. e.g. bzrlib.transport.smart.vfs.vfs_commands.
185
self._backing_transport = backing_transport
186
self._root_client_path = root_client_path
187
self._commands = commands
188
self._body_bytes = ''
190
self.finished_reading = False
193
def accept_body(self, bytes):
194
"""Accept body data."""
196
# TODO: This should be overriden for each command that desired body data
197
# to handle the right format of that data, i.e. plain bytes, a bundle,
198
# etc. The deserialisation into that format should be done in the
201
# default fallback is to accumulate bytes.
202
self._body_bytes += bytes
204
def end_of_body(self):
205
"""No more body data will be received."""
206
self._run_handler_code(self._command.do_body, (self._body_bytes,), {})
207
# cannot read after this.
208
self.finished_reading = True
210
def dispatch_command(self, cmd, args):
211
"""Deprecated compatibility method.""" # XXX XXX
213
command = self._commands.get(cmd)
215
raise errors.SmartProtocolError("bad request %r" % (cmd,))
216
self._command = command(self._backing_transport, self._root_client_path)
217
self._run_handler_code(self._command.execute, args, {})
219
def _run_handler_code(self, callable, args, kwargs):
220
"""Run some handler specific code 'callable'.
222
If a result is returned, it is considered to be the commands response,
223
and finished_reading is set true, and its assigned to self.response.
225
Any exceptions caught are translated and a response object created
228
result = self._call_converting_errors(callable, args, kwargs)
230
if result is not None:
231
self.response = result
232
self.finished_reading = True
234
def _call_converting_errors(self, callable, args, kwargs):
235
"""Call callable converting errors to Response objects."""
236
# XXX: most of this error conversion is VFS-related, and thus ought to
237
# be in SmartServerVFSRequestHandler somewhere.
239
return callable(*args, **kwargs)
240
except errors.NoSuchFile, e:
241
return FailedSmartServerResponse(('NoSuchFile', e.path))
242
except errors.FileExists, e:
243
return FailedSmartServerResponse(('FileExists', e.path))
244
except errors.DirectoryNotEmpty, e:
245
return FailedSmartServerResponse(('DirectoryNotEmpty', e.path))
246
except errors.ShortReadvError, e:
247
return FailedSmartServerResponse(('ShortReadvError',
248
e.path, str(e.offset), str(e.length), str(e.actual)))
249
except UnicodeError, e:
250
# If it is a DecodeError, than most likely we are starting
251
# with a plain string
252
str_or_unicode = e.object
253
if isinstance(str_or_unicode, unicode):
254
# XXX: UTF-8 might have \x01 (our seperator byte) in it. We
255
# should escape it somehow.
256
val = 'u:' + str_or_unicode.encode('utf-8')
258
val = 's:' + str_or_unicode.encode('base64')
259
# This handles UnicodeEncodeError or UnicodeDecodeError
260
return FailedSmartServerResponse((e.__class__.__name__,
261
e.encoding, val, str(e.start), str(e.end), e.reason))
262
except errors.TransportNotPossible, e:
263
if e.msg == "readonly transport":
264
return FailedSmartServerResponse(('ReadOnlyError', ))
269
class HelloRequest(SmartServerRequest):
270
"""Answer a version request with the highest protocol version this server
275
return SuccessfulSmartServerResponse(('ok', '2'))
278
class GetBundleRequest(SmartServerRequest):
279
"""Get a bundle of from the null revision to the specified revision."""
281
def do(self, path, revision_id):
282
# open transport relative to our base
283
t = self.transport_from_client_path(path)
284
control, extra_path = bzrdir.BzrDir.open_containing_from_transport(t)
285
repo = control.open_repository()
286
tmpf = tempfile.TemporaryFile()
287
base_revision = revision.NULL_REVISION
288
write_bundle(repo, revision_id, base_revision, tmpf)
290
return SuccessfulSmartServerResponse((), tmpf.read())
293
class SmartServerIsReadonly(SmartServerRequest):
294
# XXX: this request method belongs somewhere else.
297
if self._backing_transport.is_readonly():
301
return SuccessfulSmartServerResponse((answer,))
304
request_handlers = registry.Registry()
305
request_handlers.register_lazy(
306
'append', 'bzrlib.smart.vfs', 'AppendRequest')
307
request_handlers.register_lazy(
308
'Branch.get_config_file', 'bzrlib.smart.branch', 'SmartServerBranchGetConfigFile')
309
request_handlers.register_lazy(
310
'Branch.last_revision_info', 'bzrlib.smart.branch', 'SmartServerBranchRequestLastRevisionInfo')
311
request_handlers.register_lazy(
312
'Branch.lock_write', 'bzrlib.smart.branch', 'SmartServerBranchRequestLockWrite')
313
request_handlers.register_lazy(
314
'Branch.revision_history', 'bzrlib.smart.branch', 'SmartServerRequestRevisionHistory')
315
request_handlers.register_lazy(
316
'Branch.set_last_revision', 'bzrlib.smart.branch', 'SmartServerBranchRequestSetLastRevision')
317
request_handlers.register_lazy(
318
'Branch.unlock', 'bzrlib.smart.branch', 'SmartServerBranchRequestUnlock')
319
request_handlers.register_lazy(
320
'BzrDir.find_repository', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepository')
321
request_handlers.register_lazy(
322
'BzrDirFormat.initialize', 'bzrlib.smart.bzrdir', 'SmartServerRequestInitializeBzrDir')
323
request_handlers.register_lazy(
324
'BzrDir.open_branch', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBranch')
325
request_handlers.register_lazy(
326
'delete', 'bzrlib.smart.vfs', 'DeleteRequest')
327
request_handlers.register_lazy(
328
'get', 'bzrlib.smart.vfs', 'GetRequest')
329
request_handlers.register_lazy(
330
'get_bundle', 'bzrlib.smart.request', 'GetBundleRequest')
331
request_handlers.register_lazy(
332
'has', 'bzrlib.smart.vfs', 'HasRequest')
333
request_handlers.register_lazy(
334
'hello', 'bzrlib.smart.request', 'HelloRequest')
335
request_handlers.register_lazy(
336
'iter_files_recursive', 'bzrlib.smart.vfs', 'IterFilesRecursiveRequest')
337
request_handlers.register_lazy(
338
'list_dir', 'bzrlib.smart.vfs', 'ListDirRequest')
339
request_handlers.register_lazy(
340
'mkdir', 'bzrlib.smart.vfs', 'MkdirRequest')
341
request_handlers.register_lazy(
342
'move', 'bzrlib.smart.vfs', 'MoveRequest')
343
request_handlers.register_lazy(
344
'put', 'bzrlib.smart.vfs', 'PutRequest')
345
request_handlers.register_lazy(
346
'put_non_atomic', 'bzrlib.smart.vfs', 'PutNonAtomicRequest')
347
request_handlers.register_lazy(
348
'readv', 'bzrlib.smart.vfs', 'ReadvRequest')
349
request_handlers.register_lazy(
350
'rename', 'bzrlib.smart.vfs', 'RenameRequest')
351
request_handlers.register_lazy('Repository.gather_stats',
352
'bzrlib.smart.repository',
353
'SmartServerRepositoryGatherStats')
354
request_handlers.register_lazy(
355
'Repository.stream_knit_data_for_revisions', 'bzrlib.smart.repository',
356
'SmartServerRepositoryStreamKnitDataForRevisions')
357
request_handlers.register_lazy(
358
'Repository.get_revision_graph', 'bzrlib.smart.repository', 'SmartServerRepositoryGetRevisionGraph')
359
request_handlers.register_lazy(
360
'Repository.has_revision', 'bzrlib.smart.repository', 'SmartServerRequestHasRevision')
361
request_handlers.register_lazy(
362
'Repository.is_shared', 'bzrlib.smart.repository', 'SmartServerRepositoryIsShared')
363
request_handlers.register_lazy(
364
'Repository.lock_write', 'bzrlib.smart.repository', 'SmartServerRepositoryLockWrite')
365
request_handlers.register_lazy(
366
'Repository.unlock', 'bzrlib.smart.repository', 'SmartServerRepositoryUnlock')
367
request_handlers.register_lazy(
368
'Repository.tarball', 'bzrlib.smart.repository',
369
'SmartServerRepositoryTarball')
370
request_handlers.register_lazy(
371
'rmdir', 'bzrlib.smart.vfs', 'RmdirRequest')
372
request_handlers.register_lazy(
373
'stat', 'bzrlib.smart.vfs', 'StatRequest')
374
request_handlers.register_lazy(
375
'Transport.is_readonly', 'bzrlib.smart.request', 'SmartServerIsReadonly')
376
request_handlers.register_lazy(
377
'BzrDir.open', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBzrDir')