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
19
from urlparse import urlsplit, urlunsplit
27
__version__ as _bzrlib_version,
33
export BZR_LP_XMLRPC_URL=http://xmlrpc.staging.launchpad.net/bazaar/
36
class InvalidLaunchpadInstance(errors.BzrError):
38
_fmt = "%(lp_instance)s is not a valid Launchpad instance."
40
def __init__(self, lp_instance):
41
errors.BzrError.__init__(self, lp_instance=lp_instance)
44
class NotLaunchpadBranch(errors.BzrError):
46
_fmt = "%(url)s is not registered on Launchpad."
48
def __init__(self, url):
49
errors.BzrError.__init__(self, url=url)
52
class LaunchpadService(object):
53
"""A service to talk to Launchpad via XMLRPC.
55
See http://bazaar-vcs.org/Specs/LaunchpadRpc for the methods we can call.
59
'production': 'launchpad.net',
60
'edge': 'edge.launchpad.net',
61
'staging': 'staging.launchpad.net',
62
'demo': 'demo.launchpad.net',
63
'dev': 'launchpad.dev',
66
# NB: these should always end in a slash to avoid xmlrpclib appending
68
LAUNCHPAD_INSTANCE = {}
69
for instance, domain in LAUNCHPAD_DOMAINS.iteritems():
70
LAUNCHPAD_INSTANCE[instance] = 'https://xmlrpc.%s/bazaar/' % domain
72
# We use edge as the default because:
73
# Beta users get redirected to it
74
# All users can use it
75
# There is a bug in the launchpad side where redirection causes an OOPS.
76
DEFAULT_INSTANCE = 'edge'
77
DEFAULT_SERVICE_URL = LAUNCHPAD_INSTANCE[DEFAULT_INSTANCE]
80
registrant_email = None
81
registrant_password = None
84
def __init__(self, transport=None, lp_instance=None):
85
"""Construct a new service talking to the launchpad rpc server"""
86
self._lp_instance = lp_instance
88
uri_type = urllib.splittype(self.service_url)[0]
89
if uri_type == 'https':
90
transport = xmlrpclib.SafeTransport()
92
transport = xmlrpclib.Transport()
93
transport.user_agent = 'bzr/%s (xmlrpclib/%s)' \
94
% (_bzrlib_version, xmlrpclib.__version__)
95
self.transport = transport
98
def service_url(self):
99
"""Return the http or https url for the xmlrpc server.
101
This does not include the username/password credentials.
103
key = 'BZR_LP_XMLRPC_URL'
104
if key in os.environ:
105
return os.environ[key]
106
elif self._lp_instance is not None:
108
return self.LAUNCHPAD_INSTANCE[self._lp_instance]
110
raise InvalidLaunchpadInstance(self._lp_instance)
112
return self.DEFAULT_SERVICE_URL
115
def for_url(cls, url, **kwargs):
116
"""Return the Launchpad service corresponding to the given URL."""
117
result = urlsplit(url)
118
lp_instance = result[1]
119
if lp_instance == '':
121
elif lp_instance not in cls.LAUNCHPAD_INSTANCE:
122
raise errors.InvalidURL(path=url)
123
return cls(lp_instance=lp_instance, **kwargs)
125
def get_proxy(self, authenticated):
126
"""Return the proxy for XMLRPC requests."""
128
# auth info must be in url
129
# TODO: if there's no registrant email perhaps we should
130
# just connect anonymously?
131
scheme, hostinfo, path = urlsplit(self.service_url)[:3]
133
raise AssertionError(hostinfo)
134
if self.registrant_email is None:
135
raise AssertionError()
136
if self.registrant_password is None:
137
raise AssertionError()
138
# TODO: perhaps fully quote the password to make it very slightly
140
# TODO: can we perhaps add extra Authorization headers
141
# directly to the request, rather than putting this into
142
# the url? perhaps a bit more secure against accidentally
143
# revealing it. std66 s3.2.1 discourages putting the
144
# password in the url.
145
hostinfo = '%s:%s@%s' % (urllib.quote(self.registrant_email),
146
urllib.quote(self.registrant_password),
148
url = urlunsplit((scheme, hostinfo, path, '', ''))
150
url = self.service_url
151
return xmlrpclib.ServerProxy(url, transport=self.transport)
153
def gather_user_credentials(self):
154
"""Get the password from the user."""
155
the_config = config.GlobalConfig()
156
self.registrant_email = the_config.user_email()
157
if self.registrant_password is None:
158
auth = config.AuthenticationConfig()
159
scheme, hostinfo = urlsplit(self.service_url)[:2]
160
prompt = 'launchpad.net password for %s: ' % \
161
self.registrant_email
162
# We will reuse http[s] credentials if we can, prompt user
164
self.registrant_password = auth.get_password(scheme, hostinfo,
165
self.registrant_email,
168
def send_request(self, method_name, method_params, authenticated):
169
proxy = self.get_proxy(authenticated)
170
method = getattr(proxy, method_name)
172
result = method(*method_params)
173
except xmlrpclib.ProtocolError, e:
175
# TODO: This can give a ProtocolError representing a 301 error, whose
176
# e.headers['location'] tells where to go and e.errcode==301; should
177
# probably log something and retry on the new url.
178
raise NotImplementedError("should resend request to %s, but this isn't implemented"
179
% e.headers.get('Location', 'NO-LOCATION-PRESENT'))
181
# we don't want to print the original message because its
182
# str representation includes the plaintext password.
183
# TODO: print more headers to help in tracking down failures
184
raise errors.BzrError("xmlrpc protocol error connecting to %s: %s %s"
185
% (self.service_url, e.errcode, e.errmsg))
190
if self._lp_instance is None:
191
instance = self.DEFAULT_INSTANCE
193
instance = self._lp_instance
194
return self.LAUNCHPAD_DOMAINS[instance]
196
def _guess_branch_path(self, branch_url, _request_factory=None):
197
scheme, hostinfo, path = urlsplit(branch_url)[:3]
198
if _request_factory is None:
199
_request_factory = ResolveLaunchpadPathRequest
201
resolve = _request_factory(path)
203
result = resolve.submit(self)
204
except xmlrpclib.Fault, fault:
205
raise errors.InvalidURL(branch_url, str(fault))
206
branch_url = result['urls'][0]
207
path = urlsplit(branch_url)[2]
211
for domain in self.LAUNCHPAD_DOMAINS.itervalues())
212
if hostinfo not in domains:
213
raise NotLaunchpadBranch(branch_url)
214
return path.lstrip('/')
216
def get_web_url_from_branch_url(self, branch_url, _request_factory=None):
217
"""Get the Launchpad web URL for the given branch URL.
219
:raise errors.InvalidURL: if 'branch_url' cannot be identified as a
220
Launchpad branch URL.
221
:return: The URL of the branch on Launchpad.
223
path = self._guess_branch_path(branch_url, _request_factory)
224
return urlutils.join('https://code.%s' % self.domain, path)
227
class BaseRequest(object):
228
"""Base request for talking to a XMLRPC server."""
230
# Set this to the XMLRPC method name.
232
_authenticated = True
234
def _request_params(self):
235
"""Return the arguments to pass to the method"""
236
raise NotImplementedError(self._request_params)
238
def submit(self, service):
239
"""Submit request to Launchpad XMLRPC server.
241
:param service: LaunchpadService indicating where to send
242
the request and the authentication credentials.
244
return service.send_request(self._methodname, self._request_params(),
248
class DryRunLaunchpadService(LaunchpadService):
249
"""Service that just absorbs requests without sending to server.
251
The dummy service does not need authentication.
254
def send_request(self, method_name, method_params, authenticated):
257
def gather_user_credentials(self):
261
class BranchRegistrationRequest(BaseRequest):
262
"""Request to tell Launchpad about a bzr branch."""
264
_methodname = 'register_branch'
266
def __init__(self, branch_url,
269
branch_description='',
274
raise errors.InvalidURL(branch_url, "You need to specify a non-empty branch URL.")
275
self.branch_url = branch_url
277
self.branch_name = branch_name
279
self.branch_name = self._find_default_branch_name(self.branch_url)
280
self.branch_title = branch_title
281
self.branch_description = branch_description
282
self.author_email = author_email
283
self.product_name = product_name
285
def _request_params(self):
286
"""Return xmlrpc request parameters"""
287
# This must match the parameter tuple expected by Launchpad for this
289
return (self.branch_url,
292
self.branch_description,
297
def _find_default_branch_name(self, branch_url):
298
i = branch_url.rfind('/')
299
return branch_url[i+1:]
302
class BranchBugLinkRequest(BaseRequest):
303
"""Request to link a bzr branch in Launchpad to a bug."""
305
_methodname = 'link_branch_to_bug'
307
def __init__(self, branch_url, bug_id):
309
self.branch_url = branch_url
311
def _request_params(self):
312
"""Return xmlrpc request parameters"""
313
# This must match the parameter tuple expected by Launchpad for this
315
return (self.branch_url, self.bug_id, '')
318
class ResolveLaunchpadPathRequest(BaseRequest):
319
"""Request to resolve the path component of an lp: URL."""
321
_methodname = 'resolve_lp_path'
322
_authenticated = False
324
def __init__(self, path):
326
raise errors.InvalidURL(path=path,
327
extra="You must specify a project.")
330
def _request_params(self):
331
"""Return xmlrpc request parameters"""