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.
21
The class names are a little confusing: the protocol will instantiate a
22
SmartServerRequestHandler, whose dispatch_command method creates an instance of
23
a SmartServerRequest subclass.
25
The request_handlers registry tracks SmartServerRequest classes (rather than
26
SmartServerRequestHandler).
38
from bzrlib.bundle.serializer import write_bundle
41
class SmartServerRequest(object):
42
"""Base class for request handlers.
44
To define a new request, subclass this class and override the `do` method
45
(and if appropriate, `do_body` as well). Request implementors should take
46
care to call `translate_client_path` and `transport_from_client_path` as
47
appropriate when dealing with paths received from the client.
49
# XXX: rename this class to BaseSmartServerRequestHandler ? A request
50
# *handler* is a different concept to the request.
52
def __init__(self, backing_transport, root_client_path='/'):
55
:param backing_transport: the base transport to be used when performing
57
:param root_client_path: the client path that maps to the root of
58
backing_transport. This is used to interpret relpaths received
59
from the client. Clients will not be able to refer to paths above
60
this root. If root_client_path is None, then no translation will
61
be performed on client paths. Default is '/'.
63
self._backing_transport = backing_transport
64
if root_client_path is not None:
65
if not root_client_path.startswith('/'):
66
root_client_path = '/' + root_client_path
67
if not root_client_path.endswith('/'):
68
root_client_path += '/'
69
self._root_client_path = root_client_path
71
def _check_enabled(self):
72
"""Raises DisabledMethod if this method is disabled."""
76
"""Mandatory extension point for SmartServerRequest subclasses.
78
Subclasses must implement this.
80
This should return a SmartServerResponse if this command expects to
83
raise NotImplementedError(self.do)
85
def execute(self, *args):
86
"""Public entry point to execute this request.
88
It will return a SmartServerResponse if the command does not expect a
91
:param *args: the arguments of the request.
96
def do_body(self, body_bytes):
97
"""Called if the client sends a body with the request.
99
The do() method is still called, and must have returned None.
101
Must return a SmartServerResponse.
103
raise NotImplementedError(self.do_body)
105
def do_chunk(self, chunk_bytes):
106
"""Called with each body chunk if the request has a streamed body.
108
The do() method is still called, and must have returned None.
110
raise NotImplementedError(self.do_chunk)
113
"""Called when the end of the request has been received."""
116
def translate_client_path(self, client_path):
117
"""Translate a path received from a network client into a local
120
All paths received from the client *must* be translated.
122
:param client_path: the path from the client.
123
:returns: a relpath that may be used with self._backing_transport
124
(unlike the untranslated client_path, which must not be used with
125
the backing transport).
127
if self._root_client_path is None:
128
# no translation necessary!
130
if not client_path.startswith('/'):
131
client_path = '/' + client_path
132
if client_path.startswith(self._root_client_path):
133
path = client_path[len(self._root_client_path):]
134
relpath = urlutils.joinpath('/', path)
135
if not relpath.startswith('/'):
136
raise ValueError(relpath)
139
raise errors.PathNotChild(client_path, self._root_client_path)
141
def transport_from_client_path(self, client_path):
142
"""Get a backing transport corresponding to the location referred to by
145
:seealso: translate_client_path
146
:returns: a transport cloned from self._backing_transport
148
relpath = self.translate_client_path(client_path)
149
return self._backing_transport.clone(relpath)
152
class SmartServerResponse(object):
153
"""A response to a client request.
155
This base class should not be used. Instead use
156
SuccessfulSmartServerResponse and FailedSmartServerResponse as appropriate.
159
def __init__(self, args, body=None, body_stream=None):
162
:param args: tuple of response arguments.
163
:param body: string of a response body.
164
:param body_stream: iterable of bytestrings to be streamed to the
168
if body is not None and body_stream is not None:
169
raise errors.BzrError(
170
"'body' and 'body_stream' are mutually exclusive.")
172
self.body_stream = body_stream
174
def __eq__(self, other):
177
return (other.args == self.args and
178
other.body == self.body and
179
other.body_stream is self.body_stream)
182
return "<%s args=%r body=%r>" % (self.__class__.__name__,
183
self.args, self.body)
186
class FailedSmartServerResponse(SmartServerResponse):
187
"""A SmartServerResponse for a request which failed."""
189
def is_successful(self):
190
"""FailedSmartServerResponse are not successful."""
194
class SuccessfulSmartServerResponse(SmartServerResponse):
195
"""A SmartServerResponse for a successfully completed request."""
197
def is_successful(self):
198
"""SuccessfulSmartServerResponse are successful."""
202
class SmartServerRequestHandler(object):
203
"""Protocol logic for smart server.
205
This doesn't handle serialization at all, it just processes requests and
209
# IMPORTANT FOR IMPLEMENTORS: It is important that SmartServerRequestHandler
210
# not contain encoding or decoding logic to allow the wire protocol to vary
211
# from the object protocol: we will want to tweak the wire protocol separate
212
# from the object model, and ideally we will be able to do that without
213
# having a SmartServerRequestHandler subclass for each wire protocol, rather
214
# just a Protocol subclass.
216
# TODO: Better way of representing the body for commands that take it,
217
# and allow it to be streamed into the server.
219
def __init__(self, backing_transport, commands, root_client_path):
222
:param backing_transport: a Transport to handle requests for.
223
:param commands: a registry mapping command names to SmartServerRequest
224
subclasses. e.g. bzrlib.transport.smart.vfs.vfs_commands.
226
self._backing_transport = backing_transport
227
self._root_client_path = root_client_path
228
self._commands = commands
229
self._body_bytes = ''
231
self.finished_reading = False
234
def accept_body(self, bytes):
235
"""Accept body data."""
237
# TODO: This should be overriden for each command that desired body data
238
# to handle the right format of that data, i.e. plain bytes, a bundle,
239
# etc. The deserialisation into that format should be done in the
242
# default fallback is to accumulate bytes.
243
self._body_bytes += bytes
245
def end_of_body(self):
246
"""No more body data will be received."""
247
self._run_handler_code(self._command.do_body, (self._body_bytes,), {})
248
# cannot read after this.
249
self.finished_reading = True
251
def dispatch_command(self, cmd, args):
252
"""Deprecated compatibility method.""" # XXX XXX
254
command = self._commands.get(cmd)
256
raise errors.UnknownSmartMethod(cmd)
257
self._command = command(self._backing_transport, self._root_client_path)
258
self._run_handler_code(self._command.execute, args, {})
260
def _run_handler_code(self, callable, args, kwargs):
261
"""Run some handler specific code 'callable'.
263
If a result is returned, it is considered to be the commands response,
264
and finished_reading is set true, and its assigned to self.response.
266
Any exceptions caught are translated and a response object created
269
result = self._call_converting_errors(callable, args, kwargs)
271
if result is not None:
272
self.response = result
273
self.finished_reading = True
275
def _call_converting_errors(self, callable, args, kwargs):
276
"""Call callable converting errors to Response objects."""
277
# XXX: most of this error conversion is VFS-related, and thus ought to
278
# be in SmartServerVFSRequestHandler somewhere.
280
return callable(*args, **kwargs)
281
except errors.NoSuchFile, e:
282
return FailedSmartServerResponse(('NoSuchFile', e.path))
283
except errors.FileExists, e:
284
return FailedSmartServerResponse(('FileExists', e.path))
285
except errors.DirectoryNotEmpty, e:
286
return FailedSmartServerResponse(('DirectoryNotEmpty', e.path))
287
except errors.ShortReadvError, e:
288
return FailedSmartServerResponse(('ShortReadvError',
289
e.path, str(e.offset), str(e.length), str(e.actual)))
290
except errors.UnstackableRepositoryFormat, e:
291
return FailedSmartServerResponse(('UnstackableRepositoryFormat',
292
str(e.format), e.url))
293
except errors.UnstackableBranchFormat, e:
294
return FailedSmartServerResponse(('UnstackableBranchFormat',
295
str(e.format), e.url))
296
except errors.NotStacked, e:
297
return FailedSmartServerResponse(('NotStacked',))
298
except UnicodeError, e:
299
# If it is a DecodeError, than most likely we are starting
300
# with a plain string
301
str_or_unicode = e.object
302
if isinstance(str_or_unicode, unicode):
303
# XXX: UTF-8 might have \x01 (our seperator byte) in it. We
304
# should escape it somehow.
305
val = 'u:' + str_or_unicode.encode('utf-8')
307
val = 's:' + str_or_unicode.encode('base64')
308
# This handles UnicodeEncodeError or UnicodeDecodeError
309
return FailedSmartServerResponse((e.__class__.__name__,
310
e.encoding, val, str(e.start), str(e.end), e.reason))
311
except errors.TransportNotPossible, e:
312
if e.msg == "readonly transport":
313
return FailedSmartServerResponse(('ReadOnlyError', ))
317
def headers_received(self, headers):
318
# Just a no-op at the moment.
321
def args_received(self, args):
325
command = self._commands.get(cmd)
327
raise errors.UnknownSmartMethod(cmd)
328
self._command = command(self._backing_transport)
329
self._run_handler_code(self._command.execute, args, {})
331
def prefixed_body_received(self, body_bytes):
332
"""No more body data will be received."""
333
self._run_handler_code(self._command.do_body, (body_bytes,), {})
334
# cannot read after this.
335
self.finished_reading = True
337
def body_chunk_received(self, chunk_bytes):
338
self._run_handler_code(self._command.do_chunk, (chunk_bytes,), {})
340
def end_received(self):
341
self._run_handler_code(self._command.do_end, (), {})
344
class HelloRequest(SmartServerRequest):
345
"""Answer a version request with the highest protocol version this server
350
return SuccessfulSmartServerResponse(('ok', '2'))
353
class GetBundleRequest(SmartServerRequest):
354
"""Get a bundle of from the null revision to the specified revision."""
356
def do(self, path, revision_id):
357
# open transport relative to our base
358
t = self.transport_from_client_path(path)
359
control, extra_path = bzrdir.BzrDir.open_containing_from_transport(t)
360
repo = control.open_repository()
361
tmpf = tempfile.TemporaryFile()
362
base_revision = revision.NULL_REVISION
363
write_bundle(repo, revision_id, base_revision, tmpf)
365
return SuccessfulSmartServerResponse((), tmpf.read())
368
class SmartServerIsReadonly(SmartServerRequest):
369
# XXX: this request method belongs somewhere else.
372
if self._backing_transport.is_readonly():
376
return SuccessfulSmartServerResponse((answer,))
379
request_handlers = registry.Registry()
380
request_handlers.register_lazy(
381
'append', 'bzrlib.smart.vfs', 'AppendRequest')
382
request_handlers.register_lazy(
383
'Branch.get_config_file', 'bzrlib.smart.branch', 'SmartServerBranchGetConfigFile')
384
request_handlers.register_lazy(
385
'Branch.get_stacked_on_url', 'bzrlib.smart.branch', 'SmartServerBranchRequestGetStackedOnURL')
386
request_handlers.register_lazy(
387
'Branch.last_revision_info', 'bzrlib.smart.branch', 'SmartServerBranchRequestLastRevisionInfo')
388
request_handlers.register_lazy(
389
'Branch.lock_write', 'bzrlib.smart.branch', 'SmartServerBranchRequestLockWrite')
390
request_handlers.register_lazy(
391
'Branch.revision_history', 'bzrlib.smart.branch', 'SmartServerRequestRevisionHistory')
392
request_handlers.register_lazy(
393
'Branch.set_last_revision', 'bzrlib.smart.branch', 'SmartServerBranchRequestSetLastRevision')
394
request_handlers.register_lazy(
395
'Branch.set_last_revision_info', 'bzrlib.smart.branch',
396
'SmartServerBranchRequestSetLastRevisionInfo')
397
request_handlers.register_lazy(
398
'Branch.set_last_revision_ex', 'bzrlib.smart.branch',
399
'SmartServerBranchRequestSetLastRevisionEx')
400
request_handlers.register_lazy(
401
'Branch.unlock', 'bzrlib.smart.branch', 'SmartServerBranchRequestUnlock')
402
request_handlers.register_lazy(
403
'BzrDir.find_repository', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepositoryV1')
404
request_handlers.register_lazy(
405
'BzrDir.find_repositoryV2', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepositoryV2')
406
request_handlers.register_lazy(
407
'BzrDirFormat.initialize', 'bzrlib.smart.bzrdir', 'SmartServerRequestInitializeBzrDir')
408
request_handlers.register_lazy(
409
'BzrDir.open_branch', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBranch')
410
request_handlers.register_lazy(
411
'delete', 'bzrlib.smart.vfs', 'DeleteRequest')
412
request_handlers.register_lazy(
413
'get', 'bzrlib.smart.vfs', 'GetRequest')
414
request_handlers.register_lazy(
415
'get_bundle', 'bzrlib.smart.request', 'GetBundleRequest')
416
request_handlers.register_lazy(
417
'has', 'bzrlib.smart.vfs', 'HasRequest')
418
request_handlers.register_lazy(
419
'hello', 'bzrlib.smart.request', 'HelloRequest')
420
request_handlers.register_lazy(
421
'iter_files_recursive', 'bzrlib.smart.vfs', 'IterFilesRecursiveRequest')
422
request_handlers.register_lazy(
423
'list_dir', 'bzrlib.smart.vfs', 'ListDirRequest')
424
request_handlers.register_lazy(
425
'mkdir', 'bzrlib.smart.vfs', 'MkdirRequest')
426
request_handlers.register_lazy(
427
'move', 'bzrlib.smart.vfs', 'MoveRequest')
428
request_handlers.register_lazy(
429
'put', 'bzrlib.smart.vfs', 'PutRequest')
430
request_handlers.register_lazy(
431
'put_non_atomic', 'bzrlib.smart.vfs', 'PutNonAtomicRequest')
432
request_handlers.register_lazy(
433
'readv', 'bzrlib.smart.vfs', 'ReadvRequest')
434
request_handlers.register_lazy(
435
'rename', 'bzrlib.smart.vfs', 'RenameRequest')
436
request_handlers.register_lazy('Repository.gather_stats',
437
'bzrlib.smart.repository',
438
'SmartServerRepositoryGatherStats')
439
request_handlers.register_lazy('Repository.get_parent_map',
440
'bzrlib.smart.repository',
441
'SmartServerRepositoryGetParentMap')
442
request_handlers.register_lazy(
443
'Repository.get_revision_graph', 'bzrlib.smart.repository', 'SmartServerRepositoryGetRevisionGraph')
444
request_handlers.register_lazy(
445
'Repository.has_revision', 'bzrlib.smart.repository', 'SmartServerRequestHasRevision')
446
request_handlers.register_lazy(
447
'Repository.is_shared', 'bzrlib.smart.repository', 'SmartServerRepositoryIsShared')
448
request_handlers.register_lazy(
449
'Repository.lock_write', 'bzrlib.smart.repository', 'SmartServerRepositoryLockWrite')
450
request_handlers.register_lazy(
451
'Repository.unlock', 'bzrlib.smart.repository', 'SmartServerRepositoryUnlock')
452
request_handlers.register_lazy(
453
'Repository.tarball', 'bzrlib.smart.repository',
454
'SmartServerRepositoryTarball')
455
request_handlers.register_lazy(
456
'rmdir', 'bzrlib.smart.vfs', 'RmdirRequest')
457
request_handlers.register_lazy(
458
'stat', 'bzrlib.smart.vfs', 'StatRequest')
459
request_handlers.register_lazy(
460
'Transport.is_readonly', 'bzrlib.smart.request', 'SmartServerIsReadonly')
461
request_handlers.register_lazy(
462
'BzrDir.open', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBzrDir')