1
# Copyright (C) 2006 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."""
22
from bzrlib import bzrdir, errors, registry, revision
23
from bzrlib.bundle.serializer import write_bundle
26
class SmartServerRequest(object):
27
"""Base class for request handlers.
30
def __init__(self, backing_transport):
31
self._backing_transport = backing_transport
33
def _check_enabled(self):
34
"""Raises DisabledMethod if this method is disabled."""
38
"""Mandatory extension point for SmartServerRequest subclasses.
40
Subclasses must implement this.
42
This should return a SmartServerResponse if this command expects to
45
raise NotImplementedError(self.do)
47
def execute(self, *args):
48
"""Public entry point to execute this request.
50
It will return a SmartServerResponse if the command does not expect a
53
:param *args: the arguments of the request.
58
def do_body(self, body_bytes):
59
"""Called if the client sends a body with the request.
61
Must return a SmartServerResponse.
63
# TODO: if a client erroneously sends a request that shouldn't have a
64
# body, what to do? Probably SmartServerRequestHandler should catch
65
# this NotImplementedError and translate it into a 'bad request' error
66
# to send to the client.
67
raise NotImplementedError(self.do_body)
70
class SmartServerResponse(object):
71
"""Response generated by SmartServerRequestHandler."""
73
def __init__(self, args, body=None):
77
def __eq__(self, other):
78
return other.args == self.args and other.body == self.body
81
return "<SmartServerResponse args=%r body=%r>" % (self.args, self.body)
84
class SmartServerRequestHandler(object):
85
"""Protocol logic for smart server.
87
This doesn't handle serialization at all, it just processes requests and
91
# IMPORTANT FOR IMPLEMENTORS: It is important that SmartServerRequestHandler
92
# not contain encoding or decoding logic to allow the wire protocol to vary
93
# from the object protocol: we will want to tweak the wire protocol separate
94
# from the object model, and ideally we will be able to do that without
95
# having a SmartServerRequestHandler subclass for each wire protocol, rather
96
# just a Protocol subclass.
98
# TODO: Better way of representing the body for commands that take it,
99
# and allow it to be streamed into the server.
101
def __init__(self, backing_transport, commands):
104
:param backing_transport: a Transport to handle requests for.
105
:param commands: a registry mapping command names to SmartServerRequest
106
subclasses. e.g. bzrlib.transport.smart.vfs.vfs_commands.
108
self._backing_transport = backing_transport
109
self._commands = commands
110
self._body_bytes = ''
112
self.finished_reading = False
115
def accept_body(self, bytes):
116
"""Accept body data."""
118
# TODO: This should be overriden for each command that desired body data
119
# to handle the right format of that data, i.e. plain bytes, a bundle,
120
# etc. The deserialisation into that format should be done in the
123
# default fallback is to accumulate bytes.
124
self._body_bytes += bytes
126
def end_of_body(self):
127
"""No more body data will be received."""
128
self._run_handler_code(self._command.do_body, (self._body_bytes,), {})
129
# cannot read after this.
130
self.finished_reading = True
132
def dispatch_command(self, cmd, args):
133
"""Deprecated compatibility method.""" # XXX XXX
135
command = self._commands.get(cmd)
137
raise errors.SmartProtocolError("bad request %r" % (cmd,))
138
self._command = command(self._backing_transport)
139
self._run_handler_code(self._command.execute, args, {})
141
def _run_handler_code(self, callable, args, kwargs):
142
"""Run some handler specific code 'callable'.
144
If a result is returned, it is considered to be the commands response,
145
and finished_reading is set true, and its assigned to self.response.
147
Any exceptions caught are translated and a response object created
150
result = self._call_converting_errors(callable, args, kwargs)
152
if result is not None:
153
self.response = result
154
self.finished_reading = True
156
def _call_converting_errors(self, callable, args, kwargs):
157
"""Call callable converting errors to Response objects."""
158
# XXX: most of this error conversion is VFS-related, and thus ought to
159
# be in SmartServerVFSRequestHandler somewhere.
161
return callable(*args, **kwargs)
162
except errors.NoSuchFile, e:
163
return SmartServerResponse(('NoSuchFile', e.path))
164
except errors.FileExists, e:
165
return SmartServerResponse(('FileExists', e.path))
166
except errors.DirectoryNotEmpty, e:
167
return SmartServerResponse(('DirectoryNotEmpty', e.path))
168
except errors.ShortReadvError, e:
169
return SmartServerResponse(('ShortReadvError',
170
e.path, str(e.offset), str(e.length), str(e.actual)))
171
except UnicodeError, e:
172
# If it is a DecodeError, than most likely we are starting
173
# with a plain string
174
str_or_unicode = e.object
175
if isinstance(str_or_unicode, unicode):
176
# XXX: UTF-8 might have \x01 (our seperator byte) in it. We
177
# should escape it somehow.
178
val = 'u:' + str_or_unicode.encode('utf-8')
180
val = 's:' + str_or_unicode.encode('base64')
181
# This handles UnicodeEncodeError or UnicodeDecodeError
182
return SmartServerResponse((e.__class__.__name__,
183
e.encoding, val, str(e.start), str(e.end), e.reason))
184
except errors.TransportNotPossible, e:
185
if e.msg == "readonly transport":
186
return SmartServerResponse(('ReadOnlyError', ))
191
class HelloRequest(SmartServerRequest):
192
"""Answer a version request with my version."""
195
return SmartServerResponse(('ok', '1'))
198
class GetBundleRequest(SmartServerRequest):
200
def do(self, path, revision_id):
201
# open transport relative to our base
202
t = self._backing_transport.clone(path)
203
control, extra_path = bzrdir.BzrDir.open_containing_from_transport(t)
204
repo = control.open_repository()
205
tmpf = tempfile.TemporaryFile()
206
base_revision = revision.NULL_REVISION
207
write_bundle(repo, revision_id, base_revision, tmpf)
209
return SmartServerResponse((), tmpf.read())
212
# This exists solely to help RemoteObjectHacking. It should be removed
213
# eventually. It should not be considered part of the real smart server
215
class ProbeDontUseRequest(SmartServerRequest):
218
from bzrlib.bzrdir import BzrDirFormat
219
t = self._backing_transport.clone(path)
220
default_format = BzrDirFormat.get_default_format()
221
real_bzrdir = default_format.open(t, _found=True)
223
real_bzrdir._format.probe_transport(t)
224
except (errors.NotBranchError, errors.UnknownFormatError):
228
return SmartServerResponse((answer,))
231
request_handlers = registry.Registry()
232
request_handlers.register_lazy(
233
'append', 'bzrlib.smart.vfs', 'AppendRequest')
234
request_handlers.register_lazy(
235
'BzrDir.find_repository', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepository')
236
request_handlers.register_lazy(
237
'BzrDir.open_branch', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBranch')
238
request_handlers.register_lazy(
239
'delete', 'bzrlib.smart.vfs', 'DeleteRequest')
240
request_handlers.register_lazy(
241
'get', 'bzrlib.smart.vfs', 'GetRequest')
242
request_handlers.register_lazy(
243
'get_bundle', 'bzrlib.smart.request', 'GetBundleRequest')
244
request_handlers.register_lazy(
245
'has', 'bzrlib.smart.vfs', 'HasRequest')
246
request_handlers.register_lazy(
247
'hello', 'bzrlib.smart.request', 'HelloRequest')
248
request_handlers.register_lazy(
249
'iter_files_recursive', 'bzrlib.smart.vfs', 'IterFilesRecursiveRequest')
250
request_handlers.register_lazy(
251
'list_dir', 'bzrlib.smart.vfs', 'ListDirRequest')
252
request_handlers.register_lazy(
253
'mkdir', 'bzrlib.smart.vfs', 'MkdirRequest')
254
request_handlers.register_lazy(
255
'move', 'bzrlib.smart.vfs', 'MoveRequest')
256
request_handlers.register_lazy(
257
'put', 'bzrlib.smart.vfs', 'PutRequest')
258
request_handlers.register_lazy(
259
'put_non_atomic', 'bzrlib.smart.vfs', 'PutNonAtomicRequest')
260
request_handlers.register_lazy(
261
'readv', 'bzrlib.smart.vfs', 'ReadvRequest')
262
request_handlers.register_lazy(
263
'rename', 'bzrlib.smart.vfs', 'RenameRequest')
264
request_handlers.register_lazy(
265
'rmdir', 'bzrlib.smart.vfs', 'RmdirRequest')
266
request_handlers.register_lazy(
267
'stat', 'bzrlib.smart.vfs', 'StatRequest')
268
request_handlers.register_lazy(
269
'probe_dont_use', 'bzrlib.smart.request', 'ProbeDontUseRequest')