/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2400.1.5 by Andrew Bennetts
Add some missing docstrings and copyright boilerplate.
1
# Copyright (C) 2006, 2007 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
"""Basic server-side logic for dealing with requests."""
18
2400.1.3 by Andrew Bennetts
Split smart transport code into several separate modules.
19
20
import tempfile
21
22
from bzrlib import (
23
    bzrdir,
24
    errors,
25
    revision
26
    )
27
from bzrlib.bundle.serializer import write_bundle
28
29
30
class SmartServerResponse(object):
31
    """Response generated by SmartServerRequestHandler."""
32
33
    def __init__(self, args, body=None):
34
        self.args = args
35
        self.body = body
36
37
# XXX: TODO: Create a SmartServerRequestHandler which will take the responsibility
38
# for delivering the data for a request. This could be done with as the
39
# StreamServer, though that would create conflation between request and response
40
# which may be undesirable.
41
42
class SmartServerRequestHandler(object):
43
    """Protocol logic for smart server.
44
    
45
    This doesn't handle serialization at all, it just processes requests and
46
    creates responses.
47
    """
48
49
    # IMPORTANT FOR IMPLEMENTORS: It is important that SmartServerRequestHandler
50
    # not contain encoding or decoding logic to allow the wire protocol to vary
51
    # from the object protocol: we will want to tweak the wire protocol separate
52
    # from the object model, and ideally we will be able to do that without
53
    # having a SmartServerRequestHandler subclass for each wire protocol, rather
54
    # just a Protocol subclass.
55
56
    # TODO: Better way of representing the body for commands that take it,
57
    # and allow it to be streamed into the server.
58
    
59
    def __init__(self, backing_transport):
60
        self._backing_transport = backing_transport
61
        self._converted_command = False
62
        self.finished_reading = False
63
        self._body_bytes = ''
64
        self.response = None
65
66
    def accept_body(self, bytes):
67
        """Accept body data.
68
69
        This should be overriden for each command that desired body data to
70
        handle the right format of that data. I.e. plain bytes, a bundle etc.
71
72
        The deserialisation into that format should be done in the Protocol
73
        object. Set self.desired_body_format to the format your method will
74
        handle.
75
        """
76
        # default fallback is to accumulate bytes.
77
        self._body_bytes += bytes
78
        
79
    def _end_of_body_handler(self):
80
        """An unimplemented end of body handler."""
81
        raise NotImplementedError(self._end_of_body_handler)
82
        
83
    def do_hello(self):
84
        """Answer a version request with my version."""
85
        return SmartServerResponse(('ok', '1'))
86
87
    def do_has(self, relpath):
88
        r = self._backing_transport.has(relpath) and 'yes' or 'no'
89
        return SmartServerResponse((r,))
90
91
    def do_get(self, relpath):
92
        backing_bytes = self._backing_transport.get_bytes(relpath)
93
        return SmartServerResponse(('ok',), backing_bytes)
94
95
    def _deserialise_optional_mode(self, mode):
96
        # XXX: FIXME this should be on the protocol object.
97
        if mode == '':
98
            return None
99
        else:
100
            return int(mode)
101
102
    def do_append(self, relpath, mode):
103
        self._converted_command = True
104
        self._relpath = relpath
105
        self._mode = self._deserialise_optional_mode(mode)
106
        self._end_of_body_handler = self._handle_do_append_end
107
    
108
    def _handle_do_append_end(self):
109
        old_length = self._backing_transport.append_bytes(
110
            self._relpath, self._body_bytes, self._mode)
111
        self.response = SmartServerResponse(('appended', '%d' % old_length))
112
113
    def do_delete(self, relpath):
114
        self._backing_transport.delete(relpath)
115
116
    def do_iter_files_recursive(self, relpath):
117
        transport = self._backing_transport.clone(relpath)
118
        filenames = transport.iter_files_recursive()
119
        return SmartServerResponse(('names',) + tuple(filenames))
120
121
    def do_list_dir(self, relpath):
122
        filenames = self._backing_transport.list_dir(relpath)
123
        return SmartServerResponse(('names',) + tuple(filenames))
124
125
    def do_mkdir(self, relpath, mode):
126
        self._backing_transport.mkdir(relpath,
127
                                      self._deserialise_optional_mode(mode))
128
129
    def do_move(self, rel_from, rel_to):
130
        self._backing_transport.move(rel_from, rel_to)
131
132
    def do_put(self, relpath, mode):
133
        self._converted_command = True
134
        self._relpath = relpath
135
        self._mode = self._deserialise_optional_mode(mode)
136
        self._end_of_body_handler = self._handle_do_put
137
138
    def _handle_do_put(self):
139
        self._backing_transport.put_bytes(self._relpath,
140
                self._body_bytes, self._mode)
141
        self.response = SmartServerResponse(('ok',))
142
143
    def _deserialise_offsets(self, text):
144
        # XXX: FIXME this should be on the protocol object.
145
        offsets = []
146
        for line in text.split('\n'):
147
            if not line:
148
                continue
149
            start, length = line.split(',')
150
            offsets.append((int(start), int(length)))
151
        return offsets
152
153
    def do_put_non_atomic(self, relpath, mode, create_parent, dir_mode):
154
        self._converted_command = True
155
        self._end_of_body_handler = self._handle_put_non_atomic
156
        self._relpath = relpath
157
        self._dir_mode = self._deserialise_optional_mode(dir_mode)
158
        self._mode = self._deserialise_optional_mode(mode)
159
        # a boolean would be nicer XXX
160
        self._create_parent = (create_parent == 'T')
161
162
    def _handle_put_non_atomic(self):
163
        self._backing_transport.put_bytes_non_atomic(self._relpath,
164
                self._body_bytes,
165
                mode=self._mode,
166
                create_parent_dir=self._create_parent,
167
                dir_mode=self._dir_mode)
168
        self.response = SmartServerResponse(('ok',))
169
170
    def do_readv(self, relpath):
171
        self._converted_command = True
172
        self._end_of_body_handler = self._handle_readv_offsets
173
        self._relpath = relpath
174
175
    def end_of_body(self):
176
        """No more body data will be received."""
177
        self._run_handler_code(self._end_of_body_handler, (), {})
178
        # cannot read after this.
179
        self.finished_reading = True
180
181
    def _handle_readv_offsets(self):
182
        """accept offsets for a readv request."""
183
        offsets = self._deserialise_offsets(self._body_bytes)
184
        backing_bytes = ''.join(bytes for offset, bytes in
185
            self._backing_transport.readv(self._relpath, offsets))
186
        self.response = SmartServerResponse(('readv',), backing_bytes)
187
        
188
    def do_rename(self, rel_from, rel_to):
189
        self._backing_transport.rename(rel_from, rel_to)
190
191
    def do_rmdir(self, relpath):
192
        self._backing_transport.rmdir(relpath)
193
194
    def do_stat(self, relpath):
195
        stat = self._backing_transport.stat(relpath)
196
        return SmartServerResponse(('stat', str(stat.st_size), oct(stat.st_mode)))
197
        
198
    def do_get_bundle(self, path, revision_id):
199
        # open transport relative to our base
200
        t = self._backing_transport.clone(path)
201
        control, extra_path = bzrdir.BzrDir.open_containing_from_transport(t)
202
        repo = control.open_repository()
203
        tmpf = tempfile.TemporaryFile()
204
        base_revision = revision.NULL_REVISION
205
        write_bundle(repo, revision_id, base_revision, tmpf)
206
        tmpf.seek(0)
207
        return SmartServerResponse((), tmpf.read())
208
209
    def dispatch_command(self, cmd, args):
210
        """Deprecated compatibility method.""" # XXX XXX
211
        func = getattr(self, 'do_' + cmd, None)
212
        if func is None:
213
            raise errors.SmartProtocolError("bad request %r" % (cmd,))
214
        self._run_handler_code(func, args, {})
215
216
    def _run_handler_code(self, callable, args, kwargs):
217
        """Run some handler specific code 'callable'.
218
219
        If a result is returned, it is considered to be the commands response,
220
        and finished_reading is set true, and its assigned to self.response.
221
222
        Any exceptions caught are translated and a response object created
223
        from them.
224
        """
225
        result = self._call_converting_errors(callable, args, kwargs)
226
        if result is not None:
227
            self.response = result
228
            self.finished_reading = True
229
        # handle unconverted commands
230
        if not self._converted_command:
231
            self.finished_reading = True
232
            if result is None:
233
                self.response = SmartServerResponse(('ok',))
234
235
    def _call_converting_errors(self, callable, args, kwargs):
236
        """Call callable converting errors to Response objects."""
237
        try:
238
            return callable(*args, **kwargs)
239
        except errors.NoSuchFile, e:
240
            return SmartServerResponse(('NoSuchFile', e.path))
241
        except errors.FileExists, e:
242
            return SmartServerResponse(('FileExists', e.path))
243
        except errors.DirectoryNotEmpty, e:
244
            return SmartServerResponse(('DirectoryNotEmpty', e.path))
245
        except errors.ShortReadvError, e:
246
            return SmartServerResponse(('ShortReadvError',
247
                e.path, str(e.offset), str(e.length), str(e.actual)))
248
        except UnicodeError, e:
249
            # If it is a DecodeError, than most likely we are starting
250
            # with a plain string
251
            str_or_unicode = e.object
252
            if isinstance(str_or_unicode, unicode):
253
                # XXX: UTF-8 might have \x01 (our seperator byte) in it.  We
254
                # should escape it somehow.
255
                val = 'u:' + str_or_unicode.encode('utf-8')
256
            else:
257
                val = 's:' + str_or_unicode.encode('base64')
258
            # This handles UnicodeEncodeError or UnicodeDecodeError
259
            return SmartServerResponse((e.__class__.__name__,
260
                    e.encoding, val, str(e.start), str(e.end), e.reason))
261
        except errors.TransportNotPossible, e:
262
            if e.msg == "readonly transport":
263
                return SmartServerResponse(('ReadOnlyError', ))
264
            else:
265
                raise
266
267