1
# Copyright (C) 2006 Canonical Ltd
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.
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.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
from urlparse import urlsplit, urlunsplit
24
from bzrlib.lazy_import import lazy_import
25
lazy_import(globals(), """
26
from bzrlib import urlutils
32
__version__ as _bzrlib_version,
34
from bzrlib.transport.http import _urllib2_wrappers
38
export BZR_LP_XMLRPC_URL=http://xmlrpc.staging.launchpad.net/bazaar/
41
class InvalidLaunchpadInstance(errors.BzrError):
43
_fmt = "%(lp_instance)s is not a valid Launchpad instance."
45
def __init__(self, lp_instance):
46
errors.BzrError.__init__(self, lp_instance=lp_instance)
49
class NotLaunchpadBranch(errors.BzrError):
51
_fmt = "%(url)s is not registered on Launchpad."
53
def __init__(self, url):
54
errors.BzrError.__init__(self, url=url)
57
class XMLRPCTransport(xmlrpclib.Transport):
59
def __init__(self, scheme):
60
# In python2.4 xmlrpclib.Transport is a old-style class, and does not
61
# define __init__, so we check first
62
init = getattr(xmlrpclib.Transport, '__init__', None)
66
self._opener = _urllib2_wrappers.Opener()
69
def request(self, host, handler, request_body, verbose=0):
70
self.verbose = verbose
71
url = self._scheme + "://" + host + handler
72
request = _urllib2_wrappers.Request("POST", url, request_body)
73
# FIXME: _urllib2_wrappers will override user-agent with its own
74
# request.add_header("User-Agent", self.user_agent)
75
request.add_header("Content-Type", "text/xml")
77
response = self._opener.open(request)
78
if response.code != 200:
79
raise xmlrpclib.ProtocolError(host + handler, response.code,
80
response.msg, response.info())
81
return self.parse_response(response)
84
class LaunchpadService(object):
85
"""A service to talk to Launchpad via XMLRPC.
87
See http://bazaar-vcs.org/Specs/LaunchpadRpc for the methods we can call.
91
'production': 'launchpad.net',
92
'edge': 'edge.launchpad.net',
93
'staging': 'staging.launchpad.net',
94
'demo': 'demo.launchpad.net',
95
'dev': 'launchpad.dev',
98
# NB: these should always end in a slash to avoid xmlrpclib appending
100
LAUNCHPAD_INSTANCE = {}
101
for instance, domain in LAUNCHPAD_DOMAINS.iteritems():
102
LAUNCHPAD_INSTANCE[instance] = 'https://xmlrpc.%s/bazaar/' % domain
104
# We use edge as the default because:
105
# Beta users get redirected to it
106
# All users can use it
107
# There is a bug in the launchpad side where redirection causes an OOPS.
108
DEFAULT_INSTANCE = 'edge'
109
DEFAULT_SERVICE_URL = LAUNCHPAD_INSTANCE[DEFAULT_INSTANCE]
112
registrant_email = None
113
registrant_password = None
116
def __init__(self, transport=None, lp_instance=None):
117
"""Construct a new service talking to the launchpad rpc server"""
118
self._lp_instance = lp_instance
119
if transport is None:
120
uri_type = urllib.splittype(self.service_url)[0]
121
transport = XMLRPCTransport(uri_type)
122
transport.user_agent = 'bzr/%s (xmlrpclib/%s)' \
123
% (_bzrlib_version, xmlrpclib.__version__)
124
self.transport = transport
128
def service_url(self):
129
"""Return the http or https url for the xmlrpc server.
131
This does not include the username/password credentials.
133
key = 'BZR_LP_XMLRPC_URL'
134
if key in os.environ:
135
return os.environ[key]
136
elif self._lp_instance is not None:
138
return self.LAUNCHPAD_INSTANCE[self._lp_instance]
140
raise InvalidLaunchpadInstance(self._lp_instance)
142
return self.DEFAULT_SERVICE_URL
144
def get_proxy(self, authenticated):
145
"""Return the proxy for XMLRPC requests."""
147
# auth info must be in url
148
# TODO: if there's no registrant email perhaps we should
149
# just connect anonymously?
150
scheme, hostinfo, path = urlsplit(self.service_url)[:3]
152
raise AssertionError(hostinfo)
153
if self.registrant_email is None:
154
raise AssertionError()
155
if self.registrant_password is None:
156
raise AssertionError()
157
# TODO: perhaps fully quote the password to make it very slightly
159
# TODO: can we perhaps add extra Authorization headers
160
# directly to the request, rather than putting this into
161
# the url? perhaps a bit more secure against accidentally
162
# revealing it. std66 s3.2.1 discourages putting the
163
# password in the url.
164
hostinfo = '%s:%s@%s' % (urllib.quote(self.registrant_email),
165
urllib.quote(self.registrant_password),
167
url = urlunsplit((scheme, hostinfo, path, '', ''))
169
url = self.service_url
170
return xmlrpclib.ServerProxy(url, transport=self.transport)
172
def gather_user_credentials(self):
173
"""Get the password from the user."""
174
the_config = config.GlobalConfig()
175
self.registrant_email = the_config.user_email()
176
if self.registrant_password is None:
177
auth = config.AuthenticationConfig()
178
scheme, hostinfo = urlsplit(self.service_url)[:2]
179
prompt = 'launchpad.net password for %s: ' % \
180
self.registrant_email
181
# We will reuse http[s] credentials if we can, prompt user
183
self.registrant_password = auth.get_password(scheme, hostinfo,
184
self.registrant_email,
187
def send_request(self, method_name, method_params, authenticated):
188
proxy = self.get_proxy(authenticated)
189
method = getattr(proxy, method_name)
191
result = method(*method_params)
192
except xmlrpclib.ProtocolError, e:
194
# TODO: This can give a ProtocolError representing a 301 error, whose
195
# e.headers['location'] tells where to go and e.errcode==301; should
196
# probably log something and retry on the new url.
197
raise NotImplementedError("should resend request to %s, but this isn't implemented"
198
% e.headers.get('Location', 'NO-LOCATION-PRESENT'))
200
# we don't want to print the original message because its
201
# str representation includes the plaintext password.
202
# TODO: print more headers to help in tracking down failures
203
raise errors.BzrError("xmlrpc protocol error connecting to %s: %s %s"
204
% (self.service_url, e.errcode, e.errmsg))
205
except socket.gaierror, e:
206
raise errors.ConnectionError(
207
"Could not resolve '%s'" % self.domain,
213
if self._lp_instance is None:
214
instance = self.DEFAULT_INSTANCE
216
instance = self._lp_instance
217
return self.LAUNCHPAD_DOMAINS[instance]
219
def get_web_url_from_branch_url(self, branch_url, _request_factory=None):
220
"""Get the Launchpad web URL for the given branch URL.
222
:raise errors.InvalidURL: if 'branch_url' cannot be identified as a
223
Launchpad branch URL.
224
:return: The URL of the branch on Launchpad.
226
scheme, hostinfo, path = urlsplit(branch_url)[:3]
227
if _request_factory is None:
228
_request_factory = ResolveLaunchpadPathRequest
230
resolve = _request_factory(path)
232
result = resolve.submit(self)
233
except xmlrpclib.Fault, fault:
234
raise errors.InvalidURL(branch_url, str(fault))
235
branch_url = result['urls'][0]
236
path = urlsplit(branch_url)[2]
240
for domain in self.LAUNCHPAD_DOMAINS.itervalues())
241
if hostinfo not in domains:
242
raise NotLaunchpadBranch(branch_url)
243
return urlutils.join('https://code.%s' % self.domain, path)
246
class BaseRequest(object):
247
"""Base request for talking to a XMLRPC server."""
249
# Set this to the XMLRPC method name.
251
_authenticated = True
253
def _request_params(self):
254
"""Return the arguments to pass to the method"""
255
raise NotImplementedError(self._request_params)
257
def submit(self, service):
258
"""Submit request to Launchpad XMLRPC server.
260
:param service: LaunchpadService indicating where to send
261
the request and the authentication credentials.
263
return service.send_request(self._methodname, self._request_params(),
267
class DryRunLaunchpadService(LaunchpadService):
268
"""Service that just absorbs requests without sending to server.
270
The dummy service does not need authentication.
273
def send_request(self, method_name, method_params, authenticated):
276
def gather_user_credentials(self):
280
class BranchRegistrationRequest(BaseRequest):
281
"""Request to tell Launchpad about a bzr branch."""
283
_methodname = 'register_branch'
285
def __init__(self, branch_url,
288
branch_description='',
293
raise errors.InvalidURL(branch_url, "You need to specify a non-empty branch URL.")
294
self.branch_url = branch_url
296
self.branch_name = branch_name
298
self.branch_name = self._find_default_branch_name(self.branch_url)
299
self.branch_title = branch_title
300
self.branch_description = branch_description
301
self.author_email = author_email
302
self.product_name = product_name
304
def _request_params(self):
305
"""Return xmlrpc request parameters"""
306
# This must match the parameter tuple expected by Launchpad for this
308
return (self.branch_url,
311
self.branch_description,
316
def _find_default_branch_name(self, branch_url):
317
i = branch_url.rfind('/')
318
return branch_url[i+1:]
321
class BranchBugLinkRequest(BaseRequest):
322
"""Request to link a bzr branch in Launchpad to a bug."""
324
_methodname = 'link_branch_to_bug'
326
def __init__(self, branch_url, bug_id):
328
self.branch_url = branch_url
330
def _request_params(self):
331
"""Return xmlrpc request parameters"""
332
# This must match the parameter tuple expected by Launchpad for this
334
return (self.branch_url, self.bug_id, '')
337
class ResolveLaunchpadPathRequest(BaseRequest):
338
"""Request to resolve the path component of an lp: URL."""
340
_methodname = 'resolve_lp_path'
341
_authenticated = False
343
def __init__(self, path):
345
raise errors.InvalidURL(path=path,
346
extra="You must specify a project.")
349
def _request_params(self):
350
"""Return xmlrpc request parameters"""