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