9
from bzrlib.bundle.serializer import write_bundle
12
class SmartServerResponse(object):
13
"""Response generated by SmartServerRequestHandler."""
15
def __init__(self, args, body=None):
19
# XXX: TODO: Create a SmartServerRequestHandler which will take the responsibility
20
# for delivering the data for a request. This could be done with as the
21
# StreamServer, though that would create conflation between request and response
22
# which may be undesirable.
24
class SmartServerRequestHandler(object):
25
"""Protocol logic for smart server.
27
This doesn't handle serialization at all, it just processes requests and
31
# IMPORTANT FOR IMPLEMENTORS: It is important that SmartServerRequestHandler
32
# not contain encoding or decoding logic to allow the wire protocol to vary
33
# from the object protocol: we will want to tweak the wire protocol separate
34
# from the object model, and ideally we will be able to do that without
35
# having a SmartServerRequestHandler subclass for each wire protocol, rather
36
# just a Protocol subclass.
38
# TODO: Better way of representing the body for commands that take it,
39
# and allow it to be streamed into the server.
41
def __init__(self, backing_transport):
42
self._backing_transport = backing_transport
43
self._converted_command = False
44
self.finished_reading = False
48
def accept_body(self, bytes):
51
This should be overriden for each command that desired body data to
52
handle the right format of that data. I.e. plain bytes, a bundle etc.
54
The deserialisation into that format should be done in the Protocol
55
object. Set self.desired_body_format to the format your method will
58
# default fallback is to accumulate bytes.
59
self._body_bytes += bytes
61
def _end_of_body_handler(self):
62
"""An unimplemented end of body handler."""
63
raise NotImplementedError(self._end_of_body_handler)
66
"""Answer a version request with my version."""
67
return SmartServerResponse(('ok', '1'))
69
def do_has(self, relpath):
70
r = self._backing_transport.has(relpath) and 'yes' or 'no'
71
return SmartServerResponse((r,))
73
def do_get(self, relpath):
74
backing_bytes = self._backing_transport.get_bytes(relpath)
75
return SmartServerResponse(('ok',), backing_bytes)
77
def _deserialise_optional_mode(self, mode):
78
# XXX: FIXME this should be on the protocol object.
84
def do_append(self, relpath, mode):
85
self._converted_command = True
86
self._relpath = relpath
87
self._mode = self._deserialise_optional_mode(mode)
88
self._end_of_body_handler = self._handle_do_append_end
90
def _handle_do_append_end(self):
91
old_length = self._backing_transport.append_bytes(
92
self._relpath, self._body_bytes, self._mode)
93
self.response = SmartServerResponse(('appended', '%d' % old_length))
95
def do_delete(self, relpath):
96
self._backing_transport.delete(relpath)
98
def do_iter_files_recursive(self, relpath):
99
transport = self._backing_transport.clone(relpath)
100
filenames = transport.iter_files_recursive()
101
return SmartServerResponse(('names',) + tuple(filenames))
103
def do_list_dir(self, relpath):
104
filenames = self._backing_transport.list_dir(relpath)
105
return SmartServerResponse(('names',) + tuple(filenames))
107
def do_mkdir(self, relpath, mode):
108
self._backing_transport.mkdir(relpath,
109
self._deserialise_optional_mode(mode))
111
def do_move(self, rel_from, rel_to):
112
self._backing_transport.move(rel_from, rel_to)
114
def do_put(self, relpath, mode):
115
self._converted_command = True
116
self._relpath = relpath
117
self._mode = self._deserialise_optional_mode(mode)
118
self._end_of_body_handler = self._handle_do_put
120
def _handle_do_put(self):
121
self._backing_transport.put_bytes(self._relpath,
122
self._body_bytes, self._mode)
123
self.response = SmartServerResponse(('ok',))
125
def _deserialise_offsets(self, text):
126
# XXX: FIXME this should be on the protocol object.
128
for line in text.split('\n'):
131
start, length = line.split(',')
132
offsets.append((int(start), int(length)))
135
def do_put_non_atomic(self, relpath, mode, create_parent, dir_mode):
136
self._converted_command = True
137
self._end_of_body_handler = self._handle_put_non_atomic
138
self._relpath = relpath
139
self._dir_mode = self._deserialise_optional_mode(dir_mode)
140
self._mode = self._deserialise_optional_mode(mode)
141
# a boolean would be nicer XXX
142
self._create_parent = (create_parent == 'T')
144
def _handle_put_non_atomic(self):
145
self._backing_transport.put_bytes_non_atomic(self._relpath,
148
create_parent_dir=self._create_parent,
149
dir_mode=self._dir_mode)
150
self.response = SmartServerResponse(('ok',))
152
def do_readv(self, relpath):
153
self._converted_command = True
154
self._end_of_body_handler = self._handle_readv_offsets
155
self._relpath = relpath
157
def end_of_body(self):
158
"""No more body data will be received."""
159
self._run_handler_code(self._end_of_body_handler, (), {})
160
# cannot read after this.
161
self.finished_reading = True
163
def _handle_readv_offsets(self):
164
"""accept offsets for a readv request."""
165
offsets = self._deserialise_offsets(self._body_bytes)
166
backing_bytes = ''.join(bytes for offset, bytes in
167
self._backing_transport.readv(self._relpath, offsets))
168
self.response = SmartServerResponse(('readv',), backing_bytes)
170
def do_rename(self, rel_from, rel_to):
171
self._backing_transport.rename(rel_from, rel_to)
173
def do_rmdir(self, relpath):
174
self._backing_transport.rmdir(relpath)
176
def do_stat(self, relpath):
177
stat = self._backing_transport.stat(relpath)
178
return SmartServerResponse(('stat', str(stat.st_size), oct(stat.st_mode)))
180
def do_get_bundle(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())
191
def dispatch_command(self, cmd, args):
192
"""Deprecated compatibility method.""" # XXX XXX
193
func = getattr(self, 'do_' + cmd, None)
195
raise errors.SmartProtocolError("bad request %r" % (cmd,))
196
self._run_handler_code(func, args, {})
198
def _run_handler_code(self, callable, args, kwargs):
199
"""Run some handler specific code 'callable'.
201
If a result is returned, it is considered to be the commands response,
202
and finished_reading is set true, and its assigned to self.response.
204
Any exceptions caught are translated and a response object created
207
result = self._call_converting_errors(callable, args, kwargs)
208
if result is not None:
209
self.response = result
210
self.finished_reading = True
211
# handle unconverted commands
212
if not self._converted_command:
213
self.finished_reading = True
215
self.response = SmartServerResponse(('ok',))
217
def _call_converting_errors(self, callable, args, kwargs):
218
"""Call callable converting errors to Response objects."""
220
return callable(*args, **kwargs)
221
except errors.NoSuchFile, e:
222
return SmartServerResponse(('NoSuchFile', e.path))
223
except errors.FileExists, e:
224
return SmartServerResponse(('FileExists', e.path))
225
except errors.DirectoryNotEmpty, e:
226
return SmartServerResponse(('DirectoryNotEmpty', e.path))
227
except errors.ShortReadvError, e:
228
return SmartServerResponse(('ShortReadvError',
229
e.path, str(e.offset), str(e.length), str(e.actual)))
230
except UnicodeError, e:
231
# If it is a DecodeError, than most likely we are starting
232
# with a plain string
233
str_or_unicode = e.object
234
if isinstance(str_or_unicode, unicode):
235
# XXX: UTF-8 might have \x01 (our seperator byte) in it. We
236
# should escape it somehow.
237
val = 'u:' + str_or_unicode.encode('utf-8')
239
val = 's:' + str_or_unicode.encode('base64')
240
# This handles UnicodeEncodeError or UnicodeDecodeError
241
return SmartServerResponse((e.__class__.__name__,
242
e.encoding, val, str(e.start), str(e.end), e.reason))
243
except errors.TransportNotPossible, e:
244
if e.msg == "readonly transport":
245
return SmartServerResponse(('ReadOnlyError', ))