~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/smart/request.py

Use the Command pattern for smart server request handling

Show diffs side-by-side

added added

removed removed

Lines of Context:
22
22
from bzrlib import (
23
23
    bzrdir,
24
24
    errors,
25
 
    revision
 
25
    registry,
 
26
    revision,
26
27
    )
27
28
from bzrlib.bundle.serializer import write_bundle
28
29
 
29
30
 
 
31
class SmartServerRequest(object):
 
32
    """Base class for request handlers."""
 
33
 
 
34
    def __init__(self, backing_transport):
 
35
        """Constructor.
 
36
 
 
37
        :param backing_transport: the base transport to be used when performing
 
38
            this request.
 
39
        """
 
40
        self._backing_transport = backing_transport
 
41
 
 
42
    def _check_enabled(self):
 
43
        """Raises DisabledMethod if this method is disabled."""
 
44
        pass
 
45
 
 
46
    def do(self, *args):
 
47
        """Mandatory extension point for SmartServerRequest subclasses.
 
48
        
 
49
        Subclasses must implement this.
 
50
        
 
51
        This should return a SmartServerResponse if this command expects to
 
52
        receive no body.
 
53
        """
 
54
        raise NotImplementedError(self.do)
 
55
 
 
56
    def execute(self, *args):
 
57
        """Public entry point to execute this request.
 
58
 
 
59
        It will return a SmartServerResponse if the command does not expect a
 
60
        body.
 
61
 
 
62
        :param *args: the arguments of the request.
 
63
        """
 
64
        self._check_enabled()
 
65
        return self.do(*args)
 
66
 
 
67
    def do_body(self, body_bytes):
 
68
        """Called if the client sends a body with the request.
 
69
        
 
70
        Must return a SmartServerResponse.
 
71
        """
 
72
        # TODO: if a client erroneously sends a request that shouldn't have a
 
73
        # body, what to do?  Probably SmartServerRequestHandler should catch
 
74
        # this NotImplementedError and translate it into a 'bad request' error
 
75
        # to send to the client.
 
76
        raise NotImplementedError(self.do_body)
 
77
 
 
78
 
30
79
class SmartServerResponse(object):
31
80
    """Response generated by SmartServerRequestHandler."""
32
81
 
34
83
        self.args = args
35
84
        self.body = body
36
85
 
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.
 
86
    def __eq__(self, other):
 
87
        if other is None:
 
88
            return False
 
89
        return other.args == self.args and other.body == self.body
 
90
 
 
91
    def __repr__(self):
 
92
        return "<SmartServerResponse args=%r body=%r>" % (self.args, self.body)
 
93
 
41
94
 
42
95
class SmartServerRequestHandler(object):
43
96
    """Protocol logic for smart server.
55
108
 
56
109
    # TODO: Better way of representing the body for commands that take it,
57
110
    # and allow it to be streamed into the server.
58
 
    
59
 
    def __init__(self, backing_transport):
 
111
 
 
112
    def __init__(self, backing_transport, commands):
 
113
        """Constructor.
 
114
 
 
115
        :param backing_transport: a Transport to handle requests for.
 
116
        :param commands: a registry mapping command names to SmartServerRequest
 
117
            subclasses. e.g. bzrlib.transport.smart.vfs.vfs_commands.
 
118
        """
60
119
        self._backing_transport = backing_transport
61
 
        self._converted_command = False
62
 
        self.finished_reading = False
 
120
        self._commands = commands
63
121
        self._body_bytes = ''
64
122
        self.response = None
 
123
        self.finished_reading = False
 
124
        self._command = None
65
125
 
66
126
    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
 
        """
 
127
        """Accept body data."""
 
128
 
 
129
        # TODO: This should be overriden for each command that desired body data
 
130
        # to handle the right format of that data, i.e. plain bytes, a bundle,
 
131
        # etc.  The deserialisation into that format should be done in the
 
132
        # Protocol object.
 
133
 
76
134
        # default fallback is to accumulate bytes.
77
135
        self._body_bytes += bytes
78
136
        
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
137
    def end_of_body(self):
176
138
        """No more body data will be received."""
177
 
        self._run_handler_code(self._end_of_body_handler, (), {})
 
139
        self._run_handler_code(self._command.do_body, (self._body_bytes,), {})
178
140
        # cannot read after this.
179
141
        self.finished_reading = True
180
142
 
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
143
    def dispatch_command(self, cmd, args):
210
144
        """Deprecated compatibility method.""" # XXX XXX
211
 
        func = getattr(self, 'do_' + cmd, None)
212
 
        if func is None:
 
145
        try:
 
146
            command = self._commands.get(cmd)
 
147
        except LookupError:
213
148
            raise errors.SmartProtocolError("bad request %r" % (cmd,))
214
 
        self._run_handler_code(func, args, {})
 
149
        self._command = command(self._backing_transport)
 
150
        self._run_handler_code(self._command.execute, args, {})
215
151
 
216
152
    def _run_handler_code(self, callable, args, kwargs):
217
153
        """Run some handler specific code 'callable'.
223
159
        from them.
224
160
        """
225
161
        result = self._call_converting_errors(callable, args, kwargs)
 
162
 
226
163
        if result is not None:
227
164
            self.response = result
228
165
            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
166
 
235
167
    def _call_converting_errors(self, callable, args, kwargs):
236
168
        """Call callable converting errors to Response objects."""
 
169
        # XXX: most of this error conversion is VFS-related, and thus ought to
 
170
        # be in SmartServerVFSRequestHandler somewhere.
237
171
        try:
238
172
            return callable(*args, **kwargs)
239
173
        except errors.NoSuchFile, e:
265
199
                raise
266
200
 
267
201
 
 
202
class HelloRequest(SmartServerRequest):
 
203
    """Answer a version request with my version."""
 
204
 
 
205
    def do(self):
 
206
        return SmartServerResponse(('ok', '1'))
 
207
 
 
208
 
 
209
class GetBundleRequest(SmartServerRequest):
 
210
    """Get a bundle of from the null revision to the specified revision."""
 
211
 
 
212
    def do(self, path, revision_id):
 
213
        # open transport relative to our base
 
214
        t = self._backing_transport.clone(path)
 
215
        control, extra_path = bzrdir.BzrDir.open_containing_from_transport(t)
 
216
        repo = control.open_repository()
 
217
        tmpf = tempfile.TemporaryFile()
 
218
        base_revision = revision.NULL_REVISION
 
219
        write_bundle(repo, revision_id, base_revision, tmpf)
 
220
        tmpf.seek(0)
 
221
        return SmartServerResponse((), tmpf.read())
 
222
 
 
223
 
 
224
class SmartServerIsReadonly(SmartServerRequest):
 
225
    # XXX: this request method belongs somewhere else.
 
226
 
 
227
    def do(self):
 
228
        if self._backing_transport.is_readonly():
 
229
            answer = 'yes'
 
230
        else:
 
231
            answer = 'no'
 
232
        return SmartServerResponse((answer,))
 
233
 
 
234
 
 
235
request_handlers = registry.Registry()
 
236
request_handlers.register_lazy(
 
237
    'append', 'bzrlib.smart.vfs', 'AppendRequest')
 
238
request_handlers.register_lazy(
 
239
    'delete', 'bzrlib.smart.vfs', 'DeleteRequest')
 
240
request_handlers.register_lazy(
 
241
    'get', 'bzrlib.smart.vfs', 'GetRequest')
 
242
request_handlers.register_lazy(
 
243
    'get_bundle', 'bzrlib.smart.request', 'GetBundleRequest')
 
244
request_handlers.register_lazy(
 
245
    'has', 'bzrlib.smart.vfs', 'HasRequest')
 
246
request_handlers.register_lazy(
 
247
    'hello', 'bzrlib.smart.request', 'HelloRequest')
 
248
request_handlers.register_lazy(
 
249
    'iter_files_recursive', 'bzrlib.smart.vfs', 'IterFilesRecursiveRequest')
 
250
request_handlers.register_lazy(
 
251
    'list_dir', 'bzrlib.smart.vfs', 'ListDirRequest')
 
252
request_handlers.register_lazy(
 
253
    'mkdir', 'bzrlib.smart.vfs', 'MkdirRequest')
 
254
request_handlers.register_lazy(
 
255
    'move', 'bzrlib.smart.vfs', 'MoveRequest')
 
256
request_handlers.register_lazy(
 
257
    'put', 'bzrlib.smart.vfs', 'PutRequest')
 
258
request_handlers.register_lazy(
 
259
    'put_non_atomic', 'bzrlib.smart.vfs', 'PutNonAtomicRequest')
 
260
request_handlers.register_lazy(
 
261
    'readv', 'bzrlib.smart.vfs', 'ReadvRequest')
 
262
request_handlers.register_lazy(
 
263
    'rename', 'bzrlib.smart.vfs', 'RenameRequest')
 
264
request_handlers.register_lazy(
 
265
    'rmdir', 'bzrlib.smart.vfs', 'RmdirRequest')
 
266
request_handlers.register_lazy(
 
267
    'stat', 'bzrlib.smart.vfs', 'StatRequest')