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
rcp = root_client_path
55
self._backing_transport = backing_transport
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
:returns: a relpath that may be used with self._backing_transport
106
if not client_path.startswith('/'):
107
client_path = '/' + client_path
108
if client_path.startswith(self._root_client_path):
109
path = client_path[len(self._root_client_path):]
110
relpath = urlutils.joinpath('/', path)
111
assert relpath.startswith('/')
114
raise errors.PathNotChild(client_path, self._root_client_path)
116
def transport_from_client_path(self, client_path):
117
"""Get a backing transport corresponding to the location referred to by
120
:seealso: translate_client_path
121
:returns: a transport cloned from self._backing_transport
123
relpath = self.translate_client_path(client_path)
124
return self._backing_transport.clone(relpath)
127
class SmartServerResponse(object):
128
"""A response to a client request.
130
This base class should not be used. Instead use
131
SuccessfulSmartServerResponse and FailedSmartServerResponse as appropriate.
134
def __init__(self, args, body=None, body_stream=None):
137
:param args: tuple of response arguments.
138
:param body: string of a response body.
139
:param body_stream: iterable of bytestrings to be streamed to the
143
if body is not None and body_stream is not None:
144
raise errors.BzrError(
145
"'body' and 'body_stream' are mutually exclusive.")
147
self.body_stream = body_stream
149
def __eq__(self, other):
152
return (other.args == self.args and
153
other.body == self.body and
154
other.body_stream is self.body_stream)
157
status = {True: 'OK', False: 'ERR'}[self.is_successful()]
158
return "<SmartServerResponse status=%s args=%r body=%r>" % (status,
159
self.args, self.body)
162
class FailedSmartServerResponse(SmartServerResponse):
163
"""A SmartServerResponse for a request which failed."""
165
def is_successful(self):
166
"""FailedSmartServerResponse are not successful."""
170
class SuccessfulSmartServerResponse(SmartServerResponse):
171
"""A SmartServerResponse for a successfully completed request."""
173
def is_successful(self):
174
"""SuccessfulSmartServerResponse are successful."""
178
class SmartServerRequestHandler(object):
179
"""Protocol logic for smart server.
181
This doesn't handle serialization at all, it just processes requests and
185
# IMPORTANT FOR IMPLEMENTORS: It is important that SmartServerRequestHandler
186
# not contain encoding or decoding logic to allow the wire protocol to vary
187
# from the object protocol: we will want to tweak the wire protocol separate
188
# from the object model, and ideally we will be able to do that without
189
# having a SmartServerRequestHandler subclass for each wire protocol, rather
190
# just a Protocol subclass.
192
# TODO: Better way of representing the body for commands that take it,
193
# and allow it to be streamed into the server.
195
def __init__(self, backing_transport, commands, root_client_path):
198
:param backing_transport: a Transport to handle requests for.
199
:param commands: a registry mapping command names to SmartServerRequest
200
subclasses. e.g. bzrlib.transport.smart.vfs.vfs_commands.
202
self._backing_transport = backing_transport
203
self._root_client_path = root_client_path
204
self._commands = commands
205
self._body_bytes = ''
207
self.finished_reading = False
210
def accept_body(self, bytes):
211
"""Accept body data."""
213
# TODO: This should be overriden for each command that desired body data
214
# to handle the right format of that data, i.e. plain bytes, a bundle,
215
# etc. The deserialisation into that format should be done in the
218
# default fallback is to accumulate bytes.
219
self._body_bytes += bytes
221
def end_of_body(self):
222
"""No more body data will be received."""
223
self._run_handler_code(self._command.do_body, (self._body_bytes,), {})
224
# cannot read after this.
225
self.finished_reading = True
227
def dispatch_command(self, cmd, args):
228
"""Deprecated compatibility method.""" # XXX XXX
230
command = self._commands.get(cmd)
232
raise errors.SmartProtocolError("bad request %r" % (cmd,))
233
self._command = command(self._backing_transport, self._root_client_path)
234
self._run_handler_code(self._command.execute, args, {})
236
def _run_handler_code(self, callable, args, kwargs):
237
"""Run some handler specific code 'callable'.
239
If a result is returned, it is considered to be the commands response,
240
and finished_reading is set true, and its assigned to self.response.
242
Any exceptions caught are translated and a response object created
245
result = self._call_converting_errors(callable, args, kwargs)
247
if result is not None:
248
self.response = result
249
self.finished_reading = True
251
def _call_converting_errors(self, callable, args, kwargs):
252
"""Call callable converting errors to Response objects."""
253
# XXX: most of this error conversion is VFS-related, and thus ought to
254
# be in SmartServerVFSRequestHandler somewhere.
256
return callable(*args, **kwargs)
257
except errors.NoSuchFile, e:
258
return FailedSmartServerResponse(('NoSuchFile', e.path))
259
except errors.FileExists, e:
260
return FailedSmartServerResponse(('FileExists', e.path))
261
except errors.DirectoryNotEmpty, e:
262
return FailedSmartServerResponse(('DirectoryNotEmpty', e.path))
263
except errors.ShortReadvError, e:
264
return FailedSmartServerResponse(('ShortReadvError',
265
e.path, str(e.offset), str(e.length), str(e.actual)))
266
except UnicodeError, e:
267
# If it is a DecodeError, than most likely we are starting
268
# with a plain string
269
str_or_unicode = e.object
270
if isinstance(str_or_unicode, unicode):
271
# XXX: UTF-8 might have \x01 (our seperator byte) in it. We
272
# should escape it somehow.
273
val = 'u:' + str_or_unicode.encode('utf-8')
275
val = 's:' + str_or_unicode.encode('base64')
276
# This handles UnicodeEncodeError or UnicodeDecodeError
277
return FailedSmartServerResponse((e.__class__.__name__,
278
e.encoding, val, str(e.start), str(e.end), e.reason))
279
except errors.TransportNotPossible, e:
280
if e.msg == "readonly transport":
281
return FailedSmartServerResponse(('ReadOnlyError', ))
286
class HelloRequest(SmartServerRequest):
287
"""Answer a version request with the highest protocol version this server
292
return SuccessfulSmartServerResponse(('ok', '2'))
295
class GetBundleRequest(SmartServerRequest):
296
"""Get a bundle of from the null revision to the specified revision."""
298
def do(self, path, revision_id):
299
# open transport relative to our base
300
t = self.transport_from_client_path(path)
301
control, extra_path = bzrdir.BzrDir.open_containing_from_transport(t)
302
repo = control.open_repository()
303
tmpf = tempfile.TemporaryFile()
304
base_revision = revision.NULL_REVISION
305
write_bundle(repo, revision_id, base_revision, tmpf)
307
return SuccessfulSmartServerResponse((), tmpf.read())
310
class SmartServerIsReadonly(SmartServerRequest):
311
# XXX: this request method belongs somewhere else.
314
if self._backing_transport.is_readonly():
318
return SuccessfulSmartServerResponse((answer,))
321
request_handlers = registry.Registry()
322
request_handlers.register_lazy(
323
'append', 'bzrlib.smart.vfs', 'AppendRequest')
324
request_handlers.register_lazy(
325
'Branch.get_config_file', 'bzrlib.smart.branch', 'SmartServerBranchGetConfigFile')
326
request_handlers.register_lazy(
327
'Branch.last_revision_info', 'bzrlib.smart.branch', 'SmartServerBranchRequestLastRevisionInfo')
328
request_handlers.register_lazy(
329
'Branch.lock_write', 'bzrlib.smart.branch', 'SmartServerBranchRequestLockWrite')
330
request_handlers.register_lazy(
331
'Branch.revision_history', 'bzrlib.smart.branch', 'SmartServerRequestRevisionHistory')
332
request_handlers.register_lazy(
333
'Branch.set_last_revision', 'bzrlib.smart.branch', 'SmartServerBranchRequestSetLastRevision')
334
request_handlers.register_lazy(
335
'Branch.unlock', 'bzrlib.smart.branch', 'SmartServerBranchRequestUnlock')
336
request_handlers.register_lazy(
337
'BzrDir.find_repository', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepository')
338
request_handlers.register_lazy(
339
'BzrDirFormat.initialize', 'bzrlib.smart.bzrdir', 'SmartServerRequestInitializeBzrDir')
340
request_handlers.register_lazy(
341
'BzrDir.open_branch', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBranch')
342
request_handlers.register_lazy(
343
'delete', 'bzrlib.smart.vfs', 'DeleteRequest')
344
request_handlers.register_lazy(
345
'get', 'bzrlib.smart.vfs', 'GetRequest')
346
request_handlers.register_lazy(
347
'get_bundle', 'bzrlib.smart.request', 'GetBundleRequest')
348
request_handlers.register_lazy(
349
'has', 'bzrlib.smart.vfs', 'HasRequest')
350
request_handlers.register_lazy(
351
'hello', 'bzrlib.smart.request', 'HelloRequest')
352
request_handlers.register_lazy(
353
'iter_files_recursive', 'bzrlib.smart.vfs', 'IterFilesRecursiveRequest')
354
request_handlers.register_lazy(
355
'list_dir', 'bzrlib.smart.vfs', 'ListDirRequest')
356
request_handlers.register_lazy(
357
'mkdir', 'bzrlib.smart.vfs', 'MkdirRequest')
358
request_handlers.register_lazy(
359
'move', 'bzrlib.smart.vfs', 'MoveRequest')
360
request_handlers.register_lazy(
361
'put', 'bzrlib.smart.vfs', 'PutRequest')
362
request_handlers.register_lazy(
363
'put_non_atomic', 'bzrlib.smart.vfs', 'PutNonAtomicRequest')
364
request_handlers.register_lazy(
365
'readv', 'bzrlib.smart.vfs', 'ReadvRequest')
366
request_handlers.register_lazy(
367
'rename', 'bzrlib.smart.vfs', 'RenameRequest')
368
request_handlers.register_lazy('Repository.gather_stats',
369
'bzrlib.smart.repository',
370
'SmartServerRepositoryGatherStats')
371
request_handlers.register_lazy(
372
'Repository.stream_knit_data_for_revisions', 'bzrlib.smart.repository',
373
'SmartServerRepositoryStreamKnitDataForRevisions')
374
request_handlers.register_lazy(
375
'Repository.get_revision_graph', 'bzrlib.smart.repository', 'SmartServerRepositoryGetRevisionGraph')
376
request_handlers.register_lazy(
377
'Repository.has_revision', 'bzrlib.smart.repository', 'SmartServerRequestHasRevision')
378
request_handlers.register_lazy(
379
'Repository.is_shared', 'bzrlib.smart.repository', 'SmartServerRepositoryIsShared')
380
request_handlers.register_lazy(
381
'Repository.lock_write', 'bzrlib.smart.repository', 'SmartServerRepositoryLockWrite')
382
request_handlers.register_lazy(
383
'Repository.unlock', 'bzrlib.smart.repository', 'SmartServerRepositoryUnlock')
384
request_handlers.register_lazy(
385
'Repository.tarball', 'bzrlib.smart.repository',
386
'SmartServerRepositoryTarball')
387
request_handlers.register_lazy(
388
'rmdir', 'bzrlib.smart.vfs', 'RmdirRequest')
389
request_handlers.register_lazy(
390
'stat', 'bzrlib.smart.vfs', 'StatRequest')
391
request_handlers.register_lazy(
392
'Transport.is_readonly', 'bzrlib.smart.request', 'SmartServerIsReadonly')
393
request_handlers.register_lazy(
394
'BzrDir.open', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBzrDir')