/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/smart/request.py

  • Committer: Andrew Bennetts
  • Date: 2007-04-10 02:09:14 UTC
  • mto: This revision was merged to the branch mainline in revision 2402.
  • Revision ID: andrew.bennetts@canonical.com-20070410020914-rjhtq6bfcbrj2vjs
Tidy up accidental changes.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
 
 
2
import tempfile
 
3
 
 
4
from bzrlib import (
 
5
    bzrdir,
 
6
    errors,
 
7
    revision
 
8
    )
 
9
from bzrlib.bundle.serializer import write_bundle
 
10
 
 
11
 
 
12
class SmartServerResponse(object):
 
13
    """Response generated by SmartServerRequestHandler."""
 
14
 
 
15
    def __init__(self, args, body=None):
 
16
        self.args = args
 
17
        self.body = body
 
18
 
 
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.
 
23
 
 
24
class SmartServerRequestHandler(object):
 
25
    """Protocol logic for smart server.
 
26
    
 
27
    This doesn't handle serialization at all, it just processes requests and
 
28
    creates responses.
 
29
    """
 
30
 
 
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.
 
37
 
 
38
    # TODO: Better way of representing the body for commands that take it,
 
39
    # and allow it to be streamed into the server.
 
40
    
 
41
    def __init__(self, backing_transport):
 
42
        self._backing_transport = backing_transport
 
43
        self._converted_command = False
 
44
        self.finished_reading = False
 
45
        self._body_bytes = ''
 
46
        self.response = None
 
47
 
 
48
    def accept_body(self, bytes):
 
49
        """Accept body data.
 
50
 
 
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.
 
53
 
 
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
 
56
        handle.
 
57
        """
 
58
        # default fallback is to accumulate bytes.
 
59
        self._body_bytes += bytes
 
60
        
 
61
    def _end_of_body_handler(self):
 
62
        """An unimplemented end of body handler."""
 
63
        raise NotImplementedError(self._end_of_body_handler)
 
64
        
 
65
    def do_hello(self):
 
66
        """Answer a version request with my version."""
 
67
        return SmartServerResponse(('ok', '1'))
 
68
 
 
69
    def do_has(self, relpath):
 
70
        r = self._backing_transport.has(relpath) and 'yes' or 'no'
 
71
        return SmartServerResponse((r,))
 
72
 
 
73
    def do_get(self, relpath):
 
74
        backing_bytes = self._backing_transport.get_bytes(relpath)
 
75
        return SmartServerResponse(('ok',), backing_bytes)
 
76
 
 
77
    def _deserialise_optional_mode(self, mode):
 
78
        # XXX: FIXME this should be on the protocol object.
 
79
        if mode == '':
 
80
            return None
 
81
        else:
 
82
            return int(mode)
 
83
 
 
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
 
89
    
 
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))
 
94
 
 
95
    def do_delete(self, relpath):
 
96
        self._backing_transport.delete(relpath)
 
97
 
 
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))
 
102
 
 
103
    def do_list_dir(self, relpath):
 
104
        filenames = self._backing_transport.list_dir(relpath)
 
105
        return SmartServerResponse(('names',) + tuple(filenames))
 
106
 
 
107
    def do_mkdir(self, relpath, mode):
 
108
        self._backing_transport.mkdir(relpath,
 
109
                                      self._deserialise_optional_mode(mode))
 
110
 
 
111
    def do_move(self, rel_from, rel_to):
 
112
        self._backing_transport.move(rel_from, rel_to)
 
113
 
 
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
 
119
 
 
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',))
 
124
 
 
125
    def _deserialise_offsets(self, text):
 
126
        # XXX: FIXME this should be on the protocol object.
 
127
        offsets = []
 
128
        for line in text.split('\n'):
 
129
            if not line:
 
130
                continue
 
131
            start, length = line.split(',')
 
132
            offsets.append((int(start), int(length)))
 
133
        return offsets
 
134
 
 
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')
 
143
 
 
144
    def _handle_put_non_atomic(self):
 
145
        self._backing_transport.put_bytes_non_atomic(self._relpath,
 
146
                self._body_bytes,
 
147
                mode=self._mode,
 
148
                create_parent_dir=self._create_parent,
 
149
                dir_mode=self._dir_mode)
 
150
        self.response = SmartServerResponse(('ok',))
 
151
 
 
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
 
156
 
 
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
 
162
 
 
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)
 
169
        
 
170
    def do_rename(self, rel_from, rel_to):
 
171
        self._backing_transport.rename(rel_from, rel_to)
 
172
 
 
173
    def do_rmdir(self, relpath):
 
174
        self._backing_transport.rmdir(relpath)
 
175
 
 
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)))
 
179
        
 
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)
 
188
        tmpf.seek(0)
 
189
        return SmartServerResponse((), tmpf.read())
 
190
 
 
191
    def dispatch_command(self, cmd, args):
 
192
        """Deprecated compatibility method.""" # XXX XXX
 
193
        func = getattr(self, 'do_' + cmd, None)
 
194
        if func is None:
 
195
            raise errors.SmartProtocolError("bad request %r" % (cmd,))
 
196
        self._run_handler_code(func, args, {})
 
197
 
 
198
    def _run_handler_code(self, callable, args, kwargs):
 
199
        """Run some handler specific code 'callable'.
 
200
 
 
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.
 
203
 
 
204
        Any exceptions caught are translated and a response object created
 
205
        from them.
 
206
        """
 
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
 
214
            if result is None:
 
215
                self.response = SmartServerResponse(('ok',))
 
216
 
 
217
    def _call_converting_errors(self, callable, args, kwargs):
 
218
        """Call callable converting errors to Response objects."""
 
219
        try:
 
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')
 
238
            else:
 
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', ))
 
246
            else:
 
247
                raise
 
248
 
 
249