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