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
The do() method is still called, and must have returned None.
92
Must return a SmartServerResponse.
94
# TODO: if a client erroneously sends a request that shouldn't have a
95
# body, what to do? Probably SmartServerRequestHandler should catch
96
# this NotImplementedError and translate it into a 'bad request' error
97
# to send to the client.
98
raise NotImplementedError(self.do_body)
100
def translate_client_path(self, client_path):
101
"""Translate a path received from a network client into a local
104
All paths received from the client *must* be translated.
106
:param client_path: the path from the client.
107
:returns: a relpath that may be used with self._backing_transport
108
(unlike the untranslated client_path, which must not be used with
109
the backing transport).
111
if self._root_client_path is None:
112
# no translation necessary!
114
if not client_path.startswith('/'):
115
client_path = '/' + client_path
116
if client_path.startswith(self._root_client_path):
117
path = client_path[len(self._root_client_path):]
118
relpath = urlutils.joinpath('/', path)
119
assert relpath.startswith('/')
122
raise errors.PathNotChild(client_path, self._root_client_path)
124
def transport_from_client_path(self, client_path):
125
"""Get a backing transport corresponding to the location referred to by
128
:seealso: translate_client_path
129
:returns: a transport cloned from self._backing_transport
131
relpath = self.translate_client_path(client_path)
132
return self._backing_transport.clone(relpath)
135
class SmartServerResponse(object):
136
"""A response to a client request.
138
This base class should not be used. Instead use
139
SuccessfulSmartServerResponse and FailedSmartServerResponse as appropriate.
142
def __init__(self, args, body=None, body_stream=None):
145
:param args: tuple of response arguments.
146
:param body: string of a response body.
147
:param body_stream: iterable of bytestrings to be streamed to the
151
if body is not None and body_stream is not None:
152
raise errors.BzrError(
153
"'body' and 'body_stream' are mutually exclusive.")
155
self.body_stream = body_stream
157
def __eq__(self, other):
160
return (other.args == self.args and
161
other.body == self.body and
162
other.body_stream is self.body_stream)
165
status = {True: 'OK', False: 'ERR'}[self.is_successful()]
166
return "<SmartServerResponse status=%s args=%r body=%r>" % (status,
167
self.args, self.body)
170
class FailedSmartServerResponse(SmartServerResponse):
171
"""A SmartServerResponse for a request which failed."""
173
def is_successful(self):
174
"""FailedSmartServerResponse are not successful."""
178
class SuccessfulSmartServerResponse(SmartServerResponse):
179
"""A SmartServerResponse for a successfully completed request."""
181
def is_successful(self):
182
"""SuccessfulSmartServerResponse are successful."""
186
class SmartServerRequestHandler(object):
187
"""Protocol logic for smart server.
189
This doesn't handle serialization at all, it just processes requests and
193
# IMPORTANT FOR IMPLEMENTORS: It is important that SmartServerRequestHandler
194
# not contain encoding or decoding logic to allow the wire protocol to vary
195
# from the object protocol: we will want to tweak the wire protocol separate
196
# from the object model, and ideally we will be able to do that without
197
# having a SmartServerRequestHandler subclass for each wire protocol, rather
198
# just a Protocol subclass.
200
# TODO: Better way of representing the body for commands that take it,
201
# and allow it to be streamed into the server.
203
def __init__(self, backing_transport, commands, root_client_path):
206
:param backing_transport: a Transport to handle requests for.
207
:param commands: a registry mapping command names to SmartServerRequest
208
subclasses. e.g. bzrlib.transport.smart.vfs.vfs_commands.
210
self._backing_transport = backing_transport
211
self._root_client_path = root_client_path
212
self._commands = commands
213
self._body_bytes = ''
215
self.finished_reading = False
218
def accept_body(self, bytes):
219
"""Accept body data."""
221
# TODO: This should be overriden for each command that desired body data
222
# to handle the right format of that data, i.e. plain bytes, a bundle,
223
# etc. The deserialisation into that format should be done in the
226
# default fallback is to accumulate bytes.
227
self._body_bytes += bytes
229
def end_of_body(self):
230
"""No more body data will be received."""
231
self._run_handler_code(self._command.do_body, (self._body_bytes,), {})
232
# cannot read after this.
233
self.finished_reading = True
235
def dispatch_command(self, cmd, args):
236
"""Deprecated compatibility method.""" # XXX XXX
238
command = self._commands.get(cmd)
240
raise errors.SmartProtocolError("bad request %r" % (cmd,))
241
self._command = command(self._backing_transport, self._root_client_path)
242
self._run_handler_code(self._command.execute, args, {})
244
def _run_handler_code(self, callable, args, kwargs):
245
"""Run some handler specific code 'callable'.
247
If a result is returned, it is considered to be the commands response,
248
and finished_reading is set true, and its assigned to self.response.
250
Any exceptions caught are translated and a response object created
253
result = self._call_converting_errors(callable, args, kwargs)
255
if result is not None:
256
self.response = result
257
self.finished_reading = True
259
def _call_converting_errors(self, callable, args, kwargs):
260
"""Call callable converting errors to Response objects."""
261
# XXX: most of this error conversion is VFS-related, and thus ought to
262
# be in SmartServerVFSRequestHandler somewhere.
264
return callable(*args, **kwargs)
265
except errors.NoSuchFile, e:
266
return FailedSmartServerResponse(('NoSuchFile', e.path))
267
except errors.FileExists, e:
268
return FailedSmartServerResponse(('FileExists', e.path))
269
except errors.DirectoryNotEmpty, e:
270
return FailedSmartServerResponse(('DirectoryNotEmpty', e.path))
271
except errors.ShortReadvError, e:
272
return FailedSmartServerResponse(('ShortReadvError',
273
e.path, str(e.offset), str(e.length), str(e.actual)))
274
except UnicodeError, e:
275
# If it is a DecodeError, than most likely we are starting
276
# with a plain string
277
str_or_unicode = e.object
278
if isinstance(str_or_unicode, unicode):
279
# XXX: UTF-8 might have \x01 (our seperator byte) in it. We
280
# should escape it somehow.
281
val = 'u:' + str_or_unicode.encode('utf-8')
283
val = 's:' + str_or_unicode.encode('base64')
284
# This handles UnicodeEncodeError or UnicodeDecodeError
285
return FailedSmartServerResponse((e.__class__.__name__,
286
e.encoding, val, str(e.start), str(e.end), e.reason))
287
except errors.TransportNotPossible, e:
288
if e.msg == "readonly transport":
289
return FailedSmartServerResponse(('ReadOnlyError', ))
294
class HelloRequest(SmartServerRequest):
295
"""Answer a version request with the highest protocol version this server
300
return SuccessfulSmartServerResponse(('ok', '2'))
303
class GetBundleRequest(SmartServerRequest):
304
"""Get a bundle of from the null revision to the specified revision."""
306
def do(self, path, revision_id):
307
# open transport relative to our base
308
t = self.transport_from_client_path(path)
309
control, extra_path = bzrdir.BzrDir.open_containing_from_transport(t)
310
repo = control.open_repository()
311
tmpf = tempfile.TemporaryFile()
312
base_revision = revision.NULL_REVISION
313
write_bundle(repo, revision_id, base_revision, tmpf)
315
return SuccessfulSmartServerResponse((), tmpf.read())
318
class SmartServerIsReadonly(SmartServerRequest):
319
# XXX: this request method belongs somewhere else.
322
if self._backing_transport.is_readonly():
326
return SuccessfulSmartServerResponse((answer,))
329
request_handlers = registry.Registry()
330
request_handlers.register_lazy(
331
'append', 'bzrlib.smart.vfs', 'AppendRequest')
332
request_handlers.register_lazy(
333
'Branch.get_config_file', 'bzrlib.smart.branch', 'SmartServerBranchGetConfigFile')
334
request_handlers.register_lazy(
335
'Branch.last_revision_info', 'bzrlib.smart.branch', 'SmartServerBranchRequestLastRevisionInfo')
336
request_handlers.register_lazy(
337
'Branch.lock_write', 'bzrlib.smart.branch', 'SmartServerBranchRequestLockWrite')
338
request_handlers.register_lazy(
339
'Branch.revision_history', 'bzrlib.smart.branch', 'SmartServerRequestRevisionHistory')
340
request_handlers.register_lazy(
341
'Branch.set_last_revision', 'bzrlib.smart.branch', 'SmartServerBranchRequestSetLastRevision')
342
request_handlers.register_lazy(
343
'Branch.set_last_revision_info', 'bzrlib.smart.branch',
344
'SmartServerBranchRequestSetLastRevisionInfo')
345
request_handlers.register_lazy(
346
'Branch.unlock', 'bzrlib.smart.branch', 'SmartServerBranchRequestUnlock')
347
request_handlers.register_lazy(
348
'BzrDir.find_repository', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepositoryV1')
349
request_handlers.register_lazy(
350
'BzrDir.find_repositoryV2', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepositoryV2')
351
request_handlers.register_lazy(
352
'BzrDirFormat.initialize', 'bzrlib.smart.bzrdir', 'SmartServerRequestInitializeBzrDir')
353
request_handlers.register_lazy(
354
'BzrDir.open_branch', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBranch')
355
request_handlers.register_lazy(
356
'delete', 'bzrlib.smart.vfs', 'DeleteRequest')
357
request_handlers.register_lazy(
358
'get', 'bzrlib.smart.vfs', 'GetRequest')
359
request_handlers.register_lazy(
360
'get_bundle', 'bzrlib.smart.request', 'GetBundleRequest')
361
request_handlers.register_lazy(
362
'has', 'bzrlib.smart.vfs', 'HasRequest')
363
request_handlers.register_lazy(
364
'hello', 'bzrlib.smart.request', 'HelloRequest')
365
request_handlers.register_lazy(
366
'iter_files_recursive', 'bzrlib.smart.vfs', 'IterFilesRecursiveRequest')
367
request_handlers.register_lazy(
368
'list_dir', 'bzrlib.smart.vfs', 'ListDirRequest')
369
request_handlers.register_lazy(
370
'mkdir', 'bzrlib.smart.vfs', 'MkdirRequest')
371
request_handlers.register_lazy(
372
'move', 'bzrlib.smart.vfs', 'MoveRequest')
373
request_handlers.register_lazy(
374
'put', 'bzrlib.smart.vfs', 'PutRequest')
375
request_handlers.register_lazy(
376
'put_non_atomic', 'bzrlib.smart.vfs', 'PutNonAtomicRequest')
377
request_handlers.register_lazy(
378
'readv', 'bzrlib.smart.vfs', 'ReadvRequest')
379
request_handlers.register_lazy(
380
'rename', 'bzrlib.smart.vfs', 'RenameRequest')
381
request_handlers.register_lazy('Repository.gather_stats',
382
'bzrlib.smart.repository',
383
'SmartServerRepositoryGatherStats')
384
request_handlers.register_lazy('Repository.get_parent_map',
385
'bzrlib.smart.repository',
386
'SmartServerRepositoryGetParentMap')
387
request_handlers.register_lazy(
388
'Repository.stream_knit_data_for_revisions',
389
'bzrlib.smart.repository',
390
'SmartServerRepositoryStreamKnitDataForRevisions')
391
request_handlers.register_lazy(
392
'Repository.stream_revisions_chunked',
393
'bzrlib.smart.repository',
394
'SmartServerRepositoryStreamRevisionsChunked')
395
request_handlers.register_lazy(
396
'Repository.get_revision_graph', 'bzrlib.smart.repository', 'SmartServerRepositoryGetRevisionGraph')
397
request_handlers.register_lazy(
398
'Repository.has_revision', 'bzrlib.smart.repository', 'SmartServerRequestHasRevision')
399
request_handlers.register_lazy(
400
'Repository.is_shared', 'bzrlib.smart.repository', 'SmartServerRepositoryIsShared')
401
request_handlers.register_lazy(
402
'Repository.lock_write', 'bzrlib.smart.repository', 'SmartServerRepositoryLockWrite')
403
request_handlers.register_lazy(
404
'Repository.unlock', 'bzrlib.smart.repository', 'SmartServerRepositoryUnlock')
405
request_handlers.register_lazy(
406
'Repository.tarball', 'bzrlib.smart.repository',
407
'SmartServerRepositoryTarball')
408
request_handlers.register_lazy(
409
'rmdir', 'bzrlib.smart.vfs', 'RmdirRequest')
410
request_handlers.register_lazy(
411
'stat', 'bzrlib.smart.vfs', 'StatRequest')
412
request_handlers.register_lazy(
413
'Transport.is_readonly', 'bzrlib.smart.request', 'SmartServerIsReadonly')
414
request_handlers.register_lazy(
415
'BzrDir.open', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBzrDir')