~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/smart/client.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2008-03-16 14:01:20 UTC
  • mfrom: (3280.2.5 integration)
  • Revision ID: pqm@pqm.ubuntu.com-20080316140120-i3yq8yr1l66m11h7
Start 1.4 development

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2008 Canonical Ltd
 
1
# Copyright (C) 2006 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
 
 
17
 
import bzrlib
18
 
from bzrlib.smart import message, protocol
19
 
from bzrlib.trace import warning
20
 
from bzrlib import (
21
 
    errors,
22
 
    hooks,
23
 
    )
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
import urllib
 
18
from urlparse import urlparse
 
19
 
 
20
from bzrlib.smart import protocol
 
21
from bzrlib import urlutils
24
22
 
25
23
 
26
24
class _SmartClient(object):
27
25
 
28
 
    def __init__(self, medium, headers=None):
 
26
    def __init__(self, shared_connection):
29
27
        """Constructor.
30
28
 
31
 
        :param medium: a SmartClientMedium
 
29
        :param shared_connection: a bzrlib.transport._SharedConnection
32
30
        """
33
 
        self._medium = medium
34
 
        if headers is None:
35
 
            self._headers = {'Software version': bzrlib.__version__}
36
 
        else:
37
 
            self._headers = dict(headers)
38
 
 
39
 
    def _send_request(self, protocol_version, method, args, body=None,
40
 
                      readv_body=None, body_stream=None):
41
 
        encoder, response_handler = self._construct_protocol(
42
 
            protocol_version)
43
 
        encoder.set_headers(self._headers)
44
 
        if body is not None:
45
 
            if readv_body is not None:
46
 
                raise AssertionError(
47
 
                    "body and readv_body are mutually exclusive.")
48
 
            if body_stream is not None:
49
 
                raise AssertionError(
50
 
                    "body and body_stream are mutually exclusive.")
51
 
            encoder.call_with_body_bytes((method, ) + args, body)
52
 
        elif readv_body is not None:
53
 
            if body_stream is not None:
54
 
                raise AssertionError(
55
 
                    "readv_body and body_stream are mutually exclusive.")
56
 
            encoder.call_with_body_readv_array((method, ) + args, readv_body)
57
 
        elif body_stream is not None:
58
 
            encoder.call_with_body_stream((method, ) + args, body_stream)
59
 
        else:
60
 
            encoder.call(method, *args)
61
 
        return response_handler
62
 
 
63
 
    def _run_call_hooks(self, method, args, body, readv_body):
64
 
        if not _SmartClient.hooks['call']:
65
 
            return
66
 
        params = CallHookParams(method, args, body, readv_body, self._medium)
67
 
        for hook in _SmartClient.hooks['call']:
68
 
            hook(params)
69
 
 
70
 
    def _call_and_read_response(self, method, args, body=None, readv_body=None,
71
 
            body_stream=None, expect_response_body=True):
72
 
        self._run_call_hooks(method, args, body, readv_body)
73
 
        if self._medium._protocol_version is not None:
74
 
            response_handler = self._send_request(
75
 
                self._medium._protocol_version, method, args, body=body,
76
 
                readv_body=readv_body, body_stream=body_stream)
77
 
            return (response_handler.read_response_tuple(
78
 
                        expect_body=expect_response_body),
79
 
                    response_handler)
80
 
        else:
81
 
            for protocol_version in [3, 2]:
82
 
                if protocol_version == 2:
83
 
                    # If v3 doesn't work, the remote side is older than 1.6.
84
 
                    self._medium._remember_remote_is_before((1, 6))
85
 
                response_handler = self._send_request(
86
 
                    protocol_version, method, args, body=body,
87
 
                    readv_body=readv_body, body_stream=body_stream)
88
 
                try:
89
 
                    response_tuple = response_handler.read_response_tuple(
90
 
                        expect_body=expect_response_body)
91
 
                except errors.UnexpectedProtocolVersionMarker, err:
92
 
                    # TODO: We could recover from this without disconnecting if
93
 
                    # we recognise the protocol version.
94
 
                    warning(
95
 
                        'Server does not understand Bazaar network protocol %d,'
96
 
                        ' reconnecting.  (Upgrade the server to avoid this.)'
97
 
                        % (protocol_version,))
98
 
                    self._medium.disconnect()
99
 
                    continue
100
 
                except errors.ErrorFromSmartServer:
101
 
                    # If we received an error reply from the server, then it
102
 
                    # must be ok with this protocol version.
103
 
                    self._medium._protocol_version = protocol_version
104
 
                    raise
105
 
                else:
106
 
                    self._medium._protocol_version = protocol_version
107
 
                    return response_tuple, response_handler
108
 
            raise errors.SmartProtocolError(
109
 
                'Server is not a Bazaar server: ' + str(err))
110
 
 
111
 
    def _construct_protocol(self, version):
112
 
        request = self._medium.get_request()
113
 
        if version == 3:
114
 
            request_encoder = protocol.ProtocolThreeRequester(request)
115
 
            response_handler = message.ConventionalResponseHandler()
116
 
            response_proto = protocol.ProtocolThreeDecoder(
117
 
                response_handler, expect_version_marker=True)
118
 
            response_handler.setProtoAndMediumRequest(response_proto, request)
119
 
        elif version == 2:
120
 
            request_encoder = protocol.SmartClientRequestProtocolTwo(request)
121
 
            response_handler = request_encoder
122
 
        else:
123
 
            request_encoder = protocol.SmartClientRequestProtocolOne(request)
124
 
            response_handler = request_encoder
125
 
        return request_encoder, response_handler
 
31
        self._shared_connection = shared_connection
 
32
 
 
33
    def get_smart_medium(self):
 
34
        return self._shared_connection.connection
126
35
 
127
36
    def call(self, method, *args):
128
37
        """Call a method on the remote server."""
132
41
 
133
42
    def call_expecting_body(self, method, *args):
134
43
        """Call a method and return the result and the protocol object.
135
 
 
 
44
        
136
45
        The body can be read like so::
137
46
 
138
47
            result, smart_protocol = smart_client.call_expecting_body(...)
139
48
            body = smart_protocol.read_body_bytes()
140
49
        """
141
 
        return self._call_and_read_response(
142
 
            method, args, expect_response_body=True)
 
50
        request = self.get_smart_medium().get_request()
 
51
        smart_protocol = protocol.SmartClientRequestProtocolTwo(request)
 
52
        smart_protocol.call(method, *args)
 
53
        return smart_protocol.read_response_tuple(expect_body=True), smart_protocol
143
54
 
144
55
    def call_with_body_bytes(self, method, args, body):
145
56
        """Call a method on the remote server with body bytes."""
150
61
                raise TypeError('args must be byte strings, not %r' % (args,))
151
62
        if type(body) is not str:
152
63
            raise TypeError('body must be byte string, not %r' % (body,))
153
 
        response, response_handler = self._call_and_read_response(
154
 
            method, args, body=body, expect_response_body=False)
155
 
        return response
 
64
        request = self.get_smart_medium().get_request()
 
65
        smart_protocol = protocol.SmartClientRequestProtocolOne(request)
 
66
        smart_protocol.call_with_body_bytes((method, ) + args, body)
 
67
        return smart_protocol.read_response_tuple()
156
68
 
157
69
    def call_with_body_bytes_expecting_body(self, method, args, body):
158
70
        """Call a method on the remote server with body bytes."""
163
75
                raise TypeError('args must be byte strings, not %r' % (args,))
164
76
        if type(body) is not str:
165
77
            raise TypeError('body must be byte string, not %r' % (body,))
166
 
        response, response_handler = self._call_and_read_response(
167
 
            method, args, body=body, expect_response_body=True)
168
 
        return (response, response_handler)
169
 
 
170
 
    def call_with_body_readv_array(self, args, body):
171
 
        response, response_handler = self._call_and_read_response(
172
 
                args[0], args[1:], readv_body=body, expect_response_body=True)
173
 
        return (response, response_handler)
174
 
 
175
 
    def call_with_body_stream(self, args, stream):
176
 
        response, response_handler = self._call_and_read_response(
177
 
                args[0], args[1:], body_stream=stream,
178
 
                expect_response_body=False)
179
 
        return (response, response_handler)
 
78
        request = self.get_smart_medium().get_request()
 
79
        smart_protocol = protocol.SmartClientRequestProtocolTwo(request)
 
80
        smart_protocol.call_with_body_bytes((method, ) + args, body)
 
81
        return smart_protocol.read_response_tuple(expect_body=True), smart_protocol
180
82
 
181
83
    def remote_path_from_transport(self, transport):
182
84
        """Convert transport into a path suitable for using in a request.
183
 
 
 
85
        
184
86
        Note that the resulting remote path doesn't encode the host name or
185
87
        anything but path, so it is only safe to use it in requests sent over
186
88
        the medium from the matching transport.
187
89
        """
188
 
        return self._medium.remote_path_from_transport(transport)
189
 
 
190
 
 
191
 
class SmartClientHooks(hooks.Hooks):
192
 
 
193
 
    def __init__(self):
194
 
        hooks.Hooks.__init__(self)
195
 
        self.create_hook(hooks.HookPoint('call',
196
 
            "Called when the smart client is submitting a request to the "
197
 
            "smart server. Called with a bzrlib.smart.client.CallHookParams "
198
 
            "object. Streaming request bodies, and responses, are not "
199
 
            "accessible.", None, None))
200
 
 
201
 
 
202
 
_SmartClient.hooks = SmartClientHooks()
203
 
 
204
 
 
205
 
class CallHookParams(object):
206
 
 
207
 
    def __init__(self, method, args, body, readv_body, medium):
208
 
        self.method = method
209
 
        self.args = args
210
 
        self.body = body
211
 
        self.readv_body = readv_body
212
 
        self.medium = medium
213
 
 
214
 
    def __repr__(self):
215
 
        attrs = dict((k, v) for (k, v) in self.__dict__.iteritems()
216
 
                     if v is not None)
217
 
        return '<%s %r>' % (self.__class__.__name__, attrs)
218
 
 
219
 
    def __eq__(self, other):
220
 
        if type(other) is not type(self):
221
 
            return NotImplemented
222
 
        return self.__dict__ == other.__dict__
223
 
 
224
 
    def __ne__(self, other):
225
 
        return not self == other
 
90
        base = self._shared_connection.base
 
91
        if base.startswith('bzr+http://') or base.startswith('bzr+https://'):
 
92
            medium_base = self._shared_connection.base
 
93
        else:
 
94
            medium_base = urlutils.join(self._shared_connection.base, '/')
 
95
            
 
96
        rel_url = urlutils.relative_url(medium_base, transport.base)
 
97
        return urllib.unquote(rel_url)