~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/plugins/launchpad/lp_registration.py

Merge bzr.dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2011 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
 
from __future__ import absolute_import
18
 
 
19
 
 
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
 
 
18
from getpass import getpass
20
19
import os
21
 
import socket
22
20
from urlparse import urlsplit, urlunsplit
23
21
import urllib
24
22
import xmlrpclib
26
24
from bzrlib import (
27
25
    config,
28
26
    errors,
29
 
    urlutils,
30
27
    __version__ as _bzrlib_version,
31
28
    )
32
 
from bzrlib.transport.http import _urllib2_wrappers
33
 
 
34
29
 
35
30
# for testing, do
36
31
'''
37
32
export BZR_LP_XMLRPC_URL=http://xmlrpc.staging.launchpad.net/bazaar/
38
33
'''
39
34
 
40
 
class InvalidLaunchpadInstance(errors.BzrError):
41
 
 
42
 
    _fmt = "%(lp_instance)s is not a valid Launchpad instance."
43
 
 
44
 
    def __init__(self, lp_instance):
45
 
        errors.BzrError.__init__(self, lp_instance=lp_instance)
46
 
 
47
 
 
48
 
class NotLaunchpadBranch(errors.BzrError):
49
 
 
50
 
    _fmt = "%(url)s is not registered on Launchpad."
51
 
 
52
 
    def __init__(self, url):
53
 
        errors.BzrError.__init__(self, url=url)
54
 
 
55
 
 
56
 
class XMLRPCTransport(xmlrpclib.Transport):
57
 
 
58
 
    def __init__(self, scheme):
59
 
        xmlrpclib.Transport.__init__(self)
60
 
        self._scheme = scheme
61
 
        self._opener = _urllib2_wrappers.Opener()
62
 
        self.verbose = 0
63
 
 
64
 
    def request(self, host, handler, request_body, verbose=0):
65
 
        self.verbose = verbose
66
 
        url = self._scheme + "://" + host + handler
67
 
        request = _urllib2_wrappers.Request("POST", url, request_body)
68
 
        # FIXME: _urllib2_wrappers will override user-agent with its own
69
 
        # request.add_header("User-Agent", self.user_agent)
70
 
        request.add_header("Content-Type", "text/xml")
71
 
 
72
 
        response = self._opener.open(request)
73
 
        if response.code != 200:
74
 
            raise xmlrpclib.ProtocolError(host + handler, response.code,
75
 
                                          response.msg, response.info())
76
 
        return self.parse_response(response)
77
 
 
78
 
 
79
35
class LaunchpadService(object):
80
36
    """A service to talk to Launchpad via XMLRPC.
81
 
 
82
 
    See http://wiki.bazaar.canonical.com/Specs/LaunchpadRpc for the methods we can call.
 
37
    
 
38
    See http://bazaar-vcs.org/Specs/LaunchpadRpc for the methods we can call.
83
39
    """
84
40
 
85
 
    LAUNCHPAD_DOMAINS = {
86
 
        'production': 'launchpad.net',
87
 
        'staging': 'staging.launchpad.net',
88
 
        'qastaging': 'qastaging.launchpad.net',
89
 
        'demo': 'demo.launchpad.net',
90
 
        'dev': 'launchpad.dev',
91
 
        }
92
 
 
93
 
    # NB: these should always end in a slash to avoid xmlrpclib appending
 
41
    # NB: this should always end in a slash to avoid xmlrpclib appending
94
42
    # '/RPC2'
95
 
    LAUNCHPAD_INSTANCE = {}
96
 
    for instance, domain in LAUNCHPAD_DOMAINS.iteritems():
97
 
        LAUNCHPAD_INSTANCE[instance] = 'https://xmlrpc.%s/bazaar/' % domain
98
 
 
99
 
    # We use production as the default because edge has been deprecated circa
100
 
    # 2010-11 (see bug https://bugs.launchpad.net/bzr/+bug/583667)
101
 
    DEFAULT_INSTANCE = 'production'
102
 
    DEFAULT_SERVICE_URL = LAUNCHPAD_INSTANCE[DEFAULT_INSTANCE]
 
43
    DEFAULT_SERVICE_URL = 'https://xmlrpc.launchpad.net/bazaar/'
103
44
 
104
45
    transport = None
105
46
    registrant_email = None
106
47
    registrant_password = None
107
48
 
108
49
 
109
 
    def __init__(self, transport=None, lp_instance=None):
 
50
    def __init__(self, transport=None):
110
51
        """Construct a new service talking to the launchpad rpc server"""
111
 
        self._lp_instance = lp_instance
112
52
        if transport is None:
113
53
            uri_type = urllib.splittype(self.service_url)[0]
114
 
            transport = XMLRPCTransport(uri_type)
 
54
            if uri_type == 'https':
 
55
                transport = xmlrpclib.SafeTransport()
 
56
            else:
 
57
                transport = xmlrpclib.Transport()
115
58
            transport.user_agent = 'bzr/%s (xmlrpclib/%s)' \
116
59
                    % (_bzrlib_version, xmlrpclib.__version__)
117
60
        self.transport = transport
118
61
 
 
62
 
119
63
    @property
120
64
    def service_url(self):
121
65
        """Return the http or https url for the xmlrpc server.
125
69
        key = 'BZR_LP_XMLRPC_URL'
126
70
        if key in os.environ:
127
71
            return os.environ[key]
128
 
        elif self._lp_instance is not None:
129
 
            try:
130
 
                return self.LAUNCHPAD_INSTANCE[self._lp_instance]
131
 
            except KeyError:
132
 
                raise InvalidLaunchpadInstance(self._lp_instance)
133
72
        else:
134
73
            return self.DEFAULT_SERVICE_URL
135
74
 
136
 
    @classmethod
137
 
    def for_url(cls, url, **kwargs):
138
 
        """Return the Launchpad service corresponding to the given URL."""
139
 
        result = urlsplit(url)
140
 
        lp_instance = result[1]
141
 
        if lp_instance == '':
142
 
            lp_instance = None
143
 
        elif lp_instance not in cls.LAUNCHPAD_INSTANCE:
144
 
            raise errors.InvalidURL(path=url)
145
 
        return cls(lp_instance=lp_instance, **kwargs)
146
 
 
147
75
    def get_proxy(self, authenticated):
148
76
        """Return the proxy for XMLRPC requests."""
149
77
        if authenticated:
151
79
            # TODO: if there's no registrant email perhaps we should
152
80
            # just connect anonymously?
153
81
            scheme, hostinfo, path = urlsplit(self.service_url)[:3]
154
 
            if '@' in hostinfo:
155
 
                raise AssertionError(hostinfo)
156
 
            if self.registrant_email is None:
157
 
                raise AssertionError()
158
 
            if self.registrant_password is None:
159
 
                raise AssertionError()
 
82
            assert '@' not in hostinfo
 
83
            assert self.registrant_email is not None
 
84
            assert self.registrant_password is not None
160
85
            # TODO: perhaps fully quote the password to make it very slightly
161
86
            # obscured
162
87
            # TODO: can we perhaps add extra Authorization headers
164
89
            # the url?  perhaps a bit more secure against accidentally
165
90
            # revealing it.  std66 s3.2.1 discourages putting the
166
91
            # password in the url.
167
 
            hostinfo = '%s:%s@%s' % (urlutils.quote(self.registrant_email),
168
 
                                     urlutils.quote(self.registrant_password),
 
92
            hostinfo = '%s:%s@%s' % (urllib.quote(self.registrant_email),
 
93
                                     urllib.quote(self.registrant_password),
169
94
                                     hostinfo)
170
95
            url = urlunsplit((scheme, hostinfo, path, '', ''))
171
96
        else:
189
114
 
190
115
    def send_request(self, method_name, method_params, authenticated):
191
116
        proxy = self.get_proxy(authenticated)
 
117
        assert method_name
192
118
        method = getattr(proxy, method_name)
193
119
        try:
194
120
            result = method(*method_params)
205
131
                # TODO: print more headers to help in tracking down failures
206
132
                raise errors.BzrError("xmlrpc protocol error connecting to %s: %s %s"
207
133
                        % (self.service_url, e.errcode, e.errmsg))
208
 
        except socket.gaierror, e:
209
 
            raise errors.ConnectionError(
210
 
                "Could not resolve '%s'" % self.domain,
211
 
                orig_error=e)
212
134
        return result
213
135
 
214
 
    @property
215
 
    def domain(self):
216
 
        if self._lp_instance is None:
217
 
            instance = self.DEFAULT_INSTANCE
218
 
        else:
219
 
            instance = self._lp_instance
220
 
        return self.LAUNCHPAD_DOMAINS[instance]
221
 
 
222
 
    def _guess_branch_path(self, branch_url, _request_factory=None):
223
 
        scheme, hostinfo, path = urlsplit(branch_url)[:3]
224
 
        if _request_factory is None:
225
 
            _request_factory = ResolveLaunchpadPathRequest
226
 
        if scheme == 'lp':
227
 
            resolve = _request_factory(path)
228
 
            try:
229
 
                result = resolve.submit(self)
230
 
            except xmlrpclib.Fault, fault:
231
 
                raise errors.InvalidURL(branch_url, str(fault))
232
 
            branch_url = result['urls'][0]
233
 
            path = urlsplit(branch_url)[2]
234
 
        else:
235
 
            domains = (
236
 
                'bazaar.%s' % domain
237
 
                for domain in self.LAUNCHPAD_DOMAINS.itervalues())
238
 
            if hostinfo not in domains:
239
 
                raise NotLaunchpadBranch(branch_url)
240
 
        return path.lstrip('/')
241
 
 
242
 
    def get_web_url_from_branch_url(self, branch_url, _request_factory=None):
243
 
        """Get the Launchpad web URL for the given branch URL.
244
 
 
245
 
        :raise errors.InvalidURL: if 'branch_url' cannot be identified as a
246
 
            Launchpad branch URL.
247
 
        :return: The URL of the branch on Launchpad.
248
 
        """
249
 
        path = self._guess_branch_path(branch_url, _request_factory)
250
 
        return urlutils.join('https://code.%s' % self.domain, path)
251
 
 
252
136
 
253
137
class BaseRequest(object):
254
138
    """Base request for talking to a XMLRPC server."""
273
157
 
274
158
class DryRunLaunchpadService(LaunchpadService):
275
159
    """Service that just absorbs requests without sending to server.
276
 
 
 
160
    
277
161
    The dummy service does not need authentication.
278
162
    """
279
163
 
296
180
                 author_email='',
297
181
                 product_name='',
298
182
                 ):
299
 
        if not branch_url:
300
 
            raise errors.InvalidURL(branch_url, "You need to specify a non-empty branch URL.")
 
183
        assert branch_url
301
184
        self.branch_url = branch_url
302
185
        if branch_name:
303
186
            self.branch_name = branch_name
331
214
    _methodname = 'link_branch_to_bug'
332
215
 
333
216
    def __init__(self, branch_url, bug_id):
 
217
        assert branch_url
334
218
        self.bug_id = bug_id
335
219
        self.branch_url = branch_url
336
220
 
348
232
    _authenticated = False
349
233
 
350
234
    def __init__(self, path):
351
 
        if not path:
352
 
            raise errors.InvalidURL(path=path,
353
 
                                    extra="You must specify a project.")
 
235
        assert path
354
236
        self.path = path
355
237
 
356
238
    def _request_params(self):