szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 1 | # Copyright (c) 2013 The Chromium OS Authors. All rights reserved. |
| 2 | # Use of this source code is governed by a BSD-style license that can be |
| 3 | # found in the LICENSE file. |
| 4 | |
| 5 | """ |
| 6 | Utilities for requesting information for a gerrit server via https. |
| 7 | |
| 8 | https://gerrit-review.googlesource.com/Documentation/rest-api.html |
| 9 | """ |
| 10 | |
| 11 | import base64 |
Dan Jacques | 8d11e48 | 2016-11-15 14:25:56 -0800 | [diff] [blame] | 12 | import contextlib |
phajdan.jr@chromium.org | ff7840a | 2015-11-04 16:35:22 +0000 | [diff] [blame] | 13 | import cookielib |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 14 | import httplib # Still used for its constants. |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 15 | import json |
| 16 | import logging |
| 17 | import netrc |
| 18 | import os |
nodir@chromium.org | ce32b6e | 2014-05-12 20:31:32 +0000 | [diff] [blame] | 19 | import re |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 20 | import socket |
szager@chromium.org | f202a25 | 2014-05-27 18:55:52 +0000 | [diff] [blame] | 21 | import stat |
| 22 | import sys |
Dan Jacques | 8d11e48 | 2016-11-15 14:25:56 -0800 | [diff] [blame] | 23 | import tempfile |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 24 | import time |
| 25 | import urllib |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 26 | import urlparse |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 27 | from cStringIO import StringIO |
| 28 | |
Dan Jacques | 8d11e48 | 2016-11-15 14:25:56 -0800 | [diff] [blame] | 29 | import gclient_utils |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 30 | from third_party import httplib2 |
szager@chromium.org | f202a25 | 2014-05-27 18:55:52 +0000 | [diff] [blame] | 31 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 32 | LOGGER = logging.getLogger() |
| 33 | TRY_LIMIT = 5 |
| 34 | |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 35 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 36 | # Controls the transport protocol used to communicate with gerrit. |
| 37 | # This is parameterized primarily to enable GerritTestCase. |
| 38 | GERRIT_PROTOCOL = 'https' |
| 39 | |
| 40 | |
| 41 | class GerritError(Exception): |
| 42 | """Exception class for errors commuicating with the gerrit-on-borg service.""" |
| 43 | def __init__(self, http_status, *args, **kwargs): |
| 44 | super(GerritError, self).__init__(*args, **kwargs) |
| 45 | self.http_status = http_status |
| 46 | self.message = '(%d) %s' % (self.http_status, self.message) |
| 47 | |
| 48 | |
nodir@chromium.org | ce32b6e | 2014-05-12 20:31:32 +0000 | [diff] [blame] | 49 | class GerritAuthenticationError(GerritError): |
| 50 | """Exception class for authentication errors during Gerrit communication.""" |
| 51 | |
| 52 | |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 53 | def _QueryString(params, first_param=None): |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 54 | """Encodes query parameters in the key:val[+key:val...] format specified here: |
| 55 | |
| 56 | https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes |
| 57 | """ |
| 58 | q = [urllib.quote(first_param)] if first_param else [] |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 59 | q.extend(['%s:%s' % (key, val) for key, val in params]) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 60 | return '+'.join(q) |
| 61 | |
| 62 | |
Aaron Gable | d2db5a2 | 2017-03-24 14:14:15 -0700 | [diff] [blame] | 63 | def GetConnectionObject(protocol=None): |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 64 | if protocol is None: |
| 65 | protocol = GERRIT_PROTOCOL |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 66 | if protocol in ('http', 'https'): |
Aaron Gable | d2db5a2 | 2017-03-24 14:14:15 -0700 | [diff] [blame] | 67 | return httplib2.Http() |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 68 | else: |
| 69 | raise RuntimeError( |
| 70 | "Don't know how to work with protocol '%s'" % protocol) |
| 71 | |
| 72 | |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 73 | class Authenticator(object): |
| 74 | """Base authenticator class for authenticator implementations to subclass.""" |
| 75 | |
| 76 | def get_auth_header(self, host): |
| 77 | raise NotImplementedError() |
| 78 | |
| 79 | @staticmethod |
| 80 | def get(): |
| 81 | """Returns: (Authenticator) The identified Authenticator to use. |
| 82 | |
| 83 | Probes the local system and its environment and identifies the |
| 84 | Authenticator instance to use. |
| 85 | """ |
| 86 | if GceAuthenticator.is_gce(): |
| 87 | return GceAuthenticator() |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 88 | return CookiesAuthenticator() |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 89 | |
| 90 | |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 91 | class CookiesAuthenticator(Authenticator): |
| 92 | """Authenticator implementation that uses ".netrc" or ".gitcookies" for token. |
| 93 | |
| 94 | Expected case for developer workstations. |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 95 | """ |
| 96 | |
| 97 | def __init__(self): |
| 98 | self.netrc = self._get_netrc() |
phajdan.jr@chromium.org | ff7840a | 2015-11-04 16:35:22 +0000 | [diff] [blame] | 99 | self.gitcookies = self._get_gitcookies() |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 100 | |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 101 | @classmethod |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 102 | def get_new_password_url(cls, host): |
| 103 | assert not host.startswith('http') |
| 104 | # Assume *.googlesource.com pattern. |
| 105 | parts = host.split('.') |
| 106 | if not parts[0].endswith('-review'): |
| 107 | parts[0] += '-review' |
| 108 | return 'https://%s/new-password' % ('.'.join(parts)) |
| 109 | |
| 110 | @classmethod |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 111 | def get_new_password_message(cls, host): |
| 112 | assert not host.startswith('http') |
| 113 | # Assume *.googlesource.com pattern. |
| 114 | parts = host.split('.') |
| 115 | if not parts[0].endswith('-review'): |
| 116 | parts[0] += '-review' |
| 117 | url = 'https://%s/new-password' % ('.'.join(parts)) |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 118 | return 'You can (re)generate your credentials by visiting %s' % url |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 119 | |
| 120 | @classmethod |
| 121 | def get_netrc_path(cls): |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 122 | path = '_netrc' if sys.platform.startswith('win') else '.netrc' |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 123 | return os.path.expanduser(os.path.join('~', path)) |
| 124 | |
| 125 | @classmethod |
| 126 | def _get_netrc(cls): |
Dan Jacques | 8d11e48 | 2016-11-15 14:25:56 -0800 | [diff] [blame] | 127 | # Buffer the '.netrc' path. Use an empty file if it doesn't exist. |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 128 | path = cls.get_netrc_path() |
Dan Jacques | 8d11e48 | 2016-11-15 14:25:56 -0800 | [diff] [blame] | 129 | content = '' |
| 130 | if os.path.exists(path): |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 131 | st = os.stat(path) |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 132 | if st.st_mode & (stat.S_IRWXG | stat.S_IRWXO): |
| 133 | print >> sys.stderr, ( |
| 134 | 'WARNING: netrc file %s cannot be used because its file ' |
| 135 | 'permissions are insecure. netrc file permissions should be ' |
| 136 | '600.' % path) |
Dan Jacques | 8d11e48 | 2016-11-15 14:25:56 -0800 | [diff] [blame] | 137 | with open(path) as fd: |
| 138 | content = fd.read() |
| 139 | |
| 140 | # Load the '.netrc' file. We strip comments from it because processing them |
| 141 | # can trigger a bug in Windows. See crbug.com/664664. |
| 142 | content = '\n'.join(l for l in content.splitlines() |
| 143 | if l.strip() and not l.strip().startswith('#')) |
| 144 | with tempdir() as tdir: |
| 145 | netrc_path = os.path.join(tdir, 'netrc') |
| 146 | with open(netrc_path, 'w') as fd: |
| 147 | fd.write(content) |
| 148 | os.chmod(netrc_path, (stat.S_IRUSR | stat.S_IWUSR)) |
| 149 | return cls._get_netrc_from_path(netrc_path) |
| 150 | |
| 151 | @classmethod |
| 152 | def _get_netrc_from_path(cls, path): |
| 153 | try: |
| 154 | return netrc.netrc(path) |
| 155 | except IOError: |
| 156 | print >> sys.stderr, 'WARNING: Could not read netrc file %s' % path |
| 157 | return netrc.netrc(os.devnull) |
| 158 | except netrc.NetrcParseError as e: |
| 159 | print >> sys.stderr, ('ERROR: Cannot use netrc file %s due to a ' |
| 160 | 'parsing error: %s' % (path, e)) |
| 161 | return netrc.netrc(os.devnull) |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 162 | |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 163 | @classmethod |
| 164 | def get_gitcookies_path(cls): |
Ravi Mistry | 0bfa9ad | 2016-11-21 12:58:31 -0500 | [diff] [blame] | 165 | if os.getenv('GIT_COOKIES_PATH'): |
| 166 | return os.getenv('GIT_COOKIES_PATH') |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 167 | return os.path.join(os.environ['HOME'], '.gitcookies') |
| 168 | |
| 169 | @classmethod |
| 170 | def _get_gitcookies(cls): |
phajdan.jr@chromium.org | ff7840a | 2015-11-04 16:35:22 +0000 | [diff] [blame] | 171 | gitcookies = {} |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 172 | path = cls.get_gitcookies_path() |
| 173 | if not os.path.exists(path): |
| 174 | return gitcookies |
| 175 | |
phajdan.jr@chromium.org | ff7840a | 2015-11-04 16:35:22 +0000 | [diff] [blame] | 176 | try: |
| 177 | f = open(path, 'rb') |
| 178 | except IOError: |
| 179 | return gitcookies |
| 180 | |
| 181 | with f: |
| 182 | for line in f: |
| 183 | try: |
| 184 | fields = line.strip().split('\t') |
| 185 | if line.strip().startswith('#') or len(fields) != 7: |
| 186 | continue |
| 187 | domain, xpath, key, value = fields[0], fields[2], fields[5], fields[6] |
| 188 | if xpath == '/' and key == 'o': |
| 189 | login, secret_token = value.split('=', 1) |
| 190 | gitcookies[domain] = (login, secret_token) |
| 191 | except (IndexError, ValueError, TypeError) as exc: |
Andrii Shyshkalov | 5b04a57 | 2017-01-23 17:44:41 +0100 | [diff] [blame] | 192 | LOGGER.warning(exc) |
phajdan.jr@chromium.org | ff7840a | 2015-11-04 16:35:22 +0000 | [diff] [blame] | 193 | |
| 194 | return gitcookies |
| 195 | |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 196 | def _get_auth_for_host(self, host): |
phajdan.jr@chromium.org | ff7840a | 2015-11-04 16:35:22 +0000 | [diff] [blame] | 197 | for domain, creds in self.gitcookies.iteritems(): |
| 198 | if cookielib.domain_match(host, domain): |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 199 | return (creds[0], None, creds[1]) |
| 200 | return self.netrc.authenticators(host) |
phajdan.jr@chromium.org | ff7840a | 2015-11-04 16:35:22 +0000 | [diff] [blame] | 201 | |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 202 | def get_auth_header(self, host): |
| 203 | auth = self._get_auth_for_host(host) |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 204 | if auth: |
| 205 | return 'Basic %s' % (base64.b64encode('%s:%s' % (auth[0], auth[2]))) |
| 206 | return None |
| 207 | |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 208 | def get_auth_email(self, host): |
| 209 | """Best effort parsing of email to be used for auth for the given host.""" |
| 210 | auth = self._get_auth_for_host(host) |
| 211 | if not auth: |
| 212 | return None |
| 213 | login = auth[0] |
| 214 | # login typically looks like 'git-xxx.example.com' |
| 215 | if not login.startswith('git-') or '.' not in login: |
| 216 | return None |
| 217 | username, domain = login[len('git-'):].split('.', 1) |
| 218 | return '%s@%s' % (username, domain) |
| 219 | |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 220 | |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 221 | # Backwards compatibility just in case somebody imports this outside of |
| 222 | # depot_tools. |
| 223 | NetrcAuthenticator = CookiesAuthenticator |
| 224 | |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 225 | |
| 226 | class GceAuthenticator(Authenticator): |
| 227 | """Authenticator implementation that uses GCE metadata service for token. |
| 228 | """ |
| 229 | |
| 230 | _INFO_URL = 'http://metadata.google.internal' |
smut | 5e9401b | 2017-08-10 15:22:20 -0700 | [diff] [blame] | 231 | _ACQUIRE_URL = ('%s/computeMetadata/v1/instance/' |
| 232 | 'service-accounts/default/token' % _INFO_URL) |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 233 | _ACQUIRE_HEADERS = {"Metadata-Flavor": "Google"} |
| 234 | |
| 235 | _cache_is_gce = None |
| 236 | _token_cache = None |
| 237 | _token_expiration = None |
| 238 | |
| 239 | @classmethod |
| 240 | def is_gce(cls): |
Ravi Mistry | fad941b | 2016-11-15 13:00:47 -0500 | [diff] [blame] | 241 | if os.getenv('SKIP_GCE_AUTH_FOR_GIT'): |
| 242 | return False |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 243 | if cls._cache_is_gce is None: |
| 244 | cls._cache_is_gce = cls._test_is_gce() |
| 245 | return cls._cache_is_gce |
| 246 | |
| 247 | @classmethod |
| 248 | def _test_is_gce(cls): |
| 249 | # Based on https://cloud.google.com/compute/docs/metadata#runninggce |
| 250 | try: |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 251 | resp, _ = cls._get(cls._INFO_URL) |
| 252 | except (socket.error, httplib2.ServerNotFoundError): |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 253 | # Could not resolve URL. |
| 254 | return False |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 255 | return resp.get('metadata-flavor') == 'Google' |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 256 | |
| 257 | @staticmethod |
| 258 | def _get(url, **kwargs): |
| 259 | next_delay_sec = 1 |
| 260 | for i in xrange(TRY_LIMIT): |
| 261 | if i > 0: |
| 262 | # Retry server error status codes. |
| 263 | LOGGER.info('Encountered server error; retrying after %d second(s).', |
| 264 | next_delay_sec) |
| 265 | time.sleep(next_delay_sec) |
| 266 | next_delay_sec *= 2 |
| 267 | |
| 268 | p = urlparse.urlparse(url) |
Aaron Gable | d2db5a2 | 2017-03-24 14:14:15 -0700 | [diff] [blame] | 269 | c = GetConnectionObject(protocol=p.scheme) |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 270 | resp, contents = c.request(url, 'GET', **kwargs) |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 271 | LOGGER.debug('GET [%s] #%d/%d (%d)', url, i+1, TRY_LIMIT, resp.status) |
| 272 | if resp.status < httplib.INTERNAL_SERVER_ERROR: |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 273 | return (resp, contents) |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 274 | |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 275 | @classmethod |
| 276 | def _get_token_dict(cls): |
| 277 | if cls._token_cache: |
| 278 | # If it expires within 25 seconds, refresh. |
| 279 | if cls._token_expiration < time.time() - 25: |
| 280 | return cls._token_cache |
| 281 | |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 282 | resp, contents = cls._get(cls._ACQUIRE_URL, headers=cls._ACQUIRE_HEADERS) |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 283 | if resp.status != httplib.OK: |
| 284 | return None |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 285 | cls._token_cache = json.loads(contents) |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 286 | cls._token_expiration = cls._token_cache['expires_in'] + time.time() |
| 287 | return cls._token_cache |
| 288 | |
| 289 | def get_auth_header(self, _host): |
| 290 | token_dict = self._get_token_dict() |
| 291 | if not token_dict: |
| 292 | return None |
| 293 | return '%(token_type)s %(access_token)s' % token_dict |
| 294 | |
| 295 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 296 | def CreateHttpConn(host, path, reqtype='GET', headers=None, body=None): |
| 297 | """Opens an https connection to a gerrit service, and sends a request.""" |
| 298 | headers = headers or {} |
| 299 | bare_host = host.partition(':')[0] |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 300 | |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 301 | auth = Authenticator.get().get_auth_header(bare_host) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 302 | if auth: |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 303 | headers.setdefault('Authorization', auth) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 304 | else: |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 305 | LOGGER.debug('No authorization found for %s.' % bare_host) |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 306 | |
Dan Jacques | 6d5bcc2 | 2016-11-14 15:32:04 -0800 | [diff] [blame] | 307 | url = path |
| 308 | if not url.startswith('/'): |
| 309 | url = '/' + url |
| 310 | if 'Authorization' in headers and not url.startswith('/a/'): |
| 311 | url = '/a%s' % url |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 312 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 313 | if body: |
| 314 | body = json.JSONEncoder().encode(body) |
| 315 | headers.setdefault('Content-Type', 'application/json') |
| 316 | if LOGGER.isEnabledFor(logging.DEBUG): |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 317 | LOGGER.debug('%s %s://%s%s' % (reqtype, GERRIT_PROTOCOL, host, url)) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 318 | for key, val in headers.iteritems(): |
| 319 | if key == 'Authorization': |
| 320 | val = 'HIDDEN' |
| 321 | LOGGER.debug('%s: %s' % (key, val)) |
| 322 | if body: |
| 323 | LOGGER.debug(body) |
Aaron Gable | d2db5a2 | 2017-03-24 14:14:15 -0700 | [diff] [blame] | 324 | conn = GetConnectionObject() |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 325 | conn.req_host = host |
| 326 | conn.req_params = { |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 327 | 'uri': urlparse.urljoin('%s://%s' % (GERRIT_PROTOCOL, host), url), |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 328 | 'method': reqtype, |
| 329 | 'headers': headers, |
| 330 | 'body': body, |
| 331 | } |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 332 | return conn |
| 333 | |
| 334 | |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 335 | def ReadHttpResponse(conn, accept_statuses=frozenset([200])): |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 336 | """Reads an http response from a connection into a string buffer. |
| 337 | |
| 338 | Args: |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 339 | conn: An Http object created by CreateHttpConn above. |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 340 | accept_statuses: Treat any of these statuses as success. Default: [200] |
| 341 | Common additions include 204, 400, and 404. |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 342 | Returns: A string buffer containing the connection's reply. |
| 343 | """ |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 344 | sleep_time = 0.5 |
| 345 | for idx in range(TRY_LIMIT): |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 346 | response, contents = conn.request(**conn.req_params) |
nodir@chromium.org | ce32b6e | 2014-05-12 20:31:32 +0000 | [diff] [blame] | 347 | |
| 348 | # Check if this is an authentication issue. |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 349 | www_authenticate = response.get('www-authenticate') |
nodir@chromium.org | ce32b6e | 2014-05-12 20:31:32 +0000 | [diff] [blame] | 350 | if (response.status in (httplib.UNAUTHORIZED, httplib.FOUND) and |
| 351 | www_authenticate): |
| 352 | auth_match = re.search('realm="([^"]+)"', www_authenticate, re.I) |
| 353 | host = auth_match.group(1) if auth_match else conn.req_host |
Aaron Gable | 19ee16c | 2017-04-18 11:56:35 -0700 | [diff] [blame] | 354 | reason = ('Authentication failed. Please make sure your .gitcookies file ' |
nodir@chromium.org | ce32b6e | 2014-05-12 20:31:32 +0000 | [diff] [blame] | 355 | 'has credentials for %s' % host) |
| 356 | raise GerritAuthenticationError(response.status, reason) |
| 357 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 358 | # If response.status < 500 then the result is final; break retry loop. |
Aaron Gable | 62ca960 | 2017-05-19 17:24:52 -0700 | [diff] [blame] | 359 | # If the response is 404, it might be because of replication lag, so |
| 360 | # keep trying anyway. |
Michael Moss | b40a451 | 2017-10-10 11:07:17 -0700 | [diff] [blame] | 361 | if ((response.status < 500 and response.status != 404) |
| 362 | or response.status in accept_statuses): |
Andrii Shyshkalov | 5b04a57 | 2017-01-23 17:44:41 +0100 | [diff] [blame] | 363 | LOGGER.debug('got response %d for %s %s', response.status, |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 364 | conn.req_params['method'], conn.req_params['uri']) |
Michael Moss | b40a451 | 2017-10-10 11:07:17 -0700 | [diff] [blame] | 365 | # If 404 was in accept_statuses, then it's expected that the file might |
| 366 | # not exist, so don't return the gitiles error page because that's not the |
| 367 | # "content" that was actually requested. |
| 368 | if response.status == 404: |
| 369 | contents = '' |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 370 | break |
| 371 | # A status >=500 is assumed to be a possible transient error; retry. |
| 372 | http_version = 'HTTP/%s' % ('1.1' if response.version == 11 else '1.0') |
Andrii Shyshkalov | 5b04a57 | 2017-01-23 17:44:41 +0100 | [diff] [blame] | 373 | LOGGER.warn('A transient error occurred while querying %s:\n' |
| 374 | '%s %s %s\n' |
| 375 | '%s %d %s', |
Aaron Gable | 20d2cbb | 2017-04-25 15:04:05 -0700 | [diff] [blame] | 376 | conn.req_host, conn.req_params['method'], |
| 377 | conn.req_params['uri'], |
Andrii Shyshkalov | 5b04a57 | 2017-01-23 17:44:41 +0100 | [diff] [blame] | 378 | http_version, http_version, response.status, response.reason) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 379 | if TRY_LIMIT - idx > 1: |
Andrii Shyshkalov | 5b04a57 | 2017-01-23 17:44:41 +0100 | [diff] [blame] | 380 | LOGGER.warn('... will retry %d more times.', TRY_LIMIT - idx - 1) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 381 | time.sleep(sleep_time) |
| 382 | sleep_time = sleep_time * 2 |
Aaron Gable | 19ee16c | 2017-04-18 11:56:35 -0700 | [diff] [blame] | 383 | if response.status not in accept_statuses: |
Andrii Shyshkalov | 4956f79 | 2017-04-10 14:28:38 +0200 | [diff] [blame] | 384 | if response.status in (401, 403): |
| 385 | print('Your Gerrit credentials might be misconfigured. Try: \n' |
| 386 | ' git cl creds-check') |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 387 | reason = '%s: %s' % (response.reason, contents) |
nodir@chromium.org | a779803 | 2014-04-30 23:40:53 +0000 | [diff] [blame] | 388 | raise GerritError(response.status, reason) |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 389 | return StringIO(contents) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 390 | |
| 391 | |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 392 | def ReadHttpJsonResponse(conn, accept_statuses=frozenset([200])): |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 393 | """Parses an https response as json.""" |
Aaron Gable | 19ee16c | 2017-04-18 11:56:35 -0700 | [diff] [blame] | 394 | fh = ReadHttpResponse(conn, accept_statuses) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 395 | # The first line of the response should always be: )]}' |
| 396 | s = fh.readline() |
| 397 | if s and s.rstrip() != ")]}'": |
| 398 | raise GerritError(200, 'Unexpected json output: %s' % s) |
| 399 | s = fh.read() |
| 400 | if not s: |
| 401 | return None |
| 402 | return json.loads(s) |
| 403 | |
| 404 | |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 405 | def QueryChanges(host, params, first_param=None, limit=None, o_params=None, |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 406 | start=None): |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 407 | """ |
| 408 | Queries a gerrit-on-borg server for changes matching query terms. |
| 409 | |
| 410 | Args: |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 411 | params: A list of key:value pairs for search parameters, as documented |
| 412 | here (e.g. ('is', 'owner') for a parameter 'is:owner'): |
| 413 | https://gerrit-review.googlesource.com/Documentation/user-search.html#search-operators |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 414 | first_param: A change identifier |
| 415 | limit: Maximum number of results to return. |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 416 | start: how many changes to skip (starting with the most recent) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 417 | o_params: A list of additional output specifiers, as documented here: |
| 418 | https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes |
| 419 | Returns: |
| 420 | A list of json-decoded query results. |
| 421 | """ |
| 422 | # Note that no attempt is made to escape special characters; YMMV. |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 423 | if not params and not first_param: |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 424 | raise RuntimeError('QueryChanges requires search parameters') |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 425 | path = 'changes/?q=%s' % _QueryString(params, first_param) |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 426 | if start: |
| 427 | path = '%s&start=%s' % (path, start) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 428 | if limit: |
| 429 | path = '%s&n=%d' % (path, limit) |
| 430 | if o_params: |
| 431 | path = '%s&%s' % (path, '&'.join(['o=%s' % p for p in o_params])) |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 432 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 433 | |
| 434 | |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 435 | def GenerateAllChanges(host, params, first_param=None, limit=500, |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 436 | o_params=None, start=None): |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 437 | """ |
| 438 | Queries a gerrit-on-borg server for all the changes matching the query terms. |
| 439 | |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 440 | WARNING: this is unreliable if a change matching the query is modified while |
| 441 | this function is being called. |
| 442 | |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 443 | A single query to gerrit-on-borg is limited on the number of results by the |
| 444 | limit parameter on the request (see QueryChanges) and the server maximum |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 445 | limit. |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 446 | |
| 447 | Args: |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 448 | params, first_param: Refer to QueryChanges(). |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 449 | limit: Maximum number of requested changes per query. |
| 450 | o_params: Refer to QueryChanges(). |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 451 | start: Refer to QueryChanges(). |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 452 | |
| 453 | Returns: |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 454 | A generator object to the list of returned changes. |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 455 | """ |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 456 | already_returned = set() |
| 457 | def at_most_once(cls): |
| 458 | for cl in cls: |
| 459 | if cl['_number'] not in already_returned: |
| 460 | already_returned.add(cl['_number']) |
| 461 | yield cl |
| 462 | |
| 463 | start = start or 0 |
| 464 | cur_start = start |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 465 | more_changes = True |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 466 | |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 467 | while more_changes: |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 468 | # This will fetch changes[start..start+limit] sorted by most recently |
| 469 | # updated. Since the rank of any change in this list can be changed any time |
| 470 | # (say user posting comment), subsequent calls may overalp like this: |
| 471 | # > initial order ABCDEFGH |
| 472 | # query[0..3] => ABC |
| 473 | # > E get's updated. New order: EABCDFGH |
| 474 | # query[3..6] => CDF # C is a dup |
| 475 | # query[6..9] => GH # E is missed. |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 476 | page = QueryChanges(host, params, first_param, limit, o_params, |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 477 | cur_start) |
| 478 | for cl in at_most_once(page): |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 479 | yield cl |
| 480 | |
| 481 | more_changes = [cl for cl in page if '_more_changes' in cl] |
| 482 | if len(more_changes) > 1: |
| 483 | raise GerritError( |
| 484 | 200, |
| 485 | 'Received %d changes with a _more_changes attribute set but should ' |
| 486 | 'receive at most one.' % len(more_changes)) |
| 487 | if more_changes: |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 488 | cur_start += len(page) |
| 489 | |
| 490 | # If we paged through, query again the first page which in most circumstances |
| 491 | # will fetch all changes that were modified while this function was run. |
| 492 | if start != cur_start: |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 493 | page = QueryChanges(host, params, first_param, limit, o_params, start) |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 494 | for cl in at_most_once(page): |
| 495 | yield cl |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 496 | |
| 497 | |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 498 | def MultiQueryChanges(host, params, change_list, limit=None, o_params=None, |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 499 | start=None): |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 500 | """Initiate a query composed of multiple sets of query parameters.""" |
| 501 | if not change_list: |
| 502 | raise RuntimeError( |
| 503 | "MultiQueryChanges requires a list of change numbers/id's") |
| 504 | q = ['q=%s' % '+OR+'.join([urllib.quote(str(x)) for x in change_list])] |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 505 | if params: |
| 506 | q.append(_QueryString(params)) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 507 | if limit: |
| 508 | q.append('n=%d' % limit) |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 509 | if start: |
| 510 | q.append('S=%s' % start) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 511 | if o_params: |
| 512 | q.extend(['o=%s' % p for p in o_params]) |
| 513 | path = 'changes/?%s' % '&'.join(q) |
| 514 | try: |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 515 | result = ReadHttpJsonResponse(CreateHttpConn(host, path)) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 516 | except GerritError as e: |
| 517 | msg = '%s:\n%s' % (e.message, path) |
| 518 | raise GerritError(e.http_status, msg) |
| 519 | return result |
| 520 | |
| 521 | |
| 522 | def GetGerritFetchUrl(host): |
| 523 | """Given a gerrit host name returns URL of a gerrit instance to fetch from.""" |
| 524 | return '%s://%s/' % (GERRIT_PROTOCOL, host) |
| 525 | |
| 526 | |
| 527 | def GetChangePageUrl(host, change_number): |
| 528 | """Given a gerrit host name and change number, return change page url.""" |
| 529 | return '%s://%s/#/c/%d/' % (GERRIT_PROTOCOL, host, change_number) |
| 530 | |
| 531 | |
| 532 | def GetChangeUrl(host, change): |
| 533 | """Given a gerrit host name and change id, return an url for the change.""" |
| 534 | return '%s://%s/a/changes/%s' % (GERRIT_PROTOCOL, host, change) |
| 535 | |
| 536 | |
| 537 | def GetChange(host, change): |
| 538 | """Query a gerrit server for information about a single change.""" |
| 539 | path = 'changes/%s' % change |
| 540 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
| 541 | |
| 542 | |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 543 | def GetChangeDetail(host, change, o_params=None): |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 544 | """Query a gerrit server for extended information about a single change.""" |
| 545 | path = 'changes/%s/detail' % change |
| 546 | if o_params: |
| 547 | path += '?%s' % '&'.join(['o=%s' % p for p in o_params]) |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 548 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 549 | |
| 550 | |
agable | 32978d9 | 2016-11-01 12:55:02 -0700 | [diff] [blame] | 551 | def GetChangeCommit(host, change, revision='current'): |
| 552 | """Query a gerrit server for a revision associated with a change.""" |
| 553 | path = 'changes/%s/revisions/%s/commit?links' % (change, revision) |
| 554 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
| 555 | |
| 556 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 557 | def GetChangeCurrentRevision(host, change): |
| 558 | """Get information about the latest revision for a given change.""" |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 559 | return QueryChanges(host, [], change, o_params=('CURRENT_REVISION',)) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 560 | |
| 561 | |
| 562 | def GetChangeRevisions(host, change): |
| 563 | """Get information about all revisions associated with a change.""" |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 564 | return QueryChanges(host, [], change, o_params=('ALL_REVISIONS',)) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 565 | |
| 566 | |
| 567 | def GetChangeReview(host, change, revision=None): |
| 568 | """Get the current review information for a change.""" |
| 569 | if not revision: |
| 570 | jmsg = GetChangeRevisions(host, change) |
| 571 | if not jmsg: |
| 572 | return None |
| 573 | elif len(jmsg) > 1: |
| 574 | raise GerritError(200, 'Multiple changes found for ChangeId %s.' % change) |
| 575 | revision = jmsg[0]['current_revision'] |
| 576 | path = 'changes/%s/revisions/%s/review' |
| 577 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
| 578 | |
| 579 | |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 580 | def GetChangeComments(host, change): |
| 581 | """Get the line- and file-level comments on a change.""" |
| 582 | path = 'changes/%s/comments' % change |
| 583 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
| 584 | |
| 585 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 586 | def AbandonChange(host, change, msg=''): |
| 587 | """Abandon a gerrit change.""" |
| 588 | path = 'changes/%s/abandon' % change |
tandrii@chromium.org | c7da66a | 2016-03-24 09:52:24 +0000 | [diff] [blame] | 589 | body = {'message': msg} if msg else {} |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 590 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 591 | return ReadHttpJsonResponse(conn) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 592 | |
| 593 | |
| 594 | def RestoreChange(host, change, msg=''): |
| 595 | """Restore a previously abandoned change.""" |
| 596 | path = 'changes/%s/restore' % change |
tandrii@chromium.org | c7da66a | 2016-03-24 09:52:24 +0000 | [diff] [blame] | 597 | body = {'message': msg} if msg else {} |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 598 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 599 | return ReadHttpJsonResponse(conn) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 600 | |
| 601 | |
| 602 | def SubmitChange(host, change, wait_for_merge=True): |
| 603 | """Submits a gerrit change via Gerrit.""" |
| 604 | path = 'changes/%s/submit' % change |
| 605 | body = {'wait_for_merge': wait_for_merge} |
| 606 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 607 | return ReadHttpJsonResponse(conn) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 608 | |
| 609 | |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 610 | def HasPendingChangeEdit(host, change): |
| 611 | conn = CreateHttpConn(host, 'changes/%s/edit' % change) |
| 612 | try: |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 613 | ReadHttpResponse(conn) |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 614 | except GerritError as e: |
Aaron Gable | 19ee16c | 2017-04-18 11:56:35 -0700 | [diff] [blame] | 615 | # 204 No Content means no pending change. |
| 616 | if e.http_status == 204: |
| 617 | return False |
| 618 | raise |
| 619 | return True |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 620 | |
| 621 | |
| 622 | def DeletePendingChangeEdit(host, change): |
| 623 | conn = CreateHttpConn(host, 'changes/%s/edit' % change, reqtype='DELETE') |
Aaron Gable | 19ee16c | 2017-04-18 11:56:35 -0700 | [diff] [blame] | 624 | # On success, gerrit returns status 204; if the edit was already deleted it |
| 625 | # returns 404. Anything else is an error. |
| 626 | ReadHttpResponse(conn, accept_statuses=[204, 404]) |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 627 | |
| 628 | |
Andrii Shyshkalov | ea4fc83 | 2016-12-01 14:53:23 +0100 | [diff] [blame] | 629 | def SetCommitMessage(host, change, description, notify='ALL'): |
scottmg@chromium.org | 6d1266e | 2016-04-26 11:12:26 +0000 | [diff] [blame] | 630 | """Updates a commit message.""" |
Aaron Gable | 7625d88 | 2017-06-26 09:47:26 -0700 | [diff] [blame] | 631 | assert notify in ('ALL', 'NONE') |
| 632 | path = 'changes/%s/message' % change |
Aaron Gable | 5a4ef45 | 2017-08-24 13:19:56 -0700 | [diff] [blame] | 633 | body = {'message': description, 'notify': notify} |
Aaron Gable | 7625d88 | 2017-06-26 09:47:26 -0700 | [diff] [blame] | 634 | conn = CreateHttpConn(host, path, reqtype='PUT', body=body) |
scottmg@chromium.org | 6d1266e | 2016-04-26 11:12:26 +0000 | [diff] [blame] | 635 | try: |
Aaron Gable | 7625d88 | 2017-06-26 09:47:26 -0700 | [diff] [blame] | 636 | ReadHttpResponse(conn, accept_statuses=[200, 204]) |
| 637 | except GerritError as e: |
| 638 | raise GerritError( |
| 639 | e.http_status, |
| 640 | 'Received unexpected http status while editing message ' |
| 641 | 'in change %s' % change) |
scottmg@chromium.org | 6d1266e | 2016-04-26 11:12:26 +0000 | [diff] [blame] | 642 | |
| 643 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 644 | def GetReviewers(host, change): |
| 645 | """Get information about all reviewers attached to a change.""" |
| 646 | path = 'changes/%s/reviewers' % change |
| 647 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
| 648 | |
| 649 | |
| 650 | def GetReview(host, change, revision): |
| 651 | """Get review information about a specific revision of a change.""" |
| 652 | path = 'changes/%s/revisions/%s/review' % (change, revision) |
| 653 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
| 654 | |
| 655 | |
Aaron Gable | 6dadfbf | 2017-05-09 14:27:58 -0700 | [diff] [blame] | 656 | def AddReviewers(host, change, reviewers=None, ccs=None, notify=True, |
| 657 | accept_statuses=frozenset([200, 400, 422])): |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 658 | """Add reviewers to a change.""" |
Aaron Gable | 6dadfbf | 2017-05-09 14:27:58 -0700 | [diff] [blame] | 659 | if not reviewers and not ccs: |
Aaron Gable | df86e30 | 2016-11-08 10:48:03 -0800 | [diff] [blame] | 660 | return None |
Wiktor Garbacz | 6d0d044 | 2017-05-15 12:34:40 +0200 | [diff] [blame] | 661 | if not change: |
| 662 | return None |
Aaron Gable | 6dadfbf | 2017-05-09 14:27:58 -0700 | [diff] [blame] | 663 | reviewers = frozenset(reviewers or []) |
| 664 | ccs = frozenset(ccs or []) |
| 665 | path = 'changes/%s/revisions/current/review' % change |
| 666 | |
| 667 | body = { |
| 668 | 'reviewers': [], |
| 669 | 'notify': 'ALL' if notify else 'NONE', |
| 670 | } |
| 671 | for r in sorted(reviewers | ccs): |
| 672 | state = 'REVIEWER' if r in reviewers else 'CC' |
| 673 | body['reviewers'].append({ |
| 674 | 'reviewer': r, |
| 675 | 'state': state, |
| 676 | 'notify': 'NONE', # We handled `notify` argument above. |
| 677 | }) |
| 678 | |
| 679 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
| 680 | # Gerrit will return 400 if one or more of the requested reviewers are |
| 681 | # unprocessable. We read the response object to see which were rejected, |
| 682 | # warn about them, and retry with the remainder. |
| 683 | resp = ReadHttpJsonResponse(conn, accept_statuses=accept_statuses) |
| 684 | |
| 685 | errored = set() |
| 686 | for result in resp.get('reviewers', {}).itervalues(): |
| 687 | r = result.get('input') |
| 688 | state = 'REVIEWER' if r in reviewers else 'CC' |
| 689 | if result.get('error'): |
| 690 | errored.add(r) |
| 691 | LOGGER.warn('Note: "%s" not added as a %s' % (r, state.lower())) |
| 692 | if errored: |
| 693 | # Try again, adding only those that didn't fail, and only accepting 200. |
| 694 | AddReviewers(host, change, reviewers=(reviewers-errored), |
| 695 | ccs=(ccs-errored), notify=notify, accept_statuses=[200]) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 696 | |
| 697 | |
| 698 | def RemoveReviewers(host, change, remove=None): |
| 699 | """Remove reveiewers from a change.""" |
| 700 | if not remove: |
| 701 | return |
| 702 | if isinstance(remove, basestring): |
| 703 | remove = (remove,) |
| 704 | for r in remove: |
| 705 | path = 'changes/%s/reviewers/%s' % (change, r) |
| 706 | conn = CreateHttpConn(host, path, reqtype='DELETE') |
| 707 | try: |
Aaron Gable | 19ee16c | 2017-04-18 11:56:35 -0700 | [diff] [blame] | 708 | ReadHttpResponse(conn, accept_statuses=[204]) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 709 | except GerritError as e: |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 710 | raise GerritError( |
Aaron Gable | 19ee16c | 2017-04-18 11:56:35 -0700 | [diff] [blame] | 711 | e.http_status, |
| 712 | 'Received unexpected http status while deleting reviewer "%s" ' |
| 713 | 'from change %s' % (r, change)) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 714 | |
| 715 | |
Aaron Gable | 636b13f | 2017-07-14 10:42:48 -0700 | [diff] [blame] | 716 | def SetReview(host, change, msg=None, labels=None, notify=None, ready=None): |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 717 | """Set labels and/or add a message to a code review.""" |
| 718 | if not msg and not labels: |
| 719 | return |
| 720 | path = 'changes/%s/revisions/current/review' % change |
| 721 | body = {} |
| 722 | if msg: |
| 723 | body['message'] = msg |
| 724 | if labels: |
| 725 | body['labels'] = labels |
Aaron Gable | fc62f76 | 2017-07-17 11:12:07 -0700 | [diff] [blame] | 726 | if notify is not None: |
Aaron Gable | 75e7872 | 2017-06-09 10:40:16 -0700 | [diff] [blame] | 727 | body['notify'] = 'ALL' if notify else 'NONE' |
Aaron Gable | 636b13f | 2017-07-14 10:42:48 -0700 | [diff] [blame] | 728 | if ready: |
| 729 | body['ready'] = True |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 730 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
| 731 | response = ReadHttpJsonResponse(conn) |
| 732 | if labels: |
| 733 | for key, val in labels.iteritems(): |
| 734 | if ('labels' not in response or key not in response['labels'] or |
| 735 | int(response['labels'][key] != int(val))): |
| 736 | raise GerritError(200, 'Unable to set "%s" label on change %s.' % ( |
| 737 | key, change)) |
| 738 | |
| 739 | |
| 740 | def ResetReviewLabels(host, change, label, value='0', message=None, |
| 741 | notify=None): |
| 742 | """Reset the value of a given label for all reviewers on a change.""" |
| 743 | # This is tricky, because we want to work on the "current revision", but |
| 744 | # there's always the risk that "current revision" will change in between |
| 745 | # API calls. So, we check "current revision" at the beginning and end; if |
| 746 | # it has changed, raise an exception. |
| 747 | jmsg = GetChangeCurrentRevision(host, change) |
| 748 | if not jmsg: |
| 749 | raise GerritError( |
| 750 | 200, 'Could not get review information for change "%s"' % change) |
| 751 | value = str(value) |
| 752 | revision = jmsg[0]['current_revision'] |
| 753 | path = 'changes/%s/revisions/%s/review' % (change, revision) |
| 754 | message = message or ( |
| 755 | '%s label set to %s programmatically.' % (label, value)) |
| 756 | jmsg = GetReview(host, change, revision) |
| 757 | if not jmsg: |
| 758 | raise GerritError(200, 'Could not get review information for revison %s ' |
| 759 | 'of change %s' % (revision, change)) |
| 760 | for review in jmsg.get('labels', {}).get(label, {}).get('all', []): |
| 761 | if str(review.get('value', value)) != value: |
| 762 | body = { |
| 763 | 'message': message, |
| 764 | 'labels': {label: value}, |
| 765 | 'on_behalf_of': review['_account_id'], |
| 766 | } |
| 767 | if notify: |
| 768 | body['notify'] = notify |
| 769 | conn = CreateHttpConn( |
| 770 | host, path, reqtype='POST', body=body) |
| 771 | response = ReadHttpJsonResponse(conn) |
| 772 | if str(response['labels'][label]) != value: |
| 773 | username = review.get('email', jmsg.get('name', '')) |
| 774 | raise GerritError(200, 'Unable to set %s label for user "%s"' |
| 775 | ' on change %s.' % (label, username, change)) |
| 776 | jmsg = GetChangeCurrentRevision(host, change) |
| 777 | if not jmsg: |
| 778 | raise GerritError( |
| 779 | 200, 'Could not get review information for change "%s"' % change) |
| 780 | elif jmsg[0]['current_revision'] != revision: |
| 781 | raise GerritError(200, 'While resetting labels on change "%s", ' |
| 782 | 'a new patchset was uploaded.' % change) |
Dan Jacques | 8d11e48 | 2016-11-15 14:25:56 -0800 | [diff] [blame] | 783 | |
| 784 | |
dimu | 833c94c | 2017-01-18 17:36:15 -0800 | [diff] [blame] | 785 | def CreateGerritBranch(host, project, branch, commit): |
| 786 | """ |
| 787 | Create a new branch from given project and commit |
| 788 | https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-branch |
| 789 | |
| 790 | Returns: |
| 791 | A JSON with 'ref' key |
| 792 | """ |
| 793 | path = 'projects/%s/branches/%s' % (project, branch) |
| 794 | body = {'revision': commit} |
| 795 | conn = CreateHttpConn(host, path, reqtype='PUT', body=body) |
dimu | 7d1af2b | 2017-04-19 16:01:17 -0700 | [diff] [blame] | 796 | response = ReadHttpJsonResponse(conn, accept_statuses=[201]) |
dimu | 833c94c | 2017-01-18 17:36:15 -0800 | [diff] [blame] | 797 | if response: |
| 798 | return response |
| 799 | raise GerritError(200, 'Unable to create gerrit branch') |
| 800 | |
| 801 | |
| 802 | def GetGerritBranch(host, project, branch): |
| 803 | """ |
| 804 | Get a branch from given project and commit |
| 805 | https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-branch |
| 806 | |
| 807 | Returns: |
| 808 | A JSON object with 'revision' key |
| 809 | """ |
| 810 | path = 'projects/%s/branches/%s' % (project, branch) |
| 811 | conn = CreateHttpConn(host, path, reqtype='GET') |
| 812 | response = ReadHttpJsonResponse(conn) |
| 813 | if response: |
| 814 | return response |
| 815 | raise GerritError(200, 'Unable to get gerrit branch') |
| 816 | |
| 817 | |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 818 | def GetAccountDetails(host, account_id='self'): |
| 819 | """Returns details of the account. |
| 820 | |
| 821 | If account_id is not given, uses magic value 'self' which corresponds to |
| 822 | whichever account user is authenticating as. |
| 823 | |
| 824 | Documentation: |
| 825 | https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-account |
| 826 | """ |
| 827 | if account_id != 'self': |
| 828 | account_id = int(account_id) |
| 829 | conn = CreateHttpConn(host, '/accounts/%s' % account_id) |
| 830 | return ReadHttpJsonResponse(conn) |
| 831 | |
| 832 | |
Nick Carter | 8692b18 | 2017-11-06 16:30:38 -0800 | [diff] [blame^] | 833 | def PercentEncodeForGitRef(original): |
| 834 | """Apply percent-encoding for strings sent to gerrit via git ref metadata. |
| 835 | |
| 836 | The encoding used is based on but stricter than URL encoding (Section 2.1 |
| 837 | of RFC 3986). The only non-escaped characters are alphanumerics, and |
| 838 | 'SPACE' (U+0020) can be represented as 'LOW LINE' (U+005F) or |
| 839 | 'PLUS SIGN' (U+002B). |
| 840 | |
| 841 | For more information, see the Gerrit docs here: |
| 842 | |
| 843 | https://gerrit-review.googlesource.com/Documentation/user-upload.html#message |
| 844 | """ |
| 845 | safe = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ' |
| 846 | encoded = ''.join(c if c in safe else '%%%02X' % ord(c) for c in original) |
| 847 | |
| 848 | # spaces are not allowed in git refs; gerrit will interpret either '_' or |
| 849 | # '+' (or '%20') as space. Use '_' since that has been supported the longest. |
| 850 | return encoded.replace(' ', '_') |
| 851 | |
| 852 | |
Dan Jacques | 8d11e48 | 2016-11-15 14:25:56 -0800 | [diff] [blame] | 853 | @contextlib.contextmanager |
| 854 | def tempdir(): |
| 855 | tdir = None |
| 856 | try: |
| 857 | tdir = tempfile.mkdtemp(suffix='gerrit_util') |
| 858 | yield tdir |
| 859 | finally: |
| 860 | if tdir: |
| 861 | gclient_utils.rmtree(tdir) |