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, 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
34
"""Called with the arguments of the request.
36
This should return a SmartServerResponse if this command expects to
39
raise NotImplementedError(self.do)
41
def do_body(self, body_bytes):
42
"""Called if the client sends a body with the request.
44
Must return a SmartServerResponse.
46
# TODO: if a client erroneously sends a request that shouldn't have a
47
# body, what to do? Probably SmartServerRequestHandler should catch
48
# this NotImplementedError and translate it into a 'bad request' error
49
# to send to the client.
50
raise NotImplementedError(self.do_body)
53
class SmartServerResponse(object):
54
"""Response generated by SmartServerRequestHandler."""
56
def __init__(self, args, body=None):
61
class SmartServerRequestHandler(object):
62
"""Protocol logic for smart server.
64
This doesn't handle serialization at all, it just processes requests and
68
# IMPORTANT FOR IMPLEMENTORS: It is important that SmartServerRequestHandler
69
# not contain encoding or decoding logic to allow the wire protocol to vary
70
# from the object protocol: we will want to tweak the wire protocol separate
71
# from the object model, and ideally we will be able to do that without
72
# having a SmartServerRequestHandler subclass for each wire protocol, rather
73
# just a Protocol subclass.
75
# TODO: Better way of representing the body for commands that take it,
76
# and allow it to be streamed into the server.
78
def __init__(self, backing_transport, commands):
81
:param backing_transport: a Transport to handle requests for.
82
:param commands: a dict mapping command names to SmartServerRequest
83
subclasses. e.g. bzrlib.transport.smart.vfs.vfs_commands.
85
self._backing_transport = backing_transport
86
self._commands = commands
89
self.finished_reading = False
92
def accept_body(self, bytes):
93
"""Accept body data."""
95
# TODO: This should be overriden for each command that desired body data
96
# to handle the right format of that data, i.e. plain bytes, a bundle,
97
# etc. The deserialisation into that format should be done in the
100
# default fallback is to accumulate bytes.
101
self._body_bytes += bytes
103
def end_of_body(self):
104
"""No more body data will be received."""
105
self._run_handler_code(self._command.do_body, (self._body_bytes,), {})
106
# cannot read after this.
107
self.finished_reading = True
109
def dispatch_command(self, cmd, args):
110
"""Deprecated compatibility method.""" # XXX XXX
111
command = self._commands.get(cmd)
113
raise errors.SmartProtocolError("bad request %r" % (cmd,))
114
self._command = command(self._backing_transport)
115
self._run_handler_code(self._command.do, args, {})
117
def _run_handler_code(self, callable, args, kwargs):
118
"""Run some handler specific code 'callable'.
120
If a result is returned, it is considered to be the commands response,
121
and finished_reading is set true, and its assigned to self.response.
123
Any exceptions caught are translated and a response object created
126
result = self._call_converting_errors(callable, args, kwargs)
128
if result is not None:
129
self.response = result
130
self.finished_reading = True
132
def _call_converting_errors(self, callable, args, kwargs):
133
"""Call callable converting errors to Response objects."""
134
# XXX: most of this error conversion is VFS-related, and thus ought to
135
# be in SmartServerVFSRequestHandler somewhere.
137
return callable(*args, **kwargs)
138
except errors.NoSuchFile, e:
139
return SmartServerResponse(('NoSuchFile', e.path))
140
except errors.FileExists, e:
141
return SmartServerResponse(('FileExists', e.path))
142
except errors.DirectoryNotEmpty, e:
143
return SmartServerResponse(('DirectoryNotEmpty', e.path))
144
except errors.ShortReadvError, e:
145
return SmartServerResponse(('ShortReadvError',
146
e.path, str(e.offset), str(e.length), str(e.actual)))
147
except UnicodeError, e:
148
# If it is a DecodeError, than most likely we are starting
149
# with a plain string
150
str_or_unicode = e.object
151
if isinstance(str_or_unicode, unicode):
152
# XXX: UTF-8 might have \x01 (our seperator byte) in it. We
153
# should escape it somehow.
154
val = 'u:' + str_or_unicode.encode('utf-8')
156
val = 's:' + str_or_unicode.encode('base64')
157
# This handles UnicodeEncodeError or UnicodeDecodeError
158
return SmartServerResponse((e.__class__.__name__,
159
e.encoding, val, str(e.start), str(e.end), e.reason))
160
except errors.TransportNotPossible, e:
161
if e.msg == "readonly transport":
162
return SmartServerResponse(('ReadOnlyError', ))
167
class HelloRequest(SmartServerRequest):
168
"""Answer a version request with my version."""
173
return SmartServerResponse(('ok', '1'))
176
class GetBundleRequest(SmartServerRequest):
178
method = 'get_bundle'
180
def do(self, path, revision_id):
181
# open transport relative to our base
182
t = self._backing_transport.clone(path)
183
control, extra_path = bzrdir.BzrDir.open_containing_from_transport(t)
184
repo = control.open_repository()
185
tmpf = tempfile.TemporaryFile()
186
base_revision = revision.NULL_REVISION
187
write_bundle(repo, revision_id, base_revision, tmpf)
189
return SmartServerResponse((), tmpf.read())
192
# This is extended by bzrlib/transport/smart/vfs.py
193
version_one_commands = {
194
HelloRequest.method: HelloRequest,
195
GetBundleRequest.method: GetBundleRequest,