13
13
# You should have received a copy of the GNU General Public License
14
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).
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Infrastructure for server-side request handlers.
19
Interesting module attributes:
20
* The request_handlers registry maps verb names to SmartServerRequest
22
* The jail_info threading.local() object is used to prevent accidental
23
opening of BzrDirs outside of the backing transport, or any other
24
transports placed in jail_info.transports. The jail_info is reset on
25
every call into a request handler (which can happen an arbitrary number
26
of times during a request).
29
# XXX: The class names are a little confusing: the protocol will instantiate a
30
# SmartServerRequestHandler, whose dispatch_command method creates an instance
31
# of a SmartServerRequest subclass.
31
36
from bzrlib import (
39
46
from bzrlib.lazy_import import lazy_import
40
47
lazy_import(globals(), """
41
48
from bzrlib.bundle import serializer
55
jail_info = threading.local()
56
jail_info.transports = None
60
bzrdir.BzrDir.hooks.install_named_hook(
61
'pre_open', _pre_open_hook, 'checking server jail')
64
def _pre_open_hook(transport):
65
allowed_transports = getattr(jail_info, 'transports', None)
66
if allowed_transports is None:
68
abspath = transport.base
69
for allowed_transport in allowed_transports:
71
allowed_transport.relpath(abspath)
72
except errors.PathNotChild:
76
raise errors.JailBreak(abspath)
45
82
class SmartServerRequest(object):
46
83
"""Base class for request handlers.
53
90
# XXX: rename this class to BaseSmartServerRequestHandler ? A request
54
91
# *handler* is a different concept to the request.
56
def __init__(self, backing_transport, root_client_path='/'):
93
def __init__(self, backing_transport, root_client_path='/', jail_root=None):
59
96
:param backing_transport: the base transport to be used when performing
63
100
from the client. Clients will not be able to refer to paths above
64
101
this root. If root_client_path is None, then no translation will
65
102
be performed on client paths. Default is '/'.
103
:param jail_root: if specified, the root of the BzrDir.open jail to use
104
instead of backing_transport.
67
106
self._backing_transport = backing_transport
107
if jail_root is None:
108
jail_root = backing_transport
109
self._jail_root = jail_root
68
110
if root_client_path is not None:
69
111
if not root_client_path.startswith('/'):
70
112
root_client_path = '/' + root_client_path
137
185
return client_path
138
186
if not client_path.startswith('/'):
139
187
client_path = '/' + client_path
188
if client_path + '/' == self._root_client_path:
140
190
if client_path.startswith(self._root_client_path):
141
191
path = client_path[len(self._root_client_path):]
142
192
relpath = urlutils.joinpath('/', path)
143
193
if not relpath.startswith('/'):
144
194
raise ValueError(relpath)
195
return urlutils.escape('.' + relpath)
147
197
raise errors.PathNotChild(client_path, self._root_client_path)
224
274
# TODO: Better way of representing the body for commands that take it,
225
275
# and allow it to be streamed into the server.
227
def __init__(self, backing_transport, commands, root_client_path):
277
def __init__(self, backing_transport, commands, root_client_path,
230
281
:param backing_transport: a Transport to handle requests for.
234
285
self._backing_transport = backing_transport
235
286
self._root_client_path = root_client_path
236
287
self._commands = commands
288
if jail_root is None:
289
jail_root = backing_transport
290
self._jail_root = jail_root
237
291
self.response = None
238
292
self.finished_reading = False
239
293
self._command = None
294
if 'hpss' in debug.debug_flags:
295
self._request_start_time = osutils.timer_func()
296
self._thread_id = thread.get_ident()
298
def _trace(self, action, message, extra_bytes=None, include_time=False):
299
# It is a bit of a shame that this functionality overlaps with that of
300
# ProtocolThreeRequester._trace. However, there is enough difference
301
# that just putting it in a helper doesn't help a lot. And some state
302
# is taken from the instance.
304
t = '%5.3fs ' % (osutils.timer_func() - self._request_start_time)
307
if extra_bytes is None:
310
extra = ' ' + repr(extra_bytes[:40])
312
extra = extra[:29] + extra[-1] + '...'
313
trace.mutter('%12s: [%s] %s%s%s'
314
% (action, self._thread_id, t, message, extra))
241
316
def accept_body(self, bytes):
242
317
"""Accept body data."""
318
if self._command is None:
319
# no active command object, so ignore the event.
243
321
self._run_handler_code(self._command.do_chunk, (bytes,), {})
322
if 'hpss' in debug.debug_flags:
323
self._trace('accept body',
324
'%d bytes' % (len(bytes),), bytes)
245
326
def end_of_body(self):
246
327
"""No more body data will be received."""
247
328
self._run_handler_code(self._command.do_end, (), {})
248
329
# cannot read after this.
249
330
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, {})
331
if 'hpss' in debug.debug_flags:
332
self._trace('end of body', '', include_time=True)
260
334
def _run_handler_code(self, callable, args, kwargs):
261
335
"""Run some handler specific code 'callable'.
277
351
# XXX: most of this error conversion is VFS-related, and thus ought to
278
352
# be in SmartServerVFSRequestHandler somewhere.
280
return callable(*args, **kwargs)
354
self._command.setup_jail()
356
return callable(*args, **kwargs)
358
self._command.teardown_jail()
281
359
except (KeyboardInterrupt, SystemExit):
283
361
except Exception, err:
295
374
command = self._commands.get(cmd)
296
375
except LookupError:
376
if 'hpss' in debug.debug_flags:
377
self._trace('hpss unknown request',
378
cmd, repr(args)[1:-1])
297
379
raise errors.UnknownSmartMethod(cmd)
298
self._command = command(self._backing_transport)
380
if 'hpss' in debug.debug_flags:
381
from bzrlib.smart import vfs
382
if issubclass(command, vfs.VfsRequest):
383
action = 'hpss vfs req'
385
action = 'hpss request'
387
'%s %s' % (cmd, repr(args)[1:-1]))
388
self._command = command(
389
self._backing_transport, self._root_client_path, self._jail_root)
299
390
self._run_handler_code(self._command.execute, args, {})
301
392
def end_received(self):
393
if self._command is None:
394
# no active command object, so ignore the event.
302
396
self._run_handler_code(self._command.do_end, (), {})
397
if 'hpss' in debug.debug_flags:
398
self._trace('end', '', include_time=True)
304
400
def post_body_error_received(self, error_args):
305
401
# Just a no-op at the moment.
313
409
return ('FileExists', err.path)
314
410
elif isinstance(err, errors.DirectoryNotEmpty):
315
411
return ('DirectoryNotEmpty', err.path)
412
elif isinstance(err, errors.IncompatibleRepositories):
413
return ('IncompatibleRepositories', str(err.source), str(err.target),
316
415
elif isinstance(err, errors.ShortReadvError):
317
416
return ('ShortReadvError', err.path, str(err.offset), str(err.length),
347
446
elif isinstance(err, errors.TokenMismatch):
348
447
return ('TokenMismatch', err.given_token, err.lock_token)
349
448
elif isinstance(err, errors.LockContention):
350
return ('LockContention', err.lock, err.msg)
449
return ('LockContention',)
450
elif isinstance(err, MemoryError):
451
# GZ 2011-02-24: Copy bzrlib.trace -Dmem_dump functionality here?
452
return ('MemoryError',)
351
453
# Unserialisable error. Log it, and return a generic error
352
454
trace.log_exception_quietly()
353
return ('error', str(err))
455
return ('error', trace._qualified_exception_name(err.__class__, True),
356
459
class HelloRequest(SmartServerRequest):
400
503
'Branch.get_tags_bytes', 'bzrlib.smart.branch',
401
504
'SmartServerBranchGetTagsBytes')
402
505
request_handlers.register_lazy(
506
'Branch.set_tags_bytes', 'bzrlib.smart.branch',
507
'SmartServerBranchSetTagsBytes')
508
request_handlers.register_lazy(
509
'Branch.heads_to_fetch', 'bzrlib.smart.branch',
510
'SmartServerBranchHeadsToFetch')
511
request_handlers.register_lazy(
403
512
'Branch.get_stacked_on_url', 'bzrlib.smart.branch', 'SmartServerBranchRequestGetStackedOnURL')
404
513
request_handlers.register_lazy(
405
514
'Branch.last_revision_info', 'bzrlib.smart.branch', 'SmartServerBranchRequestLastRevisionInfo')
406
515
request_handlers.register_lazy(
407
516
'Branch.lock_write', 'bzrlib.smart.branch', 'SmartServerBranchRequestLockWrite')
408
request_handlers.register_lazy(
409
'Branch.revision_history', 'bzrlib.smart.branch', 'SmartServerRequestRevisionHistory')
410
request_handlers.register_lazy(
411
'Branch.set_last_revision', 'bzrlib.smart.branch', 'SmartServerBranchRequestSetLastRevision')
517
request_handlers.register_lazy( 'Branch.revision_history',
518
'bzrlib.smart.branch', 'SmartServerRequestRevisionHistory')
519
request_handlers.register_lazy( 'Branch.set_config_option',
520
'bzrlib.smart.branch', 'SmartServerBranchRequestSetConfigOption')
521
request_handlers.register_lazy( 'Branch.set_config_option_dict',
522
'bzrlib.smart.branch', 'SmartServerBranchRequestSetConfigOptionDict')
523
request_handlers.register_lazy( 'Branch.set_last_revision',
524
'bzrlib.smart.branch', 'SmartServerBranchRequestSetLastRevision')
412
525
request_handlers.register_lazy(
413
526
'Branch.set_last_revision_info', 'bzrlib.smart.branch',
414
527
'SmartServerBranchRequestSetLastRevisionInfo')
416
529
'Branch.set_last_revision_ex', 'bzrlib.smart.branch',
417
530
'SmartServerBranchRequestSetLastRevisionEx')
418
531
request_handlers.register_lazy(
532
'Branch.set_parent_location', 'bzrlib.smart.branch',
533
'SmartServerBranchRequestSetParentLocation')
534
request_handlers.register_lazy(
419
535
'Branch.unlock', 'bzrlib.smart.branch', 'SmartServerBranchRequestUnlock')
420
536
request_handlers.register_lazy(
421
537
'BzrDir.cloning_metadir', 'bzrlib.smart.bzrdir',
436
552
'BzrDir.find_repositoryV3', 'bzrlib.smart.bzrdir',
437
553
'SmartServerRequestFindRepositoryV3')
438
554
request_handlers.register_lazy(
555
'BzrDir.get_config_file', 'bzrlib.smart.bzrdir',
556
'SmartServerBzrDirRequestConfigFile')
557
request_handlers.register_lazy(
439
558
'BzrDirFormat.initialize', 'bzrlib.smart.bzrdir',
440
559
'SmartServerRequestInitializeBzrDir')
441
560
request_handlers.register_lazy(
561
'BzrDirFormat.initialize_ex_1.16', 'bzrlib.smart.bzrdir',
562
'SmartServerRequestBzrDirInitializeEx')
563
request_handlers.register_lazy(
564
'BzrDir.open', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBzrDir')
565
request_handlers.register_lazy(
566
'BzrDir.open_2.1', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBzrDir_2_1')
567
request_handlers.register_lazy(
442
568
'BzrDir.open_branch', 'bzrlib.smart.bzrdir',
443
569
'SmartServerRequestOpenBranch')
444
570
request_handlers.register_lazy(
445
571
'BzrDir.open_branchV2', 'bzrlib.smart.bzrdir',
446
572
'SmartServerRequestOpenBranchV2')
447
573
request_handlers.register_lazy(
574
'BzrDir.open_branchV3', 'bzrlib.smart.bzrdir',
575
'SmartServerRequestOpenBranchV3')
576
request_handlers.register_lazy(
448
577
'delete', 'bzrlib.smart.vfs', 'DeleteRequest')
449
578
request_handlers.register_lazy(
450
579
'get', 'bzrlib.smart.vfs', 'GetRequest')
486
615
request_handlers.register_lazy(
487
616
'Repository.insert_stream', 'bzrlib.smart.repository', 'SmartServerRepositoryInsertStream')
488
617
request_handlers.register_lazy(
618
'Repository.insert_stream_1.19', 'bzrlib.smart.repository', 'SmartServerRepositoryInsertStream_1_19')
619
request_handlers.register_lazy(
489
620
'Repository.insert_stream_locked', 'bzrlib.smart.repository', 'SmartServerRepositoryInsertStreamLocked')
490
621
request_handlers.register_lazy(
491
622
'Repository.is_shared', 'bzrlib.smart.repository', 'SmartServerRepositoryIsShared')
497
628
request_handlers.register_lazy(
498
629
'Repository.unlock', 'bzrlib.smart.repository', 'SmartServerRepositoryUnlock')
499
630
request_handlers.register_lazy(
631
'Repository.get_rev_id_for_revno', 'bzrlib.smart.repository',
632
'SmartServerRepositoryGetRevIdForRevno')
633
request_handlers.register_lazy(
500
634
'Repository.get_stream', 'bzrlib.smart.repository',
501
635
'SmartServerRepositoryGetStream')
502
636
request_handlers.register_lazy(
637
'Repository.get_stream_1.19', 'bzrlib.smart.repository',
638
'SmartServerRepositoryGetStream_1_19')
639
request_handlers.register_lazy(
503
640
'Repository.tarball', 'bzrlib.smart.repository',
504
641
'SmartServerRepositoryTarball')
505
642
request_handlers.register_lazy(
508
645
'stat', 'bzrlib.smart.vfs', 'StatRequest')
509
646
request_handlers.register_lazy(
510
647
'Transport.is_readonly', 'bzrlib.smart.request', 'SmartServerIsReadonly')
511
request_handlers.register_lazy(
512
'BzrDir.open', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBzrDir')