/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

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

  • Committer: Tim Penhey
  • Date: 2008-01-22 08:40:50 UTC
  • mto: (3211.1.1 ianc-integration)
  • mto: This revision was merged to the branch mainline in revision 3212.
  • Revision ID: tim.penhey@canonical.com-20080122084050-af9b4nqlg046z6bc
Mostly working, just need to update the tests for lp://dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006 Canonical Ltd
 
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
 
 
17
 
 
18
from getpass import getpass
 
19
import os
 
20
from urlparse import urlsplit, urlunsplit
 
21
import urllib
 
22
import xmlrpclib
 
23
 
 
24
from bzrlib import (
 
25
    config,
 
26
    errors,
 
27
    __version__ as _bzrlib_version,
 
28
    )
 
29
 
 
30
# for testing, do
 
31
'''
 
32
export BZR_LP_XMLRPC_URL=http://xmlrpc.staging.launchpad.net/bazaar/
 
33
'''
 
34
 
 
35
class LaunchpadService(object):
 
36
    """A service to talk to Launchpad via XMLRPC.
 
37
    
 
38
    See http://bazaar-vcs.org/Specs/LaunchpadRpc for the methods we can call.
 
39
    """
 
40
 
 
41
    # NB: this should always end in a slash to avoid xmlrpclib appending
 
42
    # '/RPC2'
 
43
    LAUNCHPAD_INSTANCE = {
 
44
        'production': 'https://xmlrpc.launchpad.net/bazaar/',
 
45
        'edge': 'https://xmlrpc.edge.launchpad.net/bazaar/',
 
46
        'staging': 'https://xmlrpc.staging.launchpad.net/bazaar/',
 
47
        'demo': 'https://xmlrpc.demo.launchpad.net/bazaar/',
 
48
        'dev': 'http://xmlrpc.launchpad.dev/bazaar/',
 
49
        }
 
50
    DEFAULT_SERVICE_URL = LAUNCHPAD_INSTANCE['production']
 
51
 
 
52
    transport = None
 
53
    registrant_email = None
 
54
    registrant_password = None
 
55
 
 
56
 
 
57
    def __init__(self, transport=None, lp_instance=None):
 
58
        """Construct a new service talking to the launchpad rpc server"""
 
59
        self._lp_instance = lp_instance
 
60
        if transport is None:
 
61
            uri_type = urllib.splittype(self.service_url)[0]
 
62
            if uri_type == 'https':
 
63
                transport = xmlrpclib.SafeTransport()
 
64
            else:
 
65
                transport = xmlrpclib.Transport()
 
66
            transport.user_agent = 'bzr/%s (xmlrpclib/%s)' \
 
67
                    % (_bzrlib_version, xmlrpclib.__version__)
 
68
        self.transport = transport
 
69
 
 
70
 
 
71
    @property
 
72
    def service_url(self):
 
73
        """Return the http or https url for the xmlrpc server.
 
74
 
 
75
        This does not include the username/password credentials.
 
76
        """
 
77
        key = 'BZR_LP_XMLRPC_URL'
 
78
        if key in os.environ:
 
79
            return os.environ[key]
 
80
        elif self._lp_instance is not None:
 
81
            return self.LAUNCHPAD_INSTANCE[self._lp_instance]
 
82
        else:
 
83
            return self.DEFAULT_SERVICE_URL
 
84
 
 
85
    def get_proxy(self, authenticated):
 
86
        """Return the proxy for XMLRPC requests."""
 
87
        if authenticated:
 
88
            # auth info must be in url
 
89
            # TODO: if there's no registrant email perhaps we should
 
90
            # just connect anonymously?
 
91
            scheme, hostinfo, path = urlsplit(self.service_url)[:3]
 
92
            assert '@' not in hostinfo
 
93
            assert self.registrant_email is not None
 
94
            assert self.registrant_password is not None
 
95
            # TODO: perhaps fully quote the password to make it very slightly
 
96
            # obscured
 
97
            # TODO: can we perhaps add extra Authorization headers
 
98
            # directly to the request, rather than putting this into
 
99
            # the url?  perhaps a bit more secure against accidentally
 
100
            # revealing it.  std66 s3.2.1 discourages putting the
 
101
            # password in the url.
 
102
            hostinfo = '%s:%s@%s' % (urllib.quote(self.registrant_email),
 
103
                                     urllib.quote(self.registrant_password),
 
104
                                     hostinfo)
 
105
            url = urlunsplit((scheme, hostinfo, path, '', ''))
 
106
        else:
 
107
            url = self.service_url
 
108
        return xmlrpclib.ServerProxy(url, transport=self.transport)
 
109
 
 
110
    def gather_user_credentials(self):
 
111
        """Get the password from the user."""
 
112
        the_config = config.GlobalConfig()
 
113
        self.registrant_email = the_config.user_email()
 
114
        if self.registrant_password is None:
 
115
            auth = config.AuthenticationConfig()
 
116
            scheme, hostinfo = urlsplit(self.service_url)[:2]
 
117
            prompt = 'launchpad.net password for %s: ' % \
 
118
                    self.registrant_email
 
119
            # We will reuse http[s] credentials if we can, prompt user
 
120
            # otherwise
 
121
            self.registrant_password = auth.get_password(scheme, hostinfo,
 
122
                                                         self.registrant_email,
 
123
                                                         prompt=prompt)
 
124
 
 
125
    def send_request(self, method_name, method_params, authenticated):
 
126
        proxy = self.get_proxy(authenticated)
 
127
        assert method_name
 
128
        method = getattr(proxy, method_name)
 
129
        try:
 
130
            result = method(*method_params)
 
131
        except xmlrpclib.ProtocolError, e:
 
132
            if e.errcode == 301:
 
133
                # TODO: This can give a ProtocolError representing a 301 error, whose
 
134
                # e.headers['location'] tells where to go and e.errcode==301; should
 
135
                # probably log something and retry on the new url.
 
136
                raise NotImplementedError("should resend request to %s, but this isn't implemented"
 
137
                        % e.headers.get('Location', 'NO-LOCATION-PRESENT'))
 
138
            else:
 
139
                # we don't want to print the original message because its
 
140
                # str representation includes the plaintext password.
 
141
                # TODO: print more headers to help in tracking down failures
 
142
                raise errors.BzrError("xmlrpc protocol error connecting to %s: %s %s"
 
143
                        % (self.service_url, e.errcode, e.errmsg))
 
144
        return result
 
145
 
 
146
 
 
147
class BaseRequest(object):
 
148
    """Base request for talking to a XMLRPC server."""
 
149
 
 
150
    # Set this to the XMLRPC method name.
 
151
    _methodname = None
 
152
    _authenticated = True
 
153
 
 
154
    def _request_params(self):
 
155
        """Return the arguments to pass to the method"""
 
156
        raise NotImplementedError(self._request_params)
 
157
 
 
158
    def submit(self, service):
 
159
        """Submit request to Launchpad XMLRPC server.
 
160
 
 
161
        :param service: LaunchpadService indicating where to send
 
162
            the request and the authentication credentials.
 
163
        """
 
164
        return service.send_request(self._methodname, self._request_params(),
 
165
                                    self._authenticated)
 
166
 
 
167
 
 
168
class DryRunLaunchpadService(LaunchpadService):
 
169
    """Service that just absorbs requests without sending to server.
 
170
    
 
171
    The dummy service does not need authentication.
 
172
    """
 
173
 
 
174
    def send_request(self, method_name, method_params, authenticated):
 
175
        pass
 
176
 
 
177
    def gather_user_credentials(self):
 
178
        pass
 
179
 
 
180
 
 
181
class BranchRegistrationRequest(BaseRequest):
 
182
    """Request to tell Launchpad about a bzr branch."""
 
183
 
 
184
    _methodname = 'register_branch'
 
185
 
 
186
    def __init__(self, branch_url,
 
187
                 branch_name='',
 
188
                 branch_title='',
 
189
                 branch_description='',
 
190
                 author_email='',
 
191
                 product_name='',
 
192
                 ):
 
193
        assert branch_url
 
194
        self.branch_url = branch_url
 
195
        if branch_name:
 
196
            self.branch_name = branch_name
 
197
        else:
 
198
            self.branch_name = self._find_default_branch_name(self.branch_url)
 
199
        self.branch_title = branch_title
 
200
        self.branch_description = branch_description
 
201
        self.author_email = author_email
 
202
        self.product_name = product_name
 
203
 
 
204
    def _request_params(self):
 
205
        """Return xmlrpc request parameters"""
 
206
        # This must match the parameter tuple expected by Launchpad for this
 
207
        # method
 
208
        return (self.branch_url,
 
209
                self.branch_name,
 
210
                self.branch_title,
 
211
                self.branch_description,
 
212
                self.author_email,
 
213
                self.product_name,
 
214
               )
 
215
 
 
216
    def _find_default_branch_name(self, branch_url):
 
217
        i = branch_url.rfind('/')
 
218
        return branch_url[i+1:]
 
219
 
 
220
 
 
221
class BranchBugLinkRequest(BaseRequest):
 
222
    """Request to link a bzr branch in Launchpad to a bug."""
 
223
 
 
224
    _methodname = 'link_branch_to_bug'
 
225
 
 
226
    def __init__(self, branch_url, bug_id):
 
227
        assert branch_url
 
228
        self.bug_id = bug_id
 
229
        self.branch_url = branch_url
 
230
 
 
231
    def _request_params(self):
 
232
        """Return xmlrpc request parameters"""
 
233
        # This must match the parameter tuple expected by Launchpad for this
 
234
        # method
 
235
        return (self.branch_url, self.bug_id, '')
 
236
 
 
237
 
 
238
class ResolveLaunchpadPathRequest(BaseRequest):
 
239
    """Request to resolve the path component of an lp: URL."""
 
240
 
 
241
    _methodname = 'resolve_lp_path'
 
242
    _authenticated = False
 
243
 
 
244
    def __init__(self, path):
 
245
        assert path
 
246
        self.path = path
 
247
 
 
248
    def _request_params(self):
 
249
        """Return xmlrpc request parameters"""
 
250
        return (self.path,)