/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/transport/smart/request.py

Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006 Canonical Ltd
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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
 
16
 
 
17
import tempfile
 
18
 
 
19
from bzrlib import bzrdir, errors, revision
 
20
from bzrlib.bundle.serializer import write_bundle
 
21
from bzrlib.transport.smart import protocol
 
22
 
 
23
 
 
24
class SmartServerRequest(object):
 
25
    """Base class for request handlers.
 
26
 
 
27
    (Command pattern.)
 
28
    """
 
29
 
 
30
    def __init__(self, backing_transport):
 
31
        self._backing_transport = backing_transport
 
32
 
 
33
    def do(self):
 
34
        raise NotImplementedError(self.do)
 
35
 
 
36
    def do_body(self, body_bytes):
 
37
        raise NotImplementedError(self.do_body)
 
38
 
 
39
 
 
40
class SmartServerRequestHandler(object):
 
41
    """Protocol logic for smart server.
 
42
    
 
43
    This doesn't handle serialization at all, it just processes requests and
 
44
    creates responses.
 
45
    """
 
46
 
 
47
    # IMPORTANT FOR IMPLEMENTORS: It is important that SmartServerRequestHandler
 
48
    # not contain encoding or decoding logic to allow the wire protocol to vary
 
49
    # from the object protocol: we will want to tweak the wire protocol separate
 
50
    # from the object model, and ideally we will be able to do that without
 
51
    # having a SmartServerRequestHandler subclass for each wire protocol, rather
 
52
    # just a Protocol subclass.
 
53
 
 
54
    # TODO: Better way of representing the body for commands that take it,
 
55
    # and allow it to be streamed into the server.
 
56
 
 
57
    def __init__(self, backing_transport):
 
58
        self._backing_transport = backing_transport
 
59
        self._body_bytes = ''
 
60
        self.response = None
 
61
        self.finished_reading = False
 
62
        self._command = None
 
63
 
 
64
    def accept_body(self, bytes):
 
65
        """Accept body data."""
 
66
 
 
67
        # TODO: This should be overriden for each command that desired body data
 
68
        # to handle the right format of that data, i.e. plain bytes, a bundle,
 
69
        # etc.  The deserialisation into that format should be done in the
 
70
        # Protocol object.
 
71
 
 
72
        # default fallback is to accumulate bytes.
 
73
        self._body_bytes += bytes
 
74
        
 
75
    def end_of_body(self):
 
76
        """No more body data will be received."""
 
77
        self._run_handler_code(self._command.do_body, (self._body_bytes,), {})
 
78
        # cannot read after this.
 
79
        self.finished_reading = True
 
80
 
 
81
    def dispatch_command(self, cmd, args):
 
82
        """Deprecated compatibility method.""" # XXX XXX
 
83
        command = version_one_commands.get(cmd)
 
84
        if command is None:
 
85
            raise errors.SmartProtocolError("bad request %r" % (cmd,))
 
86
        self._command = command(self._backing_transport)
 
87
        self._run_handler_code(self._command.do, args, {})
 
88
 
 
89
    def _run_handler_code(self, callable, args, kwargs):
 
90
        """Run some handler specific code 'callable'.
 
91
 
 
92
        If a result is returned, it is considered to be the commands response,
 
93
        and finished_reading is set true, and its assigned to self.response.
 
94
 
 
95
        Any exceptions caught are translated and a response object created
 
96
        from them.
 
97
        """
 
98
        result = self._call_converting_errors(callable, args, kwargs)
 
99
        if result is not None:
 
100
            self.response = result
 
101
            self.finished_reading = True
 
102
 
 
103
    def _call_converting_errors(self, callable, args, kwargs):
 
104
        """Call callable converting errors to Response objects."""
 
105
        # XXX: most of this error conversion is VFS-related, and thus ought to
 
106
        # be in SmartServerVFSRequestHandler somewhere.
 
107
        try:
 
108
            return callable(*args, **kwargs)
 
109
        except errors.NoSuchFile, e:
 
110
            return protocol.SmartServerResponse(('NoSuchFile', e.path))
 
111
        except errors.FileExists, e:
 
112
            return protocol.SmartServerResponse(('FileExists', e.path))
 
113
        except errors.DirectoryNotEmpty, e:
 
114
            return protocol.SmartServerResponse(('DirectoryNotEmpty', e.path))
 
115
        except errors.ShortReadvError, e:
 
116
            return protocol.SmartServerResponse(('ShortReadvError',
 
117
                e.path, str(e.offset), str(e.length), str(e.actual)))
 
118
        except UnicodeError, e:
 
119
            # If it is a DecodeError, than most likely we are starting
 
120
            # with a plain string
 
121
            str_or_unicode = e.object
 
122
            if isinstance(str_or_unicode, unicode):
 
123
                # XXX: UTF-8 might have \x01 (our seperator byte) in it.  We
 
124
                # should escape it somehow.
 
125
                val = 'u:' + str_or_unicode.encode('utf-8')
 
126
            else:
 
127
                val = 's:' + str_or_unicode.encode('base64')
 
128
            # This handles UnicodeEncodeError or UnicodeDecodeError
 
129
            return protocol.SmartServerResponse((e.__class__.__name__,
 
130
                    e.encoding, val, str(e.start), str(e.end), e.reason))
 
131
        except errors.TransportNotPossible, e:
 
132
            if e.msg == "readonly transport":
 
133
                return protocol.SmartServerResponse(('ReadOnlyError', ))
 
134
            else:
 
135
                raise
 
136
 
 
137
 
 
138
class HelloRequest(SmartServerRequest):
 
139
    """Answer a version request with my version."""
 
140
 
 
141
    method = 'hello'
 
142
 
 
143
    def do(self):
 
144
        return protocol.SmartServerResponse(('ok', '1'))
 
145
 
 
146
 
 
147
class GetBundleRequest(SmartServerRequest):
 
148
 
 
149
    method = 'get_bundle'
 
150
 
 
151
    def do(self, path, revision_id):
 
152
        # open transport relative to our base
 
153
        t = self._backing_transport.clone(path)
 
154
        control, extra_path = bzrdir.BzrDir.open_containing_from_transport(t)
 
155
        repo = control.open_repository()
 
156
        tmpf = tempfile.TemporaryFile()
 
157
        base_revision = revision.NULL_REVISION
 
158
        write_bundle(repo, revision_id, base_revision, tmpf)
 
159
        tmpf.seek(0)
 
160
        return protocol.SmartServerResponse((), tmpf.read())
 
161
 
 
162
 
 
163
# This is extended by bzrlib/transport/smart/vfs.py
 
164
version_one_commands = {
 
165
    HelloRequest.method: HelloRequest,
 
166
    GetBundleRequest.method: GetBundleRequest,
 
167
}
 
168
 
 
169