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
Must return a SmartServerResponse.
72
# TODO: if a client erroneously sends a request that shouldn't have a
73
# body, what to do? Probably SmartServerRequestHandler should catch
74
# this NotImplementedError and translate it into a 'bad request' error
75
# to send to the client.
76
raise NotImplementedError(self.do_body)
79
class SmartServerResponse(object):
80
"""A response to a client request.
82
This base class should not be used. Instead use
83
SuccessfulSmartServerResponse and FailedSmartServerResponse as appropriate.
86
def __init__(self, args, body=None, body_stream=None):
89
:param args: tuple of response arguments.
90
:param body: string of a response body.
91
:param body_stream: iterable of bytestrings to be streamed to the
95
if body is not None and body_stream is not None:
96
raise errors.BzrError(
97
"'body' and 'body_stream' are mutually exclusive.")
99
self.body_stream = body_stream
101
def __eq__(self, other):
104
return (other.args == self.args and
105
other.body == self.body and
106
other.body_stream is self.body_stream)
109
return "<SmartServerResponse %r args=%r body=%r>" % (
110
self.is_successful(), self.args, self.body)
113
class FailedSmartServerResponse(SmartServerResponse):
114
"""A SmartServerResponse for a request which failed."""
116
def is_successful(self):
117
"""FailedSmartServerResponse are not successful."""
121
class SuccessfulSmartServerResponse(SmartServerResponse):
122
"""A SmartServerResponse for a successfully completed request."""
124
def is_successful(self):
125
"""SuccessfulSmartServerResponse are successful."""
129
class SmartServerRequestHandler(object):
130
"""Protocol logic for smart server.
132
This doesn't handle serialization at all, it just processes requests and
136
# IMPORTANT FOR IMPLEMENTORS: It is important that SmartServerRequestHandler
137
# not contain encoding or decoding logic to allow the wire protocol to vary
138
# from the object protocol: we will want to tweak the wire protocol separate
139
# from the object model, and ideally we will be able to do that without
140
# having a SmartServerRequestHandler subclass for each wire protocol, rather
141
# just a Protocol subclass.
143
# TODO: Better way of representing the body for commands that take it,
144
# and allow it to be streamed into the server.
146
def __init__(self, backing_transport, commands):
149
:param backing_transport: a Transport to handle requests for.
150
:param commands: a registry mapping command names to SmartServerRequest
151
subclasses. e.g. bzrlib.transport.smart.vfs.vfs_commands.
153
self._backing_transport = backing_transport
154
self._commands = commands
155
self._body_bytes = ''
157
self.finished_reading = False
160
def accept_body(self, bytes):
161
"""Accept body data."""
163
# TODO: This should be overriden for each command that desired body data
164
# to handle the right format of that data, i.e. plain bytes, a bundle,
165
# etc. The deserialisation into that format should be done in the
168
# default fallback is to accumulate bytes.
169
self._body_bytes += bytes
171
def end_of_body(self):
172
"""No more body data will be received."""
173
self._run_handler_code(self._command.do_body, (self._body_bytes,), {})
174
# cannot read after this.
175
self.finished_reading = True
177
def dispatch_command(self, cmd, args):
178
"""Deprecated compatibility method.""" # XXX XXX
180
command = self._commands.get(cmd)
182
raise errors.SmartProtocolError("bad request %r" % (cmd,))
183
self._command = command(self._backing_transport)
184
self._run_handler_code(self._command.execute, args, {})
186
def _run_handler_code(self, callable, args, kwargs):
187
"""Run some handler specific code 'callable'.
189
If a result is returned, it is considered to be the commands response,
190
and finished_reading is set true, and its assigned to self.response.
192
Any exceptions caught are translated and a response object created
195
result = self._call_converting_errors(callable, args, kwargs)
197
if result is not None:
198
self.response = result
199
self.finished_reading = True
201
def _call_converting_errors(self, callable, args, kwargs):
202
"""Call callable converting errors to Response objects."""
203
# XXX: most of this error conversion is VFS-related, and thus ought to
204
# be in SmartServerVFSRequestHandler somewhere.
206
return callable(*args, **kwargs)
207
except errors.NoSuchFile, e:
208
return FailedSmartServerResponse(('NoSuchFile', e.path))
209
except errors.FileExists, e:
210
return FailedSmartServerResponse(('FileExists', e.path))
211
except errors.DirectoryNotEmpty, e:
212
return FailedSmartServerResponse(('DirectoryNotEmpty', e.path))
213
except errors.ShortReadvError, e:
214
return FailedSmartServerResponse(('ShortReadvError',
215
e.path, str(e.offset), str(e.length), str(e.actual)))
216
except UnicodeError, e:
217
# If it is a DecodeError, than most likely we are starting
218
# with a plain string
219
str_or_unicode = e.object
220
if isinstance(str_or_unicode, unicode):
221
# XXX: UTF-8 might have \x01 (our seperator byte) in it. We
222
# should escape it somehow.
223
val = 'u:' + str_or_unicode.encode('utf-8')
225
val = 's:' + str_or_unicode.encode('base64')
226
# This handles UnicodeEncodeError or UnicodeDecodeError
227
return FailedSmartServerResponse((e.__class__.__name__,
228
e.encoding, val, str(e.start), str(e.end), e.reason))
229
except errors.TransportNotPossible, e:
230
if e.msg == "readonly transport":
231
return FailedSmartServerResponse(('ReadOnlyError', ))
236
class HelloRequest(SmartServerRequest):
237
"""Answer a version request with the highest protocol version this server
242
return SuccessfulSmartServerResponse(('ok', '2'))
245
class GetBundleRequest(SmartServerRequest):
246
"""Get a bundle of from the null revision to the specified revision."""
248
def do(self, path, revision_id):
249
# open transport relative to our base
250
t = self._backing_transport.clone(path)
251
control, extra_path = bzrdir.BzrDir.open_containing_from_transport(t)
252
repo = control.open_repository()
253
tmpf = tempfile.TemporaryFile()
254
base_revision = revision.NULL_REVISION
255
write_bundle(repo, revision_id, base_revision, tmpf)
257
return SuccessfulSmartServerResponse((), tmpf.read())
260
class SmartServerIsReadonly(SmartServerRequest):
261
# XXX: this request method belongs somewhere else.
264
if self._backing_transport.is_readonly():
268
return SuccessfulSmartServerResponse((answer,))
271
request_handlers = registry.Registry()
272
request_handlers.register_lazy(
273
'append', 'bzrlib.smart.vfs', 'AppendRequest')
274
request_handlers.register_lazy(
275
'Branch.get_config_file', 'bzrlib.smart.branch', 'SmartServerBranchGetConfigFile')
276
request_handlers.register_lazy(
277
'Branch.last_revision_info', 'bzrlib.smart.branch', 'SmartServerBranchRequestLastRevisionInfo')
278
request_handlers.register_lazy(
279
'Branch.lock_write', 'bzrlib.smart.branch', 'SmartServerBranchRequestLockWrite')
280
request_handlers.register_lazy(
281
'Branch.revision_history', 'bzrlib.smart.branch', 'SmartServerRequestRevisionHistory')
282
request_handlers.register_lazy(
283
'Branch.set_last_revision', 'bzrlib.smart.branch', 'SmartServerBranchRequestSetLastRevision')
284
request_handlers.register_lazy(
285
'Branch.unlock', 'bzrlib.smart.branch', 'SmartServerBranchRequestUnlock')
286
request_handlers.register_lazy(
287
'BzrDir.find_repository', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepository')
288
request_handlers.register_lazy(
289
'BzrDirFormat.initialize', 'bzrlib.smart.bzrdir', 'SmartServerRequestInitializeBzrDir')
290
request_handlers.register_lazy(
291
'BzrDir.open_branch', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBranch')
292
request_handlers.register_lazy(
293
'delete', 'bzrlib.smart.vfs', 'DeleteRequest')
294
request_handlers.register_lazy(
295
'get', 'bzrlib.smart.vfs', 'GetRequest')
296
request_handlers.register_lazy(
297
'get_bundle', 'bzrlib.smart.request', 'GetBundleRequest')
298
request_handlers.register_lazy(
299
'has', 'bzrlib.smart.vfs', 'HasRequest')
300
request_handlers.register_lazy(
301
'hello', 'bzrlib.smart.request', 'HelloRequest')
302
request_handlers.register_lazy(
303
'iter_files_recursive', 'bzrlib.smart.vfs', 'IterFilesRecursiveRequest')
304
request_handlers.register_lazy(
305
'list_dir', 'bzrlib.smart.vfs', 'ListDirRequest')
306
request_handlers.register_lazy(
307
'mkdir', 'bzrlib.smart.vfs', 'MkdirRequest')
308
request_handlers.register_lazy(
309
'move', 'bzrlib.smart.vfs', 'MoveRequest')
310
request_handlers.register_lazy(
311
'put', 'bzrlib.smart.vfs', 'PutRequest')
312
request_handlers.register_lazy(
313
'put_non_atomic', 'bzrlib.smart.vfs', 'PutNonAtomicRequest')
314
request_handlers.register_lazy(
315
'readv', 'bzrlib.smart.vfs', 'ReadvRequest')
316
request_handlers.register_lazy(
317
'rename', 'bzrlib.smart.vfs', 'RenameRequest')
318
request_handlers.register_lazy('Repository.gather_stats',
319
'bzrlib.smart.repository',
320
'SmartServerRepositoryGatherStats')
321
request_handlers.register_lazy(
322
'Repository.stream_knit_data_for_revisions', 'bzrlib.smart.repository',
323
'SmartServerRepositoryStreamKnitDataForRevisions')
324
request_handlers.register_lazy(
325
'Repository.get_revision_graph', 'bzrlib.smart.repository', 'SmartServerRepositoryGetRevisionGraph')
326
request_handlers.register_lazy(
327
'Repository.has_revision', 'bzrlib.smart.repository', 'SmartServerRequestHasRevision')
328
request_handlers.register_lazy(
329
'Repository.is_shared', 'bzrlib.smart.repository', 'SmartServerRepositoryIsShared')
330
request_handlers.register_lazy(
331
'Repository.lock_write', 'bzrlib.smart.repository', 'SmartServerRepositoryLockWrite')
332
request_handlers.register_lazy(
333
'Repository.unlock', 'bzrlib.smart.repository', 'SmartServerRepositoryUnlock')
334
request_handlers.register_lazy(
335
'Repository.tarball', 'bzrlib.smart.repository',
336
'SmartServerRepositoryTarball')
337
request_handlers.register_lazy(
338
'rmdir', 'bzrlib.smart.vfs', 'RmdirRequest')
339
request_handlers.register_lazy(
340
'stat', 'bzrlib.smart.vfs', 'StatRequest')
341
request_handlers.register_lazy(
342
'Transport.is_readonly', 'bzrlib.smart.request', 'SmartServerIsReadonly')
343
request_handlers.register_lazy(
344
'BzrDir.open', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBzrDir')