/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
3224.5.8 by Andrew Bennetts
Fix failing tests.
1
# Copyright (C) 2006, 2007 Canonical Ltd
2018.5.4 by Andrew Bennetts
Split smart server VFS logic out into a new file, and start using the command pattern in the SmartServerRequestHandler.
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
3195.3.4 by Andrew Bennetts
Make the general request handler dispatch version 3 events to the specific request handler (i.e. to the SmartServerRequest instance).
17
"""Basic server-side logic for dealing with requests.
18
19
**XXX**:
20
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.
24
25
The request_handlers registry tracks SmartServerRequest classes (rather than
26
SmartServerRequestHandler).
27
"""
2018.5.19 by Andrew Bennetts
Add docstrings to all the new modules, and a few other places.
28
2018.5.6 by Andrew Bennetts
Tidy ups, and turn do_hello and do_get_bundle into command objects.
29
import tempfile
30
2402.1.2 by Andrew Bennetts
Deal with review comments.
31
from bzrlib import (
32
    bzrdir,
33
    errors,
34
    registry,
35
    revision,
2692.1.1 by Andrew Bennetts
Add translate_client_path method to SmartServerRequest.
36
    urlutils,
2402.1.2 by Andrew Bennetts
Deal with review comments.
37
    )
3224.5.6 by Andrew Bennetts
Don't import bzrlib.bundle in bzrlib.smart.request until it's needed.
38
from bzrlib.lazy_import import lazy_import
39
lazy_import(globals(), """
40
from bzrlib.bundle import serializer
41
""")
2018.5.6 by Andrew Bennetts
Tidy ups, and turn do_hello and do_get_bundle into command objects.
42
2018.5.4 by Andrew Bennetts
Split smart server VFS logic out into a new file, and start using the command pattern in the SmartServerRequestHandler.
43
44
class SmartServerRequest(object):
2692.1.10 by Andrew Bennetts
More docstring polish
45
    """Base class for request handlers.
46
    
47
    To define a new request, subclass this class and override the `do` method
48
    (and if appropriate, `do_body` as well).  Request implementors should take
49
    care to call `translate_client_path` and `transport_from_client_path` as
50
    appropriate when dealing with paths received from the client.
51
    """
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
52
    # XXX: rename this class to BaseSmartServerRequestHandler ?  A request
53
    # *handler* is a different concept to the request.
2018.5.4 by Andrew Bennetts
Split smart server VFS logic out into a new file, and start using the command pattern in the SmartServerRequestHandler.
54
2692.1.1 by Andrew Bennetts
Add translate_client_path method to SmartServerRequest.
55
    def __init__(self, backing_transport, root_client_path='/'):
2402.1.2 by Andrew Bennetts
Deal with review comments.
56
        """Constructor.
57
58
        :param backing_transport: the base transport to be used when performing
59
            this request.
2692.1.1 by Andrew Bennetts
Add translate_client_path method to SmartServerRequest.
60
        :param root_client_path: the client path that maps to the root of
2692.1.9 by Andrew Bennetts
Docstrings for translate_client_path and transport_from_client_path.
61
            backing_transport.  This is used to interpret relpaths received
62
            from the client.  Clients will not be able to refer to paths above
2692.1.16 by Andrew Bennetts
Improve comments.
63
            this root.  If root_client_path is None, then no translation will
64
            be performed on client paths.  Default is '/'.
2402.1.2 by Andrew Bennetts
Deal with review comments.
65
        """
2018.5.4 by Andrew Bennetts
Split smart server VFS logic out into a new file, and start using the command pattern in the SmartServerRequestHandler.
66
        self._backing_transport = backing_transport
2692.1.14 by Andrew Bennetts
All WSGI tests passing, and manual testing works too.
67
        if root_client_path is not None:
68
            if not root_client_path.startswith('/'):
69
                root_client_path = '/' + root_client_path
70
            if not root_client_path.endswith('/'):
71
                root_client_path += '/'
2692.1.1 by Andrew Bennetts
Add translate_client_path method to SmartServerRequest.
72
        self._root_client_path = root_client_path
2018.5.5 by Andrew Bennetts
Pass body_bytes directly to SmartServerRequest.do_body
73
2018.5.24 by Andrew Bennetts
Setting NO_SMART_VFS in environment will disable VFS methods in the smart server. (Robert Collins, John Arbash Meinel, Andrew Bennetts)
74
    def _check_enabled(self):
75
        """Raises DisabledMethod if this method is disabled."""
76
        pass
77
2018.5.19 by Andrew Bennetts
Add docstrings to all the new modules, and a few other places.
78
    def do(self, *args):
2018.5.24 by Andrew Bennetts
Setting NO_SMART_VFS in environment will disable VFS methods in the smart server. (Robert Collins, John Arbash Meinel, Andrew Bennetts)
79
        """Mandatory extension point for SmartServerRequest subclasses.
80
        
81
        Subclasses must implement this.
2018.5.19 by Andrew Bennetts
Add docstrings to all the new modules, and a few other places.
82
        
83
        This should return a SmartServerResponse if this command expects to
84
        receive no body.
85
        """
2018.5.5 by Andrew Bennetts
Pass body_bytes directly to SmartServerRequest.do_body
86
        raise NotImplementedError(self.do)
87
2018.5.24 by Andrew Bennetts
Setting NO_SMART_VFS in environment will disable VFS methods in the smart server. (Robert Collins, John Arbash Meinel, Andrew Bennetts)
88
    def execute(self, *args):
89
        """Public entry point to execute this request.
90
91
        It will return a SmartServerResponse if the command does not expect a
92
        body.
93
94
        :param *args: the arguments of the request.
95
        """
96
        self._check_enabled()
97
        return self.do(*args)
98
2018.5.5 by Andrew Bennetts
Pass body_bytes directly to SmartServerRequest.do_body
99
    def do_body(self, body_bytes):
2018.5.19 by Andrew Bennetts
Add docstrings to all the new modules, and a few other places.
100
        """Called if the client sends a body with the request.
3184.1.10 by Robert Collins
Change the smart server verb for Repository.stream_revisions_chunked to use SearchResults as the request mechanism for downloads.
101
102
        The do() method is still called, and must have returned None.
2018.5.19 by Andrew Bennetts
Add docstrings to all the new modules, and a few other places.
103
        
104
        Must return a SmartServerResponse.
105
        """
2018.5.4 by Andrew Bennetts
Split smart server VFS logic out into a new file, and start using the command pattern in the SmartServerRequestHandler.
106
        raise NotImplementedError(self.do_body)
107
3195.3.4 by Andrew Bennetts
Make the general request handler dispatch version 3 events to the specific request handler (i.e. to the SmartServerRequest instance).
108
    def do_chunk(self, chunk_bytes):
109
        """Called with each body chunk if the request has a streamed body.
110
111
        The do() method is still called, and must have returned None.
112
        """
113
        raise NotImplementedError(self.do_chunk)
114
115
    def do_end(self):
116
        """Called when the end of the request has been received."""
117
        pass
2692.1.1 by Andrew Bennetts
Add translate_client_path method to SmartServerRequest.
118
    
119
    def translate_client_path(self, client_path):
2692.1.9 by Andrew Bennetts
Docstrings for translate_client_path and transport_from_client_path.
120
        """Translate a path received from a network client into a local
121
        relpath.
122
123
        All paths received from the client *must* be translated.
124
2692.1.14 by Andrew Bennetts
All WSGI tests passing, and manual testing works too.
125
        :param client_path: the path from the client.
2692.1.9 by Andrew Bennetts
Docstrings for translate_client_path and transport_from_client_path.
126
        :returns: a relpath that may be used with self._backing_transport
2692.1.14 by Andrew Bennetts
All WSGI tests passing, and manual testing works too.
127
            (unlike the untranslated client_path, which must not be used with
128
            the backing transport).
2692.1.9 by Andrew Bennetts
Docstrings for translate_client_path and transport_from_client_path.
129
        """
2692.1.14 by Andrew Bennetts
All WSGI tests passing, and manual testing works too.
130
        if self._root_client_path is None:
131
            # no translation necessary!
132
            return client_path
2692.1.1 by Andrew Bennetts
Add translate_client_path method to SmartServerRequest.
133
        if not client_path.startswith('/'):
134
            client_path = '/' + client_path
135
        if client_path.startswith(self._root_client_path):
136
            path = client_path[len(self._root_client_path):]
137
            relpath = urlutils.joinpath('/', path)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
138
            if not relpath.startswith('/'):
139
                raise ValueError(relpath)
2692.1.1 by Andrew Bennetts
Add translate_client_path method to SmartServerRequest.
140
            return '.' + relpath
141
        else:
142
            raise errors.PathNotChild(client_path, self._root_client_path)
143
144
    def transport_from_client_path(self, client_path):
2692.1.9 by Andrew Bennetts
Docstrings for translate_client_path and transport_from_client_path.
145
        """Get a backing transport corresponding to the location referred to by
146
        a network client.
147
148
        :seealso: translate_client_path
149
        :returns: a transport cloned from self._backing_transport
150
        """
2692.1.1 by Andrew Bennetts
Add translate_client_path method to SmartServerRequest.
151
        relpath = self.translate_client_path(client_path)
2692.1.16 by Andrew Bennetts
Improve comments.
152
        return self._backing_transport.clone(relpath)
3195.3.4 by Andrew Bennetts
Make the general request handler dispatch version 3 events to the specific request handler (i.e. to the SmartServerRequest instance).
153
2018.5.6 by Andrew Bennetts
Tidy ups, and turn do_hello and do_get_bundle into command objects.
154
2018.5.16 by Andrew Bennetts
Move SmartServerResponse to smart/request.py, untangling more import dependencies.
155
class SmartServerResponse(object):
2432.4.5 by Robert Collins
Make using SuccessfulSmartServerResponse and FailedSmartServerResponse mandatory rather than optional in smart server logic.
156
    """A response to a client request.
157
    
158
    This base class should not be used. Instead use
159
    SuccessfulSmartServerResponse and FailedSmartServerResponse as appropriate.
160
    """
2018.5.16 by Andrew Bennetts
Move SmartServerResponse to smart/request.py, untangling more import dependencies.
161
2748.4.2 by Andrew Bennetts
Add protocol (version two) support for streaming bodies (using chunking) in responses.
162
    def __init__(self, args, body=None, body_stream=None):
163
        """Constructor.
164
165
        :param args: tuple of response arguments.
166
        :param body: string of a response body.
167
        :param body_stream: iterable of bytestrings to be streamed to the
168
            client.
169
        """
2018.5.16 by Andrew Bennetts
Move SmartServerResponse to smart/request.py, untangling more import dependencies.
170
        self.args = args
2748.4.2 by Andrew Bennetts
Add protocol (version two) support for streaming bodies (using chunking) in responses.
171
        if body is not None and body_stream is not None:
172
            raise errors.BzrError(
173
                "'body' and 'body_stream' are mutually exclusive.")
2018.5.16 by Andrew Bennetts
Move SmartServerResponse to smart/request.py, untangling more import dependencies.
174
        self.body = body
2748.4.2 by Andrew Bennetts
Add protocol (version two) support for streaming bodies (using chunking) in responses.
175
        self.body_stream = body_stream
2018.5.16 by Andrew Bennetts
Move SmartServerResponse to smart/request.py, untangling more import dependencies.
176
2402.1.1 by Andrew Bennetts
Use the Command pattern for handling smart server commands.
177
    def __eq__(self, other):
178
        if other is None:
179
            return False
2748.4.2 by Andrew Bennetts
Add protocol (version two) support for streaming bodies (using chunking) in responses.
180
        return (other.args == self.args and
181
                other.body == self.body and
182
                other.body_stream is self.body_stream)
2402.1.1 by Andrew Bennetts
Use the Command pattern for handling smart server commands.
183
184
    def __repr__(self):
2692.1.1 by Andrew Bennetts
Add translate_client_path method to SmartServerRequest.
185
        status = {True: 'OK', False: 'ERR'}[self.is_successful()]
186
        return "<SmartServerResponse status=%s args=%r body=%r>" % (status,
2432.4.5 by Robert Collins
Make using SuccessfulSmartServerResponse and FailedSmartServerResponse mandatory rather than optional in smart server logic.
187
            self.args, self.body)
2402.1.1 by Andrew Bennetts
Use the Command pattern for handling smart server commands.
188
2018.5.16 by Andrew Bennetts
Move SmartServerResponse to smart/request.py, untangling more import dependencies.
189
2432.4.2 by Robert Collins
Add FailedSmartServerResponse.
190
class FailedSmartServerResponse(SmartServerResponse):
191
    """A SmartServerResponse for a request which failed."""
192
193
    def is_successful(self):
194
        """FailedSmartServerResponse are not successful."""
195
        return False
196
197
2432.4.1 by Robert Collins
Add SuccessfulSmartServerResponse.
198
class SuccessfulSmartServerResponse(SmartServerResponse):
199
    """A SmartServerResponse for a successfully completed request."""
200
201
    def is_successful(self):
202
        """SuccessfulSmartServerResponse are successful."""
203
        return True
204
2018.5.16 by Andrew Bennetts
Move SmartServerResponse to smart/request.py, untangling more import dependencies.
205
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
206
class SmartServerRequestHandler(object):
207
    """Protocol logic for smart server.
208
    
209
    This doesn't handle serialization at all, it just processes requests and
210
    creates responses.
211
    """
212
213
    # IMPORTANT FOR IMPLEMENTORS: It is important that SmartServerRequestHandler
214
    # not contain encoding or decoding logic to allow the wire protocol to vary
215
    # from the object protocol: we will want to tweak the wire protocol separate
216
    # from the object model, and ideally we will be able to do that without
217
    # having a SmartServerRequestHandler subclass for each wire protocol, rather
218
    # just a Protocol subclass.
219
220
    # TODO: Better way of representing the body for commands that take it,
221
    # and allow it to be streamed into the server.
222
2692.1.1 by Andrew Bennetts
Add translate_client_path method to SmartServerRequest.
223
    def __init__(self, backing_transport, commands, root_client_path):
2018.5.17 by Andrew Bennetts
Paramaterise the commands handled by SmartServerRequestHandler.
224
        """Constructor.
225
226
        :param backing_transport: a Transport to handle requests for.
2018.5.23 by Andrew Bennetts
Use a Registry for smart server command handlers.
227
        :param commands: a registry mapping command names to SmartServerRequest
2018.5.17 by Andrew Bennetts
Paramaterise the commands handled by SmartServerRequestHandler.
228
            subclasses. e.g. bzrlib.transport.smart.vfs.vfs_commands.
229
        """
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
230
        self._backing_transport = backing_transport
2692.1.1 by Andrew Bennetts
Add translate_client_path method to SmartServerRequest.
231
        self._root_client_path = root_client_path
2018.5.17 by Andrew Bennetts
Paramaterise the commands handled by SmartServerRequestHandler.
232
        self._commands = commands
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
233
        self._body_bytes = ''
234
        self.response = None
235
        self.finished_reading = False
236
        self._command = None
237
238
    def accept_body(self, bytes):
239
        """Accept body data."""
240
241
        # TODO: This should be overriden for each command that desired body data
242
        # to handle the right format of that data, i.e. plain bytes, a bundle,
243
        # etc.  The deserialisation into that format should be done in the
244
        # Protocol object.
245
246
        # default fallback is to accumulate bytes.
247
        self._body_bytes += bytes
248
        
249
    def end_of_body(self):
250
        """No more body data will be received."""
251
        self._run_handler_code(self._command.do_body, (self._body_bytes,), {})
252
        # cannot read after this.
253
        self.finished_reading = True
254
255
    def dispatch_command(self, cmd, args):
256
        """Deprecated compatibility method.""" # XXX XXX
2018.5.23 by Andrew Bennetts
Use a Registry for smart server command handlers.
257
        try:
258
            command = self._commands.get(cmd)
259
        except LookupError:
3245.4.29 by Andrew Bennetts
Add/tidy some comments, remove dud test_errors_are_logged test, add explicit UnknownSmartMethod to v3.
260
            raise errors.UnknownSmartMethod(cmd)
2692.1.1 by Andrew Bennetts
Add translate_client_path method to SmartServerRequest.
261
        self._command = command(self._backing_transport, self._root_client_path)
2018.5.24 by Andrew Bennetts
Setting NO_SMART_VFS in environment will disable VFS methods in the smart server. (Robert Collins, John Arbash Meinel, Andrew Bennetts)
262
        self._run_handler_code(self._command.execute, args, {})
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
263
264
    def _run_handler_code(self, callable, args, kwargs):
265
        """Run some handler specific code 'callable'.
266
267
        If a result is returned, it is considered to be the commands response,
268
        and finished_reading is set true, and its assigned to self.response.
269
270
        Any exceptions caught are translated and a response object created
271
        from them.
272
        """
273
        result = self._call_converting_errors(callable, args, kwargs)
2018.5.19 by Andrew Bennetts
Add docstrings to all the new modules, and a few other places.
274
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
275
        if result is not None:
276
            self.response = result
277
            self.finished_reading = True
278
279
    def _call_converting_errors(self, callable, args, kwargs):
280
        """Call callable converting errors to Response objects."""
281
        # XXX: most of this error conversion is VFS-related, and thus ought to
282
        # be in SmartServerVFSRequestHandler somewhere.
283
        try:
284
            return callable(*args, **kwargs)
285
        except errors.NoSuchFile, e:
2432.4.5 by Robert Collins
Make using SuccessfulSmartServerResponse and FailedSmartServerResponse mandatory rather than optional in smart server logic.
286
            return FailedSmartServerResponse(('NoSuchFile', e.path))
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
287
        except errors.FileExists, e:
2432.4.5 by Robert Collins
Make using SuccessfulSmartServerResponse and FailedSmartServerResponse mandatory rather than optional in smart server logic.
288
            return FailedSmartServerResponse(('FileExists', e.path))
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
289
        except errors.DirectoryNotEmpty, e:
2432.4.5 by Robert Collins
Make using SuccessfulSmartServerResponse and FailedSmartServerResponse mandatory rather than optional in smart server logic.
290
            return FailedSmartServerResponse(('DirectoryNotEmpty', e.path))
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
291
        except errors.ShortReadvError, e:
2432.4.5 by Robert Collins
Make using SuccessfulSmartServerResponse and FailedSmartServerResponse mandatory rather than optional in smart server logic.
292
            return FailedSmartServerResponse(('ShortReadvError',
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
293
                e.path, str(e.offset), str(e.length), str(e.actual)))
294
        except UnicodeError, e:
295
            # If it is a DecodeError, than most likely we are starting
296
            # with a plain string
297
            str_or_unicode = e.object
298
            if isinstance(str_or_unicode, unicode):
299
                # XXX: UTF-8 might have \x01 (our seperator byte) in it.  We
300
                # should escape it somehow.
301
                val = 'u:' + str_or_unicode.encode('utf-8')
302
            else:
303
                val = 's:' + str_or_unicode.encode('base64')
304
            # This handles UnicodeEncodeError or UnicodeDecodeError
2432.4.5 by Robert Collins
Make using SuccessfulSmartServerResponse and FailedSmartServerResponse mandatory rather than optional in smart server logic.
305
            return FailedSmartServerResponse((e.__class__.__name__,
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
306
                    e.encoding, val, str(e.start), str(e.end), e.reason))
307
        except errors.TransportNotPossible, e:
308
            if e.msg == "readonly transport":
2432.4.5 by Robert Collins
Make using SuccessfulSmartServerResponse and FailedSmartServerResponse mandatory rather than optional in smart server logic.
309
                return FailedSmartServerResponse(('ReadOnlyError', ))
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
310
            else:
311
                raise
312
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
313
    def headers_received(self, headers):
3245.4.33 by Andrew Bennetts
Remove unused no_body_received method on SmartServerRequestHandler.
314
        # Just a no-op at the moment.
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
315
        pass
316
317
    def args_received(self, args):
3195.3.4 by Andrew Bennetts
Make the general request handler dispatch version 3 events to the specific request handler (i.e. to the SmartServerRequest instance).
318
        cmd = args[0]
319
        args = args[1:]
320
        try:
321
            command = self._commands.get(cmd)
322
        except LookupError:
3245.4.48 by Andrew Bennetts
raise UnknownSmartMethod from dispatch_command.
323
            raise errors.UnknownSmartMethod(cmd)
3195.3.4 by Andrew Bennetts
Make the general request handler dispatch version 3 events to the specific request handler (i.e. to the SmartServerRequest instance).
324
        self._command = command(self._backing_transport)
325
        self._run_handler_code(self._command.execute, args, {})
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
326
327
    def prefixed_body_received(self, body_bytes):
3195.3.4 by Andrew Bennetts
Make the general request handler dispatch version 3 events to the specific request handler (i.e. to the SmartServerRequest instance).
328
        """No more body data will be received."""
329
        self._run_handler_code(self._command.do_body, (body_bytes,), {})
330
        # cannot read after this.
331
        self.finished_reading = True
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
332
333
    def body_chunk_received(self, chunk_bytes):
3195.3.4 by Andrew Bennetts
Make the general request handler dispatch version 3 events to the specific request handler (i.e. to the SmartServerRequest instance).
334
        self._run_handler_code(self._command.do_chunk, (chunk_bytes,), {})
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
335
3195.3.4 by Andrew Bennetts
Make the general request handler dispatch version 3 events to the specific request handler (i.e. to the SmartServerRequest instance).
336
    def end_received(self):
337
        self._run_handler_code(self._command.do_end, (), {})
3195.3.2 by Andrew Bennetts
Checkpoint first rough cut of SmartServerRequestProtocolThree, this implementation reuses the _StatefulDecoder class. Plus some attempts to start tidying the smart protocol tests.
338
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
339
2018.5.6 by Andrew Bennetts
Tidy ups, and turn do_hello and do_get_bundle into command objects.
340
class HelloRequest(SmartServerRequest):
2432.2.6 by Andrew Bennetts
Improve HelloRequest's docstring.
341
    """Answer a version request with the highest protocol version this server
342
    supports.
343
    """
2018.5.6 by Andrew Bennetts
Tidy ups, and turn do_hello and do_get_bundle into command objects.
344
345
    def do(self):
3245.4.59 by Andrew Bennetts
Various tweaks in response to Martin's review.
346
        return SuccessfulSmartServerResponse(('ok', '2'))
2018.5.6 by Andrew Bennetts
Tidy ups, and turn do_hello and do_get_bundle into command objects.
347
348
349
class GetBundleRequest(SmartServerRequest):
2402.1.2 by Andrew Bennetts
Deal with review comments.
350
    """Get a bundle of from the null revision to the specified revision."""
2018.5.6 by Andrew Bennetts
Tidy ups, and turn do_hello and do_get_bundle into command objects.
351
352
    def do(self, path, revision_id):
353
        # open transport relative to our base
2692.1.7 by Andrew Bennetts
Translate path in GetBundleRequest too.
354
        t = self.transport_from_client_path(path)
2018.5.6 by Andrew Bennetts
Tidy ups, and turn do_hello and do_get_bundle into command objects.
355
        control, extra_path = bzrdir.BzrDir.open_containing_from_transport(t)
356
        repo = control.open_repository()
357
        tmpf = tempfile.TemporaryFile()
358
        base_revision = revision.NULL_REVISION
3224.5.6 by Andrew Bennetts
Don't import bzrlib.bundle in bzrlib.smart.request until it's needed.
359
        serializer.write_bundle(repo, revision_id, base_revision, tmpf)
2018.5.6 by Andrew Bennetts
Tidy ups, and turn do_hello and do_get_bundle into command objects.
360
        tmpf.seek(0)
2432.4.5 by Robert Collins
Make using SuccessfulSmartServerResponse and FailedSmartServerResponse mandatory rather than optional in smart server logic.
361
        return SuccessfulSmartServerResponse((), tmpf.read())
2018.5.6 by Andrew Bennetts
Tidy ups, and turn do_hello and do_get_bundle into command objects.
362
363
2018.5.95 by Andrew Bennetts
Add a Transport.is_readonly remote call, let {Branch,Repository}.lock_write remote call return UnlockableTransport, and miscellaneous test fixes.
364
class SmartServerIsReadonly(SmartServerRequest):
365
    # XXX: this request method belongs somewhere else.
366
367
    def do(self):
368
        if self._backing_transport.is_readonly():
369
            answer = 'yes'
370
        else:
371
            answer = 'no'
2432.4.5 by Robert Collins
Make using SuccessfulSmartServerResponse and FailedSmartServerResponse mandatory rather than optional in smart server logic.
372
        return SuccessfulSmartServerResponse((answer,))
2018.5.95 by Andrew Bennetts
Add a Transport.is_readonly remote call, let {Branch,Repository}.lock_write remote call return UnlockableTransport, and miscellaneous test fixes.
373
374
2018.5.23 by Andrew Bennetts
Use a Registry for smart server command handlers.
375
request_handlers = registry.Registry()
376
request_handlers.register_lazy(
377
    'append', 'bzrlib.smart.vfs', 'AppendRequest')
378
request_handlers.register_lazy(
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
379
    'Branch.get_config_file', 'bzrlib.smart.branch', 'SmartServerBranchGetConfigFile')
380
request_handlers.register_lazy(
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
381
    'Branch.last_revision_info', 'bzrlib.smart.branch', 'SmartServerBranchRequestLastRevisionInfo')
382
request_handlers.register_lazy(
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
383
    'Branch.lock_write', 'bzrlib.smart.branch', 'SmartServerBranchRequestLockWrite')
384
request_handlers.register_lazy(
2018.5.38 by Robert Collins
Implement RemoteBranch.revision_history().
385
    'Branch.revision_history', 'bzrlib.smart.branch', 'SmartServerRequestRevisionHistory')
386
request_handlers.register_lazy(
2018.5.77 by Wouter van Heyst
Fix typo in request_handlers registration of Branch.set_last_revision, and test that registration
387
    'Branch.set_last_revision', 'bzrlib.smart.branch', 'SmartServerBranchRequestSetLastRevision')
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
388
request_handlers.register_lazy(
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
389
    'Branch.set_last_revision_info', 'bzrlib.smart.branch',
390
    'SmartServerBranchRequestSetLastRevisionInfo')
391
request_handlers.register_lazy(
3441.5.25 by Andrew Bennetts
Rename Branch.set_last_revision_descendant verb to Branch.set_last_revision_ex. It's a cop out, but at least it's not misleading.
392
    'Branch.set_last_revision_ex', 'bzrlib.smart.branch',
393
    'SmartServerBranchRequestSetLastRevisionEx')
3441.5.6 by Andrew Bennetts
Greatly simplify RemoteBranch.update_revisions. Still needs more tests.
394
request_handlers.register_lazy(
2018.5.79 by Andrew Bennetts
Implement RemoteBranch.lock_write/unlock as smart operations.
395
    'Branch.unlock', 'bzrlib.smart.branch', 'SmartServerBranchRequestUnlock')
396
request_handlers.register_lazy(
3221.3.2 by Robert Collins
* New remote method ``RemoteBzrDir.find_repositoryV2`` adding support for
397
    'BzrDir.find_repository', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepositoryV1')
398
request_handlers.register_lazy(
399
    'BzrDir.find_repositoryV2', 'bzrlib.smart.bzrdir', 'SmartServerRequestFindRepositoryV2')
2018.5.34 by Robert Collins
Get test_remote.BasicRemoteObjectTests.test_open_remote_branch passing by implementing a remote method BzrDir.find_repository.
400
request_handlers.register_lazy(
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
401
    'BzrDirFormat.initialize', 'bzrlib.smart.bzrdir', 'SmartServerRequestInitializeBzrDir')
402
request_handlers.register_lazy(
2018.6.1 by Robert Collins
Implement a BzrDir.open_branch smart server method for opening a branch without VFS.
403
    'BzrDir.open_branch', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBranch')
404
request_handlers.register_lazy(
2018.5.23 by Andrew Bennetts
Use a Registry for smart server command handlers.
405
    'delete', 'bzrlib.smart.vfs', 'DeleteRequest')
406
request_handlers.register_lazy(
407
    'get', 'bzrlib.smart.vfs', 'GetRequest')
408
request_handlers.register_lazy(
409
    'get_bundle', 'bzrlib.smart.request', 'GetBundleRequest')
410
request_handlers.register_lazy(
411
    'has', 'bzrlib.smart.vfs', 'HasRequest')
412
request_handlers.register_lazy(
413
    'hello', 'bzrlib.smart.request', 'HelloRequest')
414
request_handlers.register_lazy(
2018.5.37 by Andrew Bennetts
Make sure all the request handlers in bzrlib/smart/vfs.py have consistent names.
415
    'iter_files_recursive', 'bzrlib.smart.vfs', 'IterFilesRecursiveRequest')
2018.5.23 by Andrew Bennetts
Use a Registry for smart server command handlers.
416
request_handlers.register_lazy(
417
    'list_dir', 'bzrlib.smart.vfs', 'ListDirRequest')
418
request_handlers.register_lazy(
2018.5.37 by Andrew Bennetts
Make sure all the request handlers in bzrlib/smart/vfs.py have consistent names.
419
    'mkdir', 'bzrlib.smart.vfs', 'MkdirRequest')
420
request_handlers.register_lazy(
421
    'move', 'bzrlib.smart.vfs', 'MoveRequest')
422
request_handlers.register_lazy(
423
    'put', 'bzrlib.smart.vfs', 'PutRequest')
424
request_handlers.register_lazy(
425
    'put_non_atomic', 'bzrlib.smart.vfs', 'PutNonAtomicRequest')
426
request_handlers.register_lazy(
427
    'readv', 'bzrlib.smart.vfs', 'ReadvRequest')
428
request_handlers.register_lazy(
429
    'rename', 'bzrlib.smart.vfs', 'RenameRequest')
2018.10.2 by v.ladeuil+lp at free
gather_stats server side and request registration
430
request_handlers.register_lazy('Repository.gather_stats',
431
                               'bzrlib.smart.repository',
432
                               'SmartServerRepositoryGatherStats')
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
433
request_handlers.register_lazy('Repository.get_parent_map',
434
                               'bzrlib.smart.repository',
435
                               'SmartServerRepositoryGetParentMap')
2018.5.37 by Andrew Bennetts
Make sure all the request handlers in bzrlib/smart/vfs.py have consistent names.
436
request_handlers.register_lazy(
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
437
    'Repository.get_revision_graph', 'bzrlib.smart.repository', 'SmartServerRepositoryGetRevisionGraph')
438
request_handlers.register_lazy(
2018.5.40 by Robert Collins
Implement a remote Repository.has_revision method.
439
    'Repository.has_revision', 'bzrlib.smart.repository', 'SmartServerRequestHasRevision')
440
request_handlers.register_lazy(
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
441
    'Repository.is_shared', 'bzrlib.smart.repository', 'SmartServerRepositoryIsShared')
442
request_handlers.register_lazy(
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
443
    'Repository.lock_write', 'bzrlib.smart.repository', 'SmartServerRepositoryLockWrite')
444
request_handlers.register_lazy(
445
    'Repository.unlock', 'bzrlib.smart.repository', 'SmartServerRepositoryUnlock')
446
request_handlers.register_lazy(
2018.18.1 by Martin Pool
Add stub Repository.tarball smart method
447
    'Repository.tarball', 'bzrlib.smart.repository',
448
    'SmartServerRepositoryTarball')
449
request_handlers.register_lazy(
2018.5.37 by Andrew Bennetts
Make sure all the request handlers in bzrlib/smart/vfs.py have consistent names.
450
    'rmdir', 'bzrlib.smart.vfs', 'RmdirRequest')
451
request_handlers.register_lazy(
452
    'stat', 'bzrlib.smart.vfs', 'StatRequest')
2018.5.26 by Andrew Bennetts
Extract a simple SmartClient class from RemoteTransport, and a hack to avoid VFS operations when probing for a bzrdir over a smart transport.
453
request_handlers.register_lazy(
2018.5.95 by Andrew Bennetts
Add a Transport.is_readonly remote call, let {Branch,Repository}.lock_write remote call return UnlockableTransport, and miscellaneous test fixes.
454
    'Transport.is_readonly', 'bzrlib.smart.request', 'SmartServerIsReadonly')
455
request_handlers.register_lazy(
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
456
    'BzrDir.open', 'bzrlib.smart.bzrdir', 'SmartServerRequestOpenBzrDir')