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."""
28
from bzrlib.bundle.serializer import write_bundle
31
class SmartServerRequest(object):
32
"""Base class for request handlers."""
34
def __init__(self, backing_transport):
37
:param backing_transport: the base transport to be used when performing
40
self._backing_transport = backing_transport
42
def _check_enabled(self):
43
"""Raises DisabledMethod if this method is disabled."""
47
"""Mandatory extension point for SmartServerRequest subclasses.
49
Subclasses must implement this.
51
This should return a SmartServerResponse if this command expects to
54
raise NotImplementedError(self.do)
56
def execute(self, *args):
57
"""Public entry point to execute this request.
59
It will return a SmartServerResponse if the command does not expect a
62
:param *args: the arguments of the request.
67
def do_body(self, body_bytes):
68
"""Called if the client sends a body with the request.
70
The do() method is still called, and must have returned None.
72
Must return a SmartServerResponse.
74
# TODO: if a client erroneously sends a request that shouldn't have a
75
# body, what to do? Probably SmartServerRequestHandler should catch
76
# this NotImplementedError and translate it into a 'bad request' error
77
# to send to the client.
78
raise NotImplementedError(self.do_body)
81
class SmartServerResponse(object):
82
"""A response to a client request.
84
This base class should not be used. Instead use
85
SuccessfulSmartServerResponse and FailedSmartServerResponse as appropriate.
88
def __init__(self, args, body=None, body_stream=None):
91
:param args: tuple of response arguments.
92
:param body: string of a response body.
93
:param body_stream: iterable of bytestrings to be streamed to the
97
if body is not None and body_stream is not None:
98
raise errors.BzrError(
99
"'body' and 'body_stream' are mutually exclusive.")
101
self.body_stream = body_stream
103
def __eq__(self, other):
106
return (other.args == self.args and
107
other.body == self.body and
108
other.body_stream is self.body_stream)
111
return ("<SmartServerResponse successful=%s args=%r body=%r>"
112
% (self.is_successful(), self.args, self.body))
115
class FailedSmartServerResponse(SmartServerResponse):
116
"""A SmartServerResponse for a request which failed."""
118
def is_successful(self):
119
"""FailedSmartServerResponse are not successful."""
123
class SuccessfulSmartServerResponse(SmartServerResponse):
124
"""A SmartServerResponse for a successfully completed request."""
126
def is_successful(self):
127
"""SuccessfulSmartServerResponse are successful."""
131
class SmartServerRequestHandler(object):
132
"""Protocol logic for smart server.
134
This doesn't handle serialization at all, it just processes requests and
138
# IMPORTANT FOR IMPLEMENTORS: It is important that SmartServerRequestHandler
139
# not contain encoding or decoding logic to allow the wire protocol to vary
140
# from the object protocol: we will want to tweak the wire protocol separate
141
# from the object model, and ideally we will be able to do that without
142
# having a SmartServerRequestHandler subclass for each wire protocol, rather
143
# just a Protocol subclass.
145
# TODO: Better way of representing the body for commands that take it,
146
# and allow it to be streamed into the server.
148
def __init__(self, backing_transport, commands):
151
:param backing_transport: a Transport to handle requests for.
152
:param commands: a registry mapping command names to SmartServerRequest
153
subclasses. e.g. bzrlib.transport.smart.vfs.vfs_commands.
155
self._backing_transport = backing_transport
156
self._commands = commands
157
self._body_bytes = ''
159
self.finished_reading = False
162
def accept_body(self, bytes):
163
"""Accept body data."""
165
# TODO: This should be overriden for each command that desired body data
166
# to handle the right format of that data, i.e. plain bytes, a bundle,
167
# etc. The deserialisation into that format should be done in the
170
# default fallback is to accumulate bytes.
171
self._body_bytes += bytes
173
def end_of_body(self):
174
"""No more body data will be received."""
175
self._run_handler_code(self._command.do_body, (self._body_bytes,), {})
176
# cannot read after this.
177
self.finished_reading = True
179
def dispatch_command(self, cmd, args):
180
"""Deprecated compatibility method.""" # XXX XXX
182
command = self._commands.get(cmd)
184
raise errors.SmartProtocolError("bad request %r" % (cmd,))
185
self._command = command(self._backing_transport)
186
self._run_handler_code(self._command.execute, args, {})
188
def _run_handler_code(self, callable, args, kwargs):
189
"""Run some handler specific code 'callable'.
191
If a result is returned, it is considered to be the commands response,
192
and finished_reading is set true, and its assigned to self.response.
194
Any exceptions caught are translated and a response object created
197
result = self._call_converting_errors(callable, args, kwargs)
199
if result is not None:
200
self.response = result
201
self.finished_reading = True
203
def _call_converting_errors(self, callable, args, kwargs):
204
"""Call callable converting errors to Response objects."""
205
# XXX: most of this error conversion is VFS-related, and thus ought to
206
# be in SmartServerVFSRequestHandler somewhere.
208
return callable(*args, **kwargs)
209
except errors.NoSuchFile, e:
210
return FailedSmartServerResponse(('NoSuchFile', e.path))
211
except errors.FileExists, e:
212
return FailedSmartServerResponse(('FileExists', e.path))
213
except errors.DirectoryNotEmpty, e:
214
return FailedSmartServerResponse(('DirectoryNotEmpty', e.path))
215
except errors.ShortReadvError, e:
216
return FailedSmartServerResponse(('ShortReadvError',
217
e.path, str(e.offset), str(e.length), str(e.actual)))
218
except UnicodeError, e:
219
# If it is a DecodeError, than most likely we are starting
220
# with a plain string
221
str_or_unicode = e.object
222
if isinstance(str_or_unicode, unicode):
223
# XXX: UTF-8 might have \x01 (our seperator byte) in it. We
224
# should escape it somehow.
225
val = 'u:' + str_or_unicode.encode('utf-8')
227
val = 's:' + str_or_unicode.encode('base64')
228
# This handles UnicodeEncodeError or UnicodeDecodeError
229
return FailedSmartServerResponse((e.__class__.__name__,
230
e.encoding, val, str(e.start), str(e.end), e.reason))
231
except errors.TransportNotPossible, e:
232
if e.msg == "readonly transport":
233
return FailedSmartServerResponse(('ReadOnlyError', ))
238
class HelloRequest(SmartServerRequest):
239
"""Answer a version request with the highest protocol version this server
244
return SuccessfulSmartServerResponse(('ok', '2'))
247
class GetBundleRequest(SmartServerRequest):
248
"""Get a bundle of from the null revision to the specified revision."""
250
def do(self, path, revision_id):
251
# open transport relative to our base
252
t = self._backing_transport.clone(path)
253
control, extra_path = bzrdir.BzrDir.open_containing_from_transport(t)
254
repo = control.open_repository()
255
tmpf = tempfile.TemporaryFile()
256
base_revision = revision.NULL_REVISION
257
write_bundle(repo, revision_id, base_revision, tmpf)
259
return SuccessfulSmartServerResponse((), tmpf.read())
262
class SmartServerIsReadonly(SmartServerRequest):
263
# XXX: this request method belongs somewhere else.
266
if self._backing_transport.is_readonly():
270
return SuccessfulSmartServerResponse((answer,))
273
request_handlers = registry.Registry()
274
request_handlers.register_lazy(
275
'append', 'bzrlib.smart.vfs', 'AppendRequest')
276
request_handlers.register_lazy(
277
'Branch.get_config_file', 'bzrlib.smart.branch', 'SmartServerBranchGetConfigFile')
278
request_handlers.register_lazy(
279
'Branch.last_revision_info', 'bzrlib.smart.branch', 'SmartServerBranchRequestLastRevisionInfo')
280
request_handlers.register_lazy(
281
'Branch.lock_write', 'bzrlib.smart.branch', 'SmartServerBranchRequestLockWrite')
282
request_handlers.register_lazy(
283
'Branch.revision_history', 'bzrlib.smart.branch', 'SmartServerRequestRevisionHistory')
284
request_handlers.register_lazy(
285
'Branch.set_last_revision', 'bzrlib.smart.branch', 'SmartServerBranchRequestSetLastRevision')
286
request_handlers.register_lazy(
287
'Branch.unlock', 'bzrlib.smart.branch', 'SmartServerBranchRequestUnlock')
288
request_handlers.register_lazy(
289
'BzrDir.find_repository', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepositoryV1')
290
request_handlers.register_lazy(
291
'BzrDir.find_repositoryV2', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepositoryV2')
292
request_handlers.register_lazy(
293
'BzrDirFormat.initialize', 'bzrlib.smart.bzrdir', 'SmartServerRequestInitializeBzrDir')
294
request_handlers.register_lazy(
295
'BzrDir.open_branch', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBranch')
296
request_handlers.register_lazy(
297
'delete', 'bzrlib.smart.vfs', 'DeleteRequest')
298
request_handlers.register_lazy(
299
'get', 'bzrlib.smart.vfs', 'GetRequest')
300
request_handlers.register_lazy(
301
'get_bundle', 'bzrlib.smart.request', 'GetBundleRequest')
302
request_handlers.register_lazy(
303
'has', 'bzrlib.smart.vfs', 'HasRequest')
304
request_handlers.register_lazy(
305
'hello', 'bzrlib.smart.request', 'HelloRequest')
306
request_handlers.register_lazy(
307
'iter_files_recursive', 'bzrlib.smart.vfs', 'IterFilesRecursiveRequest')
308
request_handlers.register_lazy(
309
'list_dir', 'bzrlib.smart.vfs', 'ListDirRequest')
310
request_handlers.register_lazy(
311
'mkdir', 'bzrlib.smart.vfs', 'MkdirRequest')
312
request_handlers.register_lazy(
313
'move', 'bzrlib.smart.vfs', 'MoveRequest')
314
request_handlers.register_lazy(
315
'put', 'bzrlib.smart.vfs', 'PutRequest')
316
request_handlers.register_lazy(
317
'put_non_atomic', 'bzrlib.smart.vfs', 'PutNonAtomicRequest')
318
request_handlers.register_lazy(
319
'readv', 'bzrlib.smart.vfs', 'ReadvRequest')
320
request_handlers.register_lazy(
321
'rename', 'bzrlib.smart.vfs', 'RenameRequest')
322
request_handlers.register_lazy('Repository.gather_stats',
323
'bzrlib.smart.repository',
324
'SmartServerRepositoryGatherStats')
325
request_handlers.register_lazy('Repository.get_parent_map',
326
'bzrlib.smart.repository',
327
'SmartServerRepositoryGetParentMap')
328
request_handlers.register_lazy(
329
'Repository.stream_knit_data_for_revisions',
330
'bzrlib.smart.repository',
331
'SmartServerRepositoryStreamKnitDataForRevisions')
332
request_handlers.register_lazy(
333
'Repository.stream_revisions_chunked',
334
'bzrlib.smart.repository',
335
'SmartServerRepositoryStreamRevisionsChunked')
336
request_handlers.register_lazy(
337
'Repository.get_revision_graph', 'bzrlib.smart.repository', 'SmartServerRepositoryGetRevisionGraph')
338
request_handlers.register_lazy(
339
'Repository.has_revision', 'bzrlib.smart.repository', 'SmartServerRequestHasRevision')
340
request_handlers.register_lazy(
341
'Repository.is_shared', 'bzrlib.smart.repository', 'SmartServerRepositoryIsShared')
342
request_handlers.register_lazy(
343
'Repository.lock_write', 'bzrlib.smart.repository', 'SmartServerRepositoryLockWrite')
344
request_handlers.register_lazy(
345
'Repository.unlock', 'bzrlib.smart.repository', 'SmartServerRepositoryUnlock')
346
request_handlers.register_lazy(
347
'Repository.tarball', 'bzrlib.smart.repository',
348
'SmartServerRepositoryTarball')
349
request_handlers.register_lazy(
350
'rmdir', 'bzrlib.smart.vfs', 'RmdirRequest')
351
request_handlers.register_lazy(
352
'stat', 'bzrlib.smart.vfs', 'StatRequest')
353
request_handlers.register_lazy(
354
'Transport.is_readonly', 'bzrlib.smart.request', 'SmartServerIsReadonly')
355
request_handlers.register_lazy(
356
'BzrDir.open', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBzrDir')