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 [] |
Josip Sokcevic | f5c6d8a | 2021-05-12 18:23:24 +0000 | [diff] [blame] | 88 | q.extend(['%s:%s' % (key, val.replace(" ", "+")) 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') |
Aravind Vasudevan | c5f0cbb | 2022-01-24 23:56:57 +0000 | [diff] [blame] | 257 | |
| 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) |
Raphael Kubo da Costa | 9f6aa1b | 2021-06-24 16:59:31 +0000 | [diff] [blame] | 318 | except (socket.error, httplib2.HttpLib2Error, |
| 319 | httplib2.socks.ProxyError) as e: |
Edward Lemur | a3b6fd0 | 2020-03-02 22:16:15 +0000 | [diff] [blame] | 320 | LOGGER.debug('GET [%s] raised %s', url, e) |
| 321 | return None, None |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 322 | 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] | 323 | if resp.status < 500: |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 324 | return (resp, contents) |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 325 | |
Aaron Gable | 92e9f38 | 2017-12-07 11:47:41 -0800 | [diff] [blame] | 326 | # Retry server error status codes. |
| 327 | LOGGER.warn('Encountered server error') |
| 328 | if TRY_LIMIT - i > 1: |
| 329 | LOGGER.info('Will retry in %d seconds (%d more times)...', |
| 330 | next_delay_sec, TRY_LIMIT - i - 1) |
Edward Lemur | 4ba192e | 2019-10-28 20:19:37 +0000 | [diff] [blame] | 331 | time_sleep(next_delay_sec) |
George Engelbrecht | 888c0fe | 2020-04-17 15:00:20 +0000 | [diff] [blame] | 332 | next_delay_sec *= random.uniform(MIN_BACKOFF, MAX_BACKOFF) |
Edward Lemur | a3b6fd0 | 2020-03-02 22:16:15 +0000 | [diff] [blame] | 333 | return None, None |
Aaron Gable | 92e9f38 | 2017-12-07 11:47:41 -0800 | [diff] [blame] | 334 | |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 335 | @classmethod |
| 336 | def _get_token_dict(cls): |
Edward Lemur | a3b6fd0 | 2020-03-02 22:16:15 +0000 | [diff] [blame] | 337 | # If cached token is valid for at least 25 seconds, return it. |
| 338 | if cls._token_cache and time_time() + 25 < cls._token_expiration: |
| 339 | return cls._token_cache |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 340 | |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 341 | resp, contents = cls._get(cls._ACQUIRE_URL, headers=cls._ACQUIRE_HEADERS) |
Edward Lemur | a3b6fd0 | 2020-03-02 22:16:15 +0000 | [diff] [blame] | 342 | if resp is None or resp.status != 200: |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 343 | return None |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 344 | cls._token_cache = json.loads(contents) |
Edward Lemur | a3b6fd0 | 2020-03-02 22:16:15 +0000 | [diff] [blame] | 345 | cls._token_expiration = cls._token_cache['expires_in'] + time_time() |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 346 | return cls._token_cache |
| 347 | |
| 348 | def get_auth_header(self, _host): |
| 349 | token_dict = self._get_token_dict() |
| 350 | if not token_dict: |
| 351 | return None |
| 352 | return '%(token_type)s %(access_token)s' % token_dict |
| 353 | |
| 354 | |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 355 | class LuciContextAuthenticator(Authenticator): |
| 356 | """Authenticator implementation that uses LUCI_CONTEXT ambient local auth. |
| 357 | """ |
| 358 | |
| 359 | @staticmethod |
| 360 | def is_luci(): |
| 361 | return auth.has_luci_context_local_auth() |
| 362 | |
| 363 | def __init__(self): |
Edward Lemur | 5b929a4 | 2019-10-21 17:57:39 +0000 | [diff] [blame] | 364 | self._authenticator = auth.Authenticator( |
| 365 | ' '.join([auth.OAUTH_SCOPE_EMAIL, auth.OAUTH_SCOPE_GERRIT])) |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 366 | |
| 367 | def get_auth_header(self, _host): |
Edward Lemur | 5b929a4 | 2019-10-21 17:57:39 +0000 | [diff] [blame] | 368 | return 'Bearer %s' % self._authenticator.get_access_token().token |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 369 | |
| 370 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 371 | def CreateHttpConn(host, path, reqtype='GET', headers=None, body=None): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 372 | """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] | 373 | headers = headers or {} |
| 374 | bare_host = host.partition(':')[0] |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 375 | |
Edward Lemur | 447507e | 2020-03-31 17:33:54 +0000 | [diff] [blame] | 376 | a = Authenticator.get() |
| 377 | # TODO(crbug.com/1059384): Automatically detect when running on cloudtop. |
| 378 | if isinstance(a, GceAuthenticator): |
| 379 | print('If you\'re on a cloudtop instance, export ' |
| 380 | 'SKIP_GCE_AUTH_FOR_GIT=1 in your env.') |
| 381 | |
| 382 | a = a.get_auth_header(bare_host) |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 383 | if a: |
| 384 | headers.setdefault('Authorization', a) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 385 | else: |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 386 | LOGGER.debug('No authorization found for %s.' % bare_host) |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 387 | |
Dan Jacques | 6d5bcc2 | 2016-11-14 15:32:04 -0800 | [diff] [blame] | 388 | url = path |
| 389 | if not url.startswith('/'): |
| 390 | url = '/' + url |
| 391 | if 'Authorization' in headers and not url.startswith('/a/'): |
| 392 | url = '/a%s' % url |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 393 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 394 | if body: |
Edward Lemur | 4ba192e | 2019-10-28 20:19:37 +0000 | [diff] [blame] | 395 | body = json.dumps(body, sort_keys=True) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 396 | headers.setdefault('Content-Type', 'application/json') |
| 397 | if LOGGER.isEnabledFor(logging.DEBUG): |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 398 | LOGGER.debug('%s %s://%s%s' % (reqtype, GERRIT_PROTOCOL, host, url)) |
Marc-Antoine Ruel | 8e57b4b | 2019-10-11 01:01:36 +0000 | [diff] [blame] | 399 | for key, val in headers.items(): |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 400 | if key == 'Authorization': |
| 401 | val = 'HIDDEN' |
| 402 | LOGGER.debug('%s: %s' % (key, val)) |
| 403 | if body: |
| 404 | LOGGER.debug(body) |
Edward Lemur | 4ba192e | 2019-10-28 20:19:37 +0000 | [diff] [blame] | 405 | conn = httplib2.Http() |
| 406 | # 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] | 407 | # use in ReadHttpResponse. |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 408 | conn.req_host = host |
| 409 | conn.req_params = { |
Edward Lemur | 4ba192e | 2019-10-28 20:19:37 +0000 | [diff] [blame] | 410 | 'uri': urllib.parse.urljoin('%s://%s' % (GERRIT_PROTOCOL, host), url), |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 411 | 'method': reqtype, |
| 412 | 'headers': headers, |
| 413 | 'body': body, |
| 414 | } |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 415 | return conn |
| 416 | |
| 417 | |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 418 | def ReadHttpResponse(conn, accept_statuses=frozenset([200])): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 419 | """Reads an HTTP response from a connection into a string buffer. |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 420 | |
| 421 | Args: |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 422 | conn: An Http object created by CreateHttpConn above. |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 423 | accept_statuses: Treat any of these statuses as success. Default: [200] |
| 424 | Common additions include 204, 400, and 404. |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 425 | Returns: A string buffer containing the connection's reply. |
| 426 | """ |
George Engelbrecht | 888c0fe | 2020-04-17 15:00:20 +0000 | [diff] [blame] | 427 | sleep_time = SLEEP_TIME |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 428 | for idx in range(TRY_LIMIT): |
Edward Lemur | 5a9ff43 | 2018-10-30 19:00:22 +0000 | [diff] [blame] | 429 | before_response = time.time() |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 430 | response, contents = conn.request(**conn.req_params) |
Edward Lemur | 4ba192e | 2019-10-28 20:19:37 +0000 | [diff] [blame] | 431 | contents = contents.decode('utf-8', 'replace') |
nodir@chromium.org | ce32b6e | 2014-05-12 20:31:32 +0000 | [diff] [blame] | 432 | |
Edward Lemur | 5a9ff43 | 2018-10-30 19:00:22 +0000 | [diff] [blame] | 433 | response_time = time.time() - before_response |
| 434 | metrics.collector.add_repeated( |
| 435 | 'http_requests', |
| 436 | metrics_utils.extract_http_metrics( |
| 437 | conn.req_params['uri'], conn.req_params['method'], response.status, |
| 438 | response_time)) |
| 439 | |
Edward Lemur | 4ba192e | 2019-10-28 20:19:37 +0000 | [diff] [blame] | 440 | # If response.status is an accepted status, |
| 441 | # or response.status < 500 then the result is final; break retry loop. |
| 442 | # 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] | 443 | # so keep trying anyway. If it is 429, it is generally ok to retry after |
| 444 | # a backoff. |
Edward Lemur | 4ba192e | 2019-10-28 20:19:37 +0000 | [diff] [blame] | 445 | if (response.status in accept_statuses |
George Engelbrecht | 888c0fe | 2020-04-17 15:00:20 +0000 | [diff] [blame] | 446 | or response.status < 500 and response.status not in [404, 409, 429]): |
Andrii Shyshkalov | 5b04a57 | 2017-01-23 17:44:41 +0100 | [diff] [blame] | 447 | LOGGER.debug('got response %d for %s %s', response.status, |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 448 | conn.req_params['method'], conn.req_params['uri']) |
Michael Moss | b40a451 | 2017-10-10 11:07:17 -0700 | [diff] [blame] | 449 | # 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] | 450 | # not exist, so don't return the gitiles error page because that's not |
| 451 | # the "content" that was actually requested. |
Michael Moss | b40a451 | 2017-10-10 11:07:17 -0700 | [diff] [blame] | 452 | if response.status == 404: |
| 453 | contents = '' |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 454 | break |
Edward Lemur | 4ba192e | 2019-10-28 20:19:37 +0000 | [diff] [blame] | 455 | |
Edward Lemur | 49c8eaf | 2018-11-07 22:13:12 +0000 | [diff] [blame] | 456 | # A status >=500 is assumed to be a possible transient error; retry. |
| 457 | http_version = 'HTTP/%s' % ('1.1' if response.version == 11 else '1.0') |
| 458 | LOGGER.warn('A transient error occurred while querying %s:\n' |
| 459 | '%s %s %s\n' |
Edward Lesmes | b073999 | 2020-10-09 23:15:44 +0000 | [diff] [blame] | 460 | '%s %d %s\n' |
| 461 | '%s', |
Edward Lemur | 49c8eaf | 2018-11-07 22:13:12 +0000 | [diff] [blame] | 462 | conn.req_host, conn.req_params['method'], |
| 463 | conn.req_params['uri'], |
Edward Lesmes | b073999 | 2020-10-09 23:15:44 +0000 | [diff] [blame] | 464 | http_version, http_version, response.status, response.reason, |
| 465 | contents) |
Andrii Shyshkalov | d4c8673 | 2018-09-25 04:29:31 +0000 | [diff] [blame] | 466 | |
Edward Lemur | 4ba192e | 2019-10-28 20:19:37 +0000 | [diff] [blame] | 467 | if idx < TRY_LIMIT - 1: |
Aaron Gable | 92e9f38 | 2017-12-07 11:47:41 -0800 | [diff] [blame] | 468 | LOGGER.info('Will retry in %d seconds (%d more times)...', |
| 469 | sleep_time, TRY_LIMIT - idx - 1) |
Edward Lemur | 4ba192e | 2019-10-28 20:19:37 +0000 | [diff] [blame] | 470 | time_sleep(sleep_time) |
George Engelbrecht | 888c0fe | 2020-04-17 15:00:20 +0000 | [diff] [blame] | 471 | sleep_time *= random.uniform(MIN_BACKOFF, MAX_BACKOFF) |
Edward Lemur | 83bd7f4 | 2018-10-10 00:14:21 +0000 | [diff] [blame] | 472 | # end of retries loop |
Edward Lemur | 4ba192e | 2019-10-28 20:19:37 +0000 | [diff] [blame] | 473 | |
| 474 | if response.status in accept_statuses: |
| 475 | return StringIO(contents) |
| 476 | |
| 477 | if response.status in (302, 401, 403): |
| 478 | www_authenticate = response.get('www-authenticate') |
| 479 | if not www_authenticate: |
| 480 | print('Your Gerrit credentials might be misconfigured.') |
| 481 | else: |
| 482 | auth_match = re.search('realm="([^"]+)"', www_authenticate, re.I) |
| 483 | host = auth_match.group(1) if auth_match else conn.req_host |
| 484 | print('Authentication failed. Please make sure your .gitcookies ' |
| 485 | 'file has credentials for %s.' % host) |
| 486 | print('Try:\n git cl creds-check') |
| 487 | |
| 488 | reason = '%s: %s' % (response.reason, contents) |
| 489 | raise GerritError(response.status, reason) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 490 | |
| 491 | |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 492 | def ReadHttpJsonResponse(conn, accept_statuses=frozenset([200])): |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 493 | """Parses an https response as json.""" |
Aaron Gable | 19ee16c | 2017-04-18 11:56:35 -0700 | [diff] [blame] | 494 | fh = ReadHttpResponse(conn, accept_statuses) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 495 | # The first line of the response should always be: )]}' |
| 496 | s = fh.readline() |
| 497 | if s and s.rstrip() != ")]}'": |
| 498 | raise GerritError(200, 'Unexpected json output: %s' % s) |
| 499 | s = fh.read() |
| 500 | if not s: |
| 501 | return None |
| 502 | return json.loads(s) |
| 503 | |
| 504 | |
Michael Moss | 9c28af4 | 2021-10-25 16:59:05 +0000 | [diff] [blame] | 505 | def CallGerritApi(host, path, **kwargs): |
| 506 | """Helper for calling a Gerrit API that returns a JSON response.""" |
| 507 | conn_kwargs = {} |
| 508 | conn_kwargs.update( |
| 509 | (k, kwargs[k]) for k in ['reqtype', 'headers', 'body'] if k in kwargs) |
| 510 | conn = CreateHttpConn(host, path, **conn_kwargs) |
| 511 | read_kwargs = {} |
| 512 | read_kwargs.update((k, kwargs[k]) for k in ['accept_statuses'] if k in kwargs) |
| 513 | return ReadHttpJsonResponse(conn, **read_kwargs) |
| 514 | |
| 515 | |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 516 | def QueryChanges(host, params, first_param=None, limit=None, o_params=None, |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 517 | start=None): |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 518 | """ |
| 519 | Queries a gerrit-on-borg server for changes matching query terms. |
| 520 | |
| 521 | Args: |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 522 | params: A list of key:value pairs for search parameters, as documented |
| 523 | here (e.g. ('is', 'owner') for a parameter 'is:owner'): |
| 524 | https://gerrit-review.googlesource.com/Documentation/user-search.html#search-operators |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 525 | first_param: A change identifier |
| 526 | limit: Maximum number of results to return. |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 527 | start: how many changes to skip (starting with the most recent) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 528 | o_params: A list of additional output specifiers, as documented here: |
| 529 | https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 530 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 531 | Returns: |
| 532 | A list of json-decoded query results. |
| 533 | """ |
| 534 | # Note that no attempt is made to escape special characters; YMMV. |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 535 | if not params and not first_param: |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 536 | raise RuntimeError('QueryChanges requires search parameters') |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 537 | path = 'changes/?q=%s' % _QueryString(params, first_param) |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 538 | if start: |
| 539 | path = '%s&start=%s' % (path, start) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 540 | if limit: |
| 541 | path = '%s&n=%d' % (path, limit) |
| 542 | if o_params: |
| 543 | 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] | 544 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 545 | |
| 546 | |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 547 | def GenerateAllChanges(host, params, first_param=None, limit=500, |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 548 | o_params=None, start=None): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 549 | """Queries a gerrit-on-borg server for all the changes matching the query |
| 550 | terms. |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 551 | |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 552 | 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] | 553 | this function is being called. |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 554 | |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 555 | A single query to gerrit-on-borg is limited on the number of results by the |
| 556 | limit parameter on the request (see QueryChanges) and the server maximum |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 557 | limit. |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 558 | |
| 559 | Args: |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 560 | params, first_param: Refer to QueryChanges(). |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 561 | limit: Maximum number of requested changes per query. |
| 562 | o_params: Refer to QueryChanges(). |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 563 | start: Refer to QueryChanges(). |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 564 | |
| 565 | Returns: |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 566 | A generator object to the list of returned changes. |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 567 | """ |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 568 | already_returned = set() |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 569 | |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 570 | def at_most_once(cls): |
| 571 | for cl in cls: |
| 572 | if cl['_number'] not in already_returned: |
| 573 | already_returned.add(cl['_number']) |
| 574 | yield cl |
| 575 | |
| 576 | start = start or 0 |
| 577 | cur_start = start |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 578 | more_changes = True |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 579 | |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 580 | while more_changes: |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 581 | # This will fetch changes[start..start+limit] sorted by most recently |
| 582 | # updated. Since the rank of any change in this list can be changed any time |
| 583 | # (say user posting comment), subsequent calls may overalp like this: |
| 584 | # > initial order ABCDEFGH |
| 585 | # query[0..3] => ABC |
Quinten Yearsley | 925cedb | 2020-04-13 17:49:39 +0000 | [diff] [blame] | 586 | # > E gets updated. New order: EABCDFGH |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 587 | # query[3..6] => CDF # C is a dup |
| 588 | # query[6..9] => GH # E is missed. |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 589 | page = QueryChanges(host, params, first_param, limit, o_params, |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 590 | cur_start) |
| 591 | for cl in at_most_once(page): |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 592 | yield cl |
| 593 | |
| 594 | more_changes = [cl for cl in page if '_more_changes' in cl] |
| 595 | if len(more_changes) > 1: |
| 596 | raise GerritError( |
| 597 | 200, |
| 598 | 'Received %d changes with a _more_changes attribute set but should ' |
| 599 | 'receive at most one.' % len(more_changes)) |
| 600 | if more_changes: |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 601 | cur_start += len(page) |
| 602 | |
| 603 | # If we paged through, query again the first page which in most circumstances |
| 604 | # will fetch all changes that were modified while this function was run. |
| 605 | if start != cur_start: |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 606 | page = QueryChanges(host, params, first_param, limit, o_params, start) |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 607 | for cl in at_most_once(page): |
| 608 | yield cl |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 609 | |
| 610 | |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 611 | def MultiQueryChanges(host, params, change_list, limit=None, o_params=None, |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 612 | start=None): |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 613 | """Initiate a query composed of multiple sets of query parameters.""" |
| 614 | if not change_list: |
| 615 | raise RuntimeError( |
| 616 | "MultiQueryChanges requires a list of change numbers/id's") |
Edward Lemur | 4ba192e | 2019-10-28 20:19:37 +0000 | [diff] [blame] | 617 | 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] | 618 | if params: |
| 619 | q.append(_QueryString(params)) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 620 | if limit: |
| 621 | q.append('n=%d' % limit) |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 622 | if start: |
| 623 | q.append('S=%s' % start) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 624 | if o_params: |
| 625 | q.extend(['o=%s' % p for p in o_params]) |
| 626 | path = 'changes/?%s' % '&'.join(q) |
| 627 | try: |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 628 | result = ReadHttpJsonResponse(CreateHttpConn(host, path)) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 629 | except GerritError as e: |
| 630 | msg = '%s:\n%s' % (e.message, path) |
| 631 | raise GerritError(e.http_status, msg) |
| 632 | return result |
| 633 | |
| 634 | |
| 635 | def GetGerritFetchUrl(host): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 636 | """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] | 637 | return '%s://%s/' % (GERRIT_PROTOCOL, host) |
| 638 | |
| 639 | |
Edward Lemur | 687ca90 | 2018-12-05 02:30:30 +0000 | [diff] [blame] | 640 | def GetCodeReviewTbrScore(host, project): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 641 | """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] | 642 | """ |
Edward Lemur | 4ba192e | 2019-10-28 20:19:37 +0000 | [diff] [blame] | 643 | conn = CreateHttpConn( |
| 644 | host, '/projects/%s' % urllib.parse.quote(project, '')) |
Edward Lemur | 687ca90 | 2018-12-05 02:30:30 +0000 | [diff] [blame] | 645 | project = ReadHttpJsonResponse(conn) |
| 646 | if ('labels' not in project |
| 647 | or 'Code-Review' not in project['labels'] |
| 648 | or 'values' not in project['labels']['Code-Review']): |
| 649 | return 1 |
| 650 | return max([int(x) for x in project['labels']['Code-Review']['values']]) |
| 651 | |
| 652 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 653 | def GetChangePageUrl(host, change_number): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 654 | """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] | 655 | return '%s://%s/#/c/%d/' % (GERRIT_PROTOCOL, host, change_number) |
| 656 | |
| 657 | |
| 658 | def GetChangeUrl(host, change): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 659 | """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] | 660 | return '%s://%s/a/changes/%s' % (GERRIT_PROTOCOL, host, change) |
| 661 | |
| 662 | |
| 663 | def GetChange(host, change): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 664 | """Queries a Gerrit server for information about a single change.""" |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 665 | path = 'changes/%s' % change |
| 666 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
| 667 | |
| 668 | |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 669 | def GetChangeDetail(host, change, o_params=None): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 670 | """Queries a Gerrit server for extended information about a single change.""" |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 671 | path = 'changes/%s/detail' % change |
| 672 | if o_params: |
| 673 | path += '?%s' % '&'.join(['o=%s' % p for p in o_params]) |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 674 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 675 | |
| 676 | |
agable | 32978d9 | 2016-11-01 12:55:02 -0700 | [diff] [blame] | 677 | def GetChangeCommit(host, change, revision='current'): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 678 | """Query a Gerrit server for a revision associated with a change.""" |
agable | 32978d9 | 2016-11-01 12:55:02 -0700 | [diff] [blame] | 679 | path = 'changes/%s/revisions/%s/commit?links' % (change, revision) |
| 680 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
| 681 | |
| 682 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 683 | def GetChangeCurrentRevision(host, change): |
| 684 | """Get information about the latest revision for a given change.""" |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 685 | return QueryChanges(host, [], change, o_params=('CURRENT_REVISION',)) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 686 | |
| 687 | |
| 688 | def GetChangeRevisions(host, change): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 689 | """Gets information about all revisions associated with a change.""" |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 690 | return QueryChanges(host, [], change, o_params=('ALL_REVISIONS',)) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 691 | |
| 692 | |
| 693 | def GetChangeReview(host, change, revision=None): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 694 | """Gets the current review information for a change.""" |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 695 | if not revision: |
| 696 | jmsg = GetChangeRevisions(host, change) |
| 697 | if not jmsg: |
| 698 | return None |
Aravind Vasudevan | c5f0cbb | 2022-01-24 23:56:57 +0000 | [diff] [blame] | 699 | |
| 700 | if len(jmsg) > 1: |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 701 | raise GerritError(200, 'Multiple changes found for ChangeId %s.' % change) |
| 702 | revision = jmsg[0]['current_revision'] |
| 703 | path = 'changes/%s/revisions/%s/review' |
| 704 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
| 705 | |
| 706 | |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 707 | def GetChangeComments(host, change): |
| 708 | """Get the line- and file-level comments on a change.""" |
| 709 | path = 'changes/%s/comments' % change |
| 710 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
| 711 | |
| 712 | |
Quinten Yearsley | 0e617c0 | 2019-02-20 00:37:03 +0000 | [diff] [blame] | 713 | def GetChangeRobotComments(host, change): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 714 | """Gets the line- and file-level robot comments on a change.""" |
Quinten Yearsley | 0e617c0 | 2019-02-20 00:37:03 +0000 | [diff] [blame] | 715 | path = 'changes/%s/robotcomments' % change |
| 716 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
| 717 | |
| 718 | |
Marco Georgaklis | 85557a0 | 2021-06-03 15:56:54 +0000 | [diff] [blame] | 719 | def GetRelatedChanges(host, change, revision='current'): |
| 720 | """Gets the related changes for a given change and revision.""" |
| 721 | path = 'changes/%s/revisions/%s/related' % (change, revision) |
| 722 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
| 723 | |
| 724 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 725 | def AbandonChange(host, change, msg=''): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 726 | """Abandons a Gerrit change.""" |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 727 | path = 'changes/%s/abandon' % change |
tandrii@chromium.org | c7da66a | 2016-03-24 09:52:24 +0000 | [diff] [blame] | 728 | body = {'message': msg} if msg else {} |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 729 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 730 | return ReadHttpJsonResponse(conn) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 731 | |
| 732 | |
Josip Sokcevic | c39ab99 | 2020-09-24 20:09:15 +0000 | [diff] [blame] | 733 | def MoveChange(host, change, destination_branch): |
| 734 | """Move a Gerrit change to different destination branch.""" |
| 735 | path = 'changes/%s/move' % change |
Mike Frysinger | f1c7d0d | 2020-12-15 20:05:36 +0000 | [diff] [blame] | 736 | body = {'destination_branch': destination_branch, |
| 737 | 'keep_all_votes': True} |
Josip Sokcevic | c39ab99 | 2020-09-24 20:09:15 +0000 | [diff] [blame] | 738 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
| 739 | return ReadHttpJsonResponse(conn) |
| 740 | |
| 741 | |
| 742 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 743 | def RestoreChange(host, change, msg=''): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 744 | """Restores a previously abandoned change.""" |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 745 | path = 'changes/%s/restore' % change |
tandrii@chromium.org | c7da66a | 2016-03-24 09:52:24 +0000 | [diff] [blame] | 746 | body = {'message': msg} if msg else {} |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 747 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 748 | return ReadHttpJsonResponse(conn) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 749 | |
| 750 | |
Xinan Lin | 1bd4ffa | 2021-07-28 00:54:22 +0000 | [diff] [blame] | 751 | def SubmitChange(host, change): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 752 | """Submits a Gerrit change via Gerrit.""" |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 753 | path = 'changes/%s/submit' % change |
Xinan Lin | 1bd4ffa | 2021-07-28 00:54:22 +0000 | [diff] [blame] | 754 | conn = CreateHttpConn(host, path, reqtype='POST') |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 755 | return ReadHttpJsonResponse(conn) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 756 | |
| 757 | |
Xinan Lin | 2b4ec95 | 2021-08-20 17:35:29 +0000 | [diff] [blame] | 758 | def GetChangesSubmittedTogether(host, change): |
| 759 | """Get all changes submitted with the given one.""" |
| 760 | path = 'changes/%s/submitted_together?o=NON_VISIBLE_CHANGES' % change |
| 761 | conn = CreateHttpConn(host, path, reqtype='GET') |
| 762 | return ReadHttpJsonResponse(conn) |
| 763 | |
| 764 | |
LaMont Jones | 9eed423 | 2021-04-02 16:29:49 +0000 | [diff] [blame] | 765 | def PublishChangeEdit(host, change, notify=True): |
| 766 | """Publish a Gerrit change edit.""" |
| 767 | path = 'changes/%s/edit:publish' % change |
| 768 | body = {'notify': 'ALL' if notify else 'NONE'} |
| 769 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
| 770 | return ReadHttpJsonResponse(conn, accept_statuses=(204, )) |
| 771 | |
| 772 | |
| 773 | def ChangeEdit(host, change, path, data): |
| 774 | """Puts content of a file into a change edit.""" |
| 775 | path = 'changes/%s/edit/%s' % (change, urllib.parse.quote(path, '')) |
| 776 | body = { |
| 777 | 'binary_content': |
Leszek Swirski | 4c0c3fb | 2022-06-08 17:04:02 +0000 | [diff] [blame] | 778 | 'data:text/plain;base64,%s' % |
| 779 | base64.b64encode(data.encode('utf-8')).decode('utf-8') |
LaMont Jones | 9eed423 | 2021-04-02 16:29:49 +0000 | [diff] [blame] | 780 | } |
| 781 | conn = CreateHttpConn(host, path, reqtype='PUT', body=body) |
| 782 | return ReadHttpJsonResponse(conn, accept_statuses=(204, 409)) |
| 783 | |
| 784 | |
Leszek Swirski | c1c45f8 | 2022-06-09 16:21:07 +0000 | [diff] [blame] | 785 | def SetChangeEditMessage(host, change, message): |
| 786 | """Sets the commit message of a change edit.""" |
| 787 | path = 'changes/%s/edit:message' % change |
| 788 | body = {'message': message} |
| 789 | conn = CreateHttpConn(host, path, reqtype='PUT', body=body) |
| 790 | return ReadHttpJsonResponse(conn, accept_statuses=(204, 409)) |
| 791 | |
| 792 | |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 793 | def HasPendingChangeEdit(host, change): |
| 794 | conn = CreateHttpConn(host, 'changes/%s/edit' % change) |
| 795 | try: |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 796 | ReadHttpResponse(conn) |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 797 | except GerritError as e: |
Aaron Gable | 19ee16c | 2017-04-18 11:56:35 -0700 | [diff] [blame] | 798 | # 204 No Content means no pending change. |
| 799 | if e.http_status == 204: |
| 800 | return False |
| 801 | raise |
| 802 | return True |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 803 | |
| 804 | |
| 805 | def DeletePendingChangeEdit(host, change): |
| 806 | conn = CreateHttpConn(host, 'changes/%s/edit' % change, reqtype='DELETE') |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 807 | # 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] | 808 | # returns 404. Anything else is an error. |
| 809 | ReadHttpResponse(conn, accept_statuses=[204, 404]) |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 810 | |
| 811 | |
Leszek Swirski | c1c45f8 | 2022-06-09 16:21:07 +0000 | [diff] [blame] | 812 | def CherryPick(host, change, destination, revision='current'): |
| 813 | """Create a cherry-pick commit from the given change, onto the given |
| 814 | destination. |
| 815 | """ |
| 816 | path = 'changes/%s/revisions/%s/cherrypick' % (change, revision) |
| 817 | body = {'destination': destination} |
| 818 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
| 819 | return ReadHttpJsonResponse(conn) |
| 820 | |
| 821 | |
| 822 | def GetFileContents(host, change, path): |
| 823 | """Get the contents of a file with the given path in the given revision. |
| 824 | |
| 825 | Returns: |
| 826 | A bytes object with the file's contents. |
| 827 | """ |
| 828 | path = 'changes/%s/revisions/current/files/%s/content' % ( |
| 829 | change, urllib.parse.quote(path, '')) |
| 830 | conn = CreateHttpConn(host, path, reqtype='GET') |
| 831 | return base64.b64decode(ReadHttpResponse(conn).read()) |
| 832 | |
| 833 | |
Andrii Shyshkalov | ea4fc83 | 2016-12-01 14:53:23 +0100 | [diff] [blame] | 834 | def SetCommitMessage(host, change, description, notify='ALL'): |
scottmg@chromium.org | 6d1266e | 2016-04-26 11:12:26 +0000 | [diff] [blame] | 835 | """Updates a commit message.""" |
Aaron Gable | 7625d88 | 2017-06-26 09:47:26 -0700 | [diff] [blame] | 836 | assert notify in ('ALL', 'NONE') |
| 837 | path = 'changes/%s/message' % change |
Aaron Gable | 5a4ef45 | 2017-08-24 13:19:56 -0700 | [diff] [blame] | 838 | body = {'message': description, 'notify': notify} |
Aaron Gable | 7625d88 | 2017-06-26 09:47:26 -0700 | [diff] [blame] | 839 | conn = CreateHttpConn(host, path, reqtype='PUT', body=body) |
scottmg@chromium.org | 6d1266e | 2016-04-26 11:12:26 +0000 | [diff] [blame] | 840 | try: |
Aaron Gable | 7625d88 | 2017-06-26 09:47:26 -0700 | [diff] [blame] | 841 | ReadHttpResponse(conn, accept_statuses=[200, 204]) |
| 842 | except GerritError as e: |
| 843 | raise GerritError( |
| 844 | e.http_status, |
| 845 | 'Received unexpected http status while editing message ' |
| 846 | 'in change %s' % change) |
scottmg@chromium.org | 6d1266e | 2016-04-26 11:12:26 +0000 | [diff] [blame] | 847 | |
| 848 | |
Xinan Lin | c2fb26a | 2021-07-27 18:01:55 +0000 | [diff] [blame] | 849 | def GetCommitIncludedIn(host, project, commit): |
| 850 | """Retrieves the branches and tags for a given commit. |
| 851 | |
| 852 | https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-included-in |
| 853 | |
| 854 | Returns: |
| 855 | A JSON object with keys of 'branches' and 'tags'. |
| 856 | """ |
| 857 | path = 'projects/%s/commits/%s/in' % (urllib.parse.quote(project, ''), commit) |
| 858 | conn = CreateHttpConn(host, path, reqtype='GET') |
| 859 | return ReadHttpJsonResponse(conn, accept_statuses=[200]) |
| 860 | |
| 861 | |
Edward Lesmes | 8170c29 | 2021-03-19 20:04:43 +0000 | [diff] [blame] | 862 | def IsCodeOwnersEnabledOnHost(host): |
Edward Lesmes | 110823b | 2021-02-05 21:42:27 +0000 | [diff] [blame] | 863 | """Check if the code-owners plugin is enabled for the host.""" |
| 864 | path = 'config/server/capabilities' |
| 865 | capabilities = ReadHttpJsonResponse(CreateHttpConn(host, path)) |
| 866 | return 'code-owners-checkCodeOwner' in capabilities |
| 867 | |
| 868 | |
Edward Lesmes | 8170c29 | 2021-03-19 20:04:43 +0000 | [diff] [blame] | 869 | def IsCodeOwnersEnabledOnRepo(host, repo): |
| 870 | """Check if the code-owners plugin is enabled for the repo.""" |
| 871 | repo = PercentEncodeForGitRef(repo) |
| 872 | path = '/projects/%s/code_owners.project_config' % repo |
| 873 | config = ReadHttpJsonResponse(CreateHttpConn(host, path)) |
Edward Lesmes | 743e98c | 2021-03-22 18:00:54 +0000 | [diff] [blame] | 874 | return not config['status'].get('disabled', False) |
Edward Lesmes | 8170c29 | 2021-03-19 20:04:43 +0000 | [diff] [blame] | 875 | |
| 876 | |
Gavin Mak | e0fee9f | 2022-08-10 23:41:55 +0000 | [diff] [blame^] | 877 | def GetOwnersForFile(host, |
| 878 | project, |
| 879 | branch, |
| 880 | path, |
| 881 | limit=100, |
| 882 | resolve_all_users=True, |
| 883 | highest_score_only=False, |
| 884 | seed=None, |
| 885 | o_params=('DETAILS',)): |
Gavin Mak | c94b21d | 2020-12-10 20:27:32 +0000 | [diff] [blame] | 886 | """Gets information about owners attached to a file.""" |
| 887 | path = 'projects/%s/branches/%s/code_owners/%s' % ( |
| 888 | urllib.parse.quote(project, ''), |
| 889 | urllib.parse.quote(branch, ''), |
| 890 | urllib.parse.quote(path, '')) |
Gavin Mak | 7d69005 | 2021-02-25 19:14:22 +0000 | [diff] [blame] | 891 | q = ['resolve-all-users=%s' % json.dumps(resolve_all_users)] |
Gavin Mak | e0fee9f | 2022-08-10 23:41:55 +0000 | [diff] [blame^] | 892 | if highest_score_only: |
| 893 | q.append('highest-score-only=%s' % json.dumps(highest_score_only)) |
Edward Lesmes | 23c3bdc | 2021-03-11 20:37:32 +0000 | [diff] [blame] | 894 | if seed: |
| 895 | q.append('seed=%d' % seed) |
Gavin Mak | c94b21d | 2020-12-10 20:27:32 +0000 | [diff] [blame] | 896 | if limit: |
| 897 | q.append('n=%d' % limit) |
| 898 | if o_params: |
| 899 | q.extend(['o=%s' % p for p in o_params]) |
| 900 | if q: |
| 901 | path = '%s?%s' % (path, '&'.join(q)) |
| 902 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
| 903 | |
| 904 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 905 | def GetReviewers(host, change): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 906 | """Gets information about all reviewers attached to a change.""" |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 907 | path = 'changes/%s/reviewers' % change |
| 908 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
| 909 | |
| 910 | |
| 911 | def GetReview(host, change, revision): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 912 | """Gets review information about a specific revision of a change.""" |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 913 | path = 'changes/%s/revisions/%s/review' % (change, revision) |
| 914 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
| 915 | |
| 916 | |
Aaron Gable | 6dadfbf | 2017-05-09 14:27:58 -0700 | [diff] [blame] | 917 | def AddReviewers(host, change, reviewers=None, ccs=None, notify=True, |
| 918 | accept_statuses=frozenset([200, 400, 422])): |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 919 | """Add reviewers to a change.""" |
Aaron Gable | 6dadfbf | 2017-05-09 14:27:58 -0700 | [diff] [blame] | 920 | if not reviewers and not ccs: |
Aaron Gable | df86e30 | 2016-11-08 10:48:03 -0800 | [diff] [blame] | 921 | return None |
Wiktor Garbacz | 6d0d044 | 2017-05-15 12:34:40 +0200 | [diff] [blame] | 922 | if not change: |
| 923 | return None |
Aaron Gable | 6dadfbf | 2017-05-09 14:27:58 -0700 | [diff] [blame] | 924 | reviewers = frozenset(reviewers or []) |
| 925 | ccs = frozenset(ccs or []) |
| 926 | path = 'changes/%s/revisions/current/review' % change |
| 927 | |
| 928 | body = { |
Jonathan Nieder | 1ea2132 | 2017-11-10 11:45:42 -0800 | [diff] [blame] | 929 | 'drafts': 'KEEP', |
Aaron Gable | 6dadfbf | 2017-05-09 14:27:58 -0700 | [diff] [blame] | 930 | 'reviewers': [], |
| 931 | 'notify': 'ALL' if notify else 'NONE', |
| 932 | } |
| 933 | for r in sorted(reviewers | ccs): |
| 934 | state = 'REVIEWER' if r in reviewers else 'CC' |
| 935 | body['reviewers'].append({ |
| 936 | 'reviewer': r, |
| 937 | 'state': state, |
| 938 | 'notify': 'NONE', # We handled `notify` argument above. |
Raul Tambre | 80ee78e | 2019-05-06 22:41:05 +0000 | [diff] [blame] | 939 | }) |
Aaron Gable | 6dadfbf | 2017-05-09 14:27:58 -0700 | [diff] [blame] | 940 | |
| 941 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
| 942 | # Gerrit will return 400 if one or more of the requested reviewers are |
| 943 | # unprocessable. We read the response object to see which were rejected, |
| 944 | # warn about them, and retry with the remainder. |
| 945 | resp = ReadHttpJsonResponse(conn, accept_statuses=accept_statuses) |
| 946 | |
| 947 | errored = set() |
Marc-Antoine Ruel | 8e57b4b | 2019-10-11 01:01:36 +0000 | [diff] [blame] | 948 | for result in resp.get('reviewers', {}).values(): |
Aaron Gable | 6dadfbf | 2017-05-09 14:27:58 -0700 | [diff] [blame] | 949 | r = result.get('input') |
| 950 | state = 'REVIEWER' if r in reviewers else 'CC' |
| 951 | if result.get('error'): |
| 952 | errored.add(r) |
| 953 | LOGGER.warn('Note: "%s" not added as a %s' % (r, state.lower())) |
| 954 | if errored: |
| 955 | # Try again, adding only those that didn't fail, and only accepting 200. |
| 956 | AddReviewers(host, change, reviewers=(reviewers-errored), |
| 957 | ccs=(ccs-errored), notify=notify, accept_statuses=[200]) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 958 | |
| 959 | |
Aaron Gable | 636b13f | 2017-07-14 10:42:48 -0700 | [diff] [blame] | 960 | def SetReview(host, change, msg=None, labels=None, notify=None, ready=None): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 961 | """Sets labels and/or adds a message to a code review.""" |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 962 | if not msg and not labels: |
| 963 | return |
| 964 | path = 'changes/%s/revisions/current/review' % change |
Jonathan Nieder | 1ea2132 | 2017-11-10 11:45:42 -0800 | [diff] [blame] | 965 | body = {'drafts': 'KEEP'} |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 966 | if msg: |
| 967 | body['message'] = msg |
| 968 | if labels: |
| 969 | body['labels'] = labels |
Aaron Gable | fc62f76 | 2017-07-17 11:12:07 -0700 | [diff] [blame] | 970 | if notify is not None: |
Aaron Gable | 75e7872 | 2017-06-09 10:40:16 -0700 | [diff] [blame] | 971 | body['notify'] = 'ALL' if notify else 'NONE' |
Aaron Gable | 636b13f | 2017-07-14 10:42:48 -0700 | [diff] [blame] | 972 | if ready: |
| 973 | body['ready'] = True |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 974 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
| 975 | response = ReadHttpJsonResponse(conn) |
| 976 | if labels: |
Marc-Antoine Ruel | 8e57b4b | 2019-10-11 01:01:36 +0000 | [diff] [blame] | 977 | for key, val in labels.items(): |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 978 | if ('labels' not in response or key not in response['labels'] or |
| 979 | int(response['labels'][key] != int(val))): |
| 980 | raise GerritError(200, 'Unable to set "%s" label on change %s.' % ( |
| 981 | key, change)) |
Xinan Lin | 0b0738d | 2021-07-27 19:13:49 +0000 | [diff] [blame] | 982 | return response |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 983 | |
| 984 | def ResetReviewLabels(host, change, label, value='0', message=None, |
| 985 | notify=None): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 986 | """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] | 987 | # This is tricky, because we want to work on the "current revision", but |
| 988 | # there's always the risk that "current revision" will change in between |
| 989 | # API calls. So, we check "current revision" at the beginning and end; if |
| 990 | # it has changed, raise an exception. |
| 991 | jmsg = GetChangeCurrentRevision(host, change) |
| 992 | if not jmsg: |
| 993 | raise GerritError( |
| 994 | 200, 'Could not get review information for change "%s"' % change) |
| 995 | value = str(value) |
| 996 | revision = jmsg[0]['current_revision'] |
| 997 | path = 'changes/%s/revisions/%s/review' % (change, revision) |
| 998 | message = message or ( |
| 999 | '%s label set to %s programmatically.' % (label, value)) |
| 1000 | jmsg = GetReview(host, change, revision) |
| 1001 | if not jmsg: |
Quinten Yearsley | 925cedb | 2020-04-13 17:49:39 +0000 | [diff] [blame] | 1002 | raise GerritError(200, 'Could not get review information for revision %s ' |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 1003 | 'of change %s' % (revision, change)) |
| 1004 | for review in jmsg.get('labels', {}).get(label, {}).get('all', []): |
| 1005 | if str(review.get('value', value)) != value: |
| 1006 | body = { |
Jonathan Nieder | 1ea2132 | 2017-11-10 11:45:42 -0800 | [diff] [blame] | 1007 | 'drafts': 'KEEP', |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 1008 | 'message': message, |
| 1009 | 'labels': {label: value}, |
| 1010 | 'on_behalf_of': review['_account_id'], |
| 1011 | } |
| 1012 | if notify: |
| 1013 | body['notify'] = notify |
| 1014 | conn = CreateHttpConn( |
| 1015 | host, path, reqtype='POST', body=body) |
| 1016 | response = ReadHttpJsonResponse(conn) |
| 1017 | if str(response['labels'][label]) != value: |
| 1018 | username = review.get('email', jmsg.get('name', '')) |
| 1019 | raise GerritError(200, 'Unable to set %s label for user "%s"' |
| 1020 | ' on change %s.' % (label, username, change)) |
| 1021 | jmsg = GetChangeCurrentRevision(host, change) |
| 1022 | if not jmsg: |
| 1023 | raise GerritError( |
| 1024 | 200, 'Could not get review information for change "%s"' % change) |
Aravind Vasudevan | c5f0cbb | 2022-01-24 23:56:57 +0000 | [diff] [blame] | 1025 | |
| 1026 | if jmsg[0]['current_revision'] != revision: |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 1027 | raise GerritError(200, 'While resetting labels on change "%s", ' |
| 1028 | 'a new patchset was uploaded.' % change) |
Dan Jacques | 8d11e48 | 2016-11-15 14:25:56 -0800 | [diff] [blame] | 1029 | |
| 1030 | |
LaMont Jones | 9eed423 | 2021-04-02 16:29:49 +0000 | [diff] [blame] | 1031 | def CreateChange(host, project, branch='main', subject='', params=()): |
| 1032 | """ |
| 1033 | Creates a new change. |
| 1034 | |
| 1035 | Args: |
| 1036 | params: A list of additional ChangeInput specifiers, as documented here: |
| 1037 | (e.g. ('is_private', 'true') to mark the change private. |
| 1038 | https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#change-input |
| 1039 | |
| 1040 | Returns: |
| 1041 | ChangeInfo for the new change. |
| 1042 | """ |
| 1043 | path = 'changes/' |
| 1044 | body = {'project': project, 'branch': branch, 'subject': subject} |
Aravind Vasudevan | c5f0cbb | 2022-01-24 23:56:57 +0000 | [diff] [blame] | 1045 | body.update(dict(params)) |
LaMont Jones | 9eed423 | 2021-04-02 16:29:49 +0000 | [diff] [blame] | 1046 | for key in 'project', 'branch', 'subject': |
| 1047 | if not body[key]: |
| 1048 | raise GerritError(200, '%s is required' % key.title()) |
| 1049 | |
| 1050 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
| 1051 | return ReadHttpJsonResponse(conn, accept_statuses=[201]) |
| 1052 | |
| 1053 | |
dimu | 833c94c | 2017-01-18 17:36:15 -0800 | [diff] [blame] | 1054 | def CreateGerritBranch(host, project, branch, commit): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 1055 | """Creates a new branch from given project and commit |
| 1056 | |
dimu | 833c94c | 2017-01-18 17:36:15 -0800 | [diff] [blame] | 1057 | https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-branch |
| 1058 | |
| 1059 | Returns: |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 1060 | A JSON object with 'ref' key. |
dimu | 833c94c | 2017-01-18 17:36:15 -0800 | [diff] [blame] | 1061 | """ |
| 1062 | path = 'projects/%s/branches/%s' % (project, branch) |
| 1063 | body = {'revision': commit} |
| 1064 | conn = CreateHttpConn(host, path, reqtype='PUT', body=body) |
dimu | 7d1af2b | 2017-04-19 16:01:17 -0700 | [diff] [blame] | 1065 | response = ReadHttpJsonResponse(conn, accept_statuses=[201]) |
dimu | 833c94c | 2017-01-18 17:36:15 -0800 | [diff] [blame] | 1066 | if response: |
| 1067 | return response |
| 1068 | raise GerritError(200, 'Unable to create gerrit branch') |
| 1069 | |
| 1070 | |
Michael Moss | b6ce244 | 2021-10-20 04:36:24 +0000 | [diff] [blame] | 1071 | def CreateGerritTag(host, project, tag, commit): |
| 1072 | """Creates a new tag at the given commit. |
| 1073 | |
| 1074 | https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-tag |
| 1075 | |
| 1076 | Returns: |
| 1077 | A JSON object with 'ref' key. |
| 1078 | """ |
| 1079 | path = 'projects/%s/tags/%s' % (project, tag) |
| 1080 | body = {'revision': commit} |
| 1081 | conn = CreateHttpConn(host, path, reqtype='PUT', body=body) |
| 1082 | response = ReadHttpJsonResponse(conn, accept_statuses=[201]) |
| 1083 | if response: |
| 1084 | return response |
| 1085 | raise GerritError(200, 'Unable to create gerrit tag') |
| 1086 | |
| 1087 | |
Josip Sokcevic | df9a802 | 2020-12-08 00:10:19 +0000 | [diff] [blame] | 1088 | def GetHead(host, project): |
| 1089 | """Retrieves current HEAD of Gerrit project |
| 1090 | |
| 1091 | https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-head |
| 1092 | |
| 1093 | Returns: |
| 1094 | A JSON object with 'ref' key. |
| 1095 | """ |
| 1096 | path = 'projects/%s/HEAD' % (project) |
| 1097 | conn = CreateHttpConn(host, path, reqtype='GET') |
| 1098 | response = ReadHttpJsonResponse(conn, accept_statuses=[200]) |
| 1099 | if response: |
| 1100 | return response |
| 1101 | raise GerritError(200, 'Unable to update gerrit HEAD') |
| 1102 | |
| 1103 | |
| 1104 | def UpdateHead(host, project, branch): |
| 1105 | """Updates Gerrit HEAD to point to branch |
| 1106 | |
| 1107 | https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#set-head |
| 1108 | |
| 1109 | Returns: |
| 1110 | A JSON object with 'ref' key. |
| 1111 | """ |
| 1112 | path = 'projects/%s/HEAD' % (project) |
| 1113 | body = {'ref': branch} |
| 1114 | conn = CreateHttpConn(host, path, reqtype='PUT', body=body) |
| 1115 | response = ReadHttpJsonResponse(conn, accept_statuses=[200]) |
| 1116 | if response: |
| 1117 | return response |
| 1118 | raise GerritError(200, 'Unable to update gerrit HEAD') |
| 1119 | |
| 1120 | |
dimu | 833c94c | 2017-01-18 17:36:15 -0800 | [diff] [blame] | 1121 | def GetGerritBranch(host, project, branch): |
Xinan Lin | af79f24 | 2021-08-09 21:23:58 +0000 | [diff] [blame] | 1122 | """Gets a branch info from given project and branch name. |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 1123 | |
| 1124 | See: |
dimu | 833c94c | 2017-01-18 17:36:15 -0800 | [diff] [blame] | 1125 | https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-branch |
| 1126 | |
| 1127 | Returns: |
Xinan Lin | af79f24 | 2021-08-09 21:23:58 +0000 | [diff] [blame] | 1128 | A JSON object with 'revision' key if the branch exists, otherwise None. |
dimu | 833c94c | 2017-01-18 17:36:15 -0800 | [diff] [blame] | 1129 | """ |
| 1130 | path = 'projects/%s/branches/%s' % (project, branch) |
| 1131 | conn = CreateHttpConn(host, path, reqtype='GET') |
Xinan Lin | af79f24 | 2021-08-09 21:23:58 +0000 | [diff] [blame] | 1132 | return ReadHttpJsonResponse(conn, accept_statuses=[200, 404]) |
dimu | 833c94c | 2017-01-18 17:36:15 -0800 | [diff] [blame] | 1133 | |
| 1134 | |
Josip Sokcevic | f736cab | 2020-10-20 23:41:38 +0000 | [diff] [blame] | 1135 | def GetProjectHead(host, project): |
| 1136 | conn = CreateHttpConn(host, |
| 1137 | '/projects/%s/HEAD' % urllib.parse.quote(project, '')) |
| 1138 | return ReadHttpJsonResponse(conn, accept_statuses=[200]) |
| 1139 | |
| 1140 | |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 1141 | def GetAccountDetails(host, account_id='self'): |
| 1142 | """Returns details of the account. |
| 1143 | |
| 1144 | If account_id is not given, uses magic value 'self' which corresponds to |
| 1145 | whichever account user is authenticating as. |
| 1146 | |
| 1147 | Documentation: |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 1148 | https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-account |
Andrii Shyshkalov | ba7b0a4 | 2018-10-15 03:20:35 +0000 | [diff] [blame] | 1149 | |
| 1150 | Returns None if account is not found (i.e., Gerrit returned 404). |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 1151 | """ |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 1152 | conn = CreateHttpConn(host, '/accounts/%s' % account_id) |
Andrii Shyshkalov | ba7b0a4 | 2018-10-15 03:20:35 +0000 | [diff] [blame] | 1153 | return ReadHttpJsonResponse(conn, accept_statuses=[200, 404]) |
| 1154 | |
| 1155 | |
| 1156 | def ValidAccounts(host, accounts, max_threads=10): |
| 1157 | """Returns a mapping from valid account to its details. |
| 1158 | |
| 1159 | Invalid accounts, either not existing or without unique match, |
| 1160 | are not present as returned dictionary keys. |
| 1161 | """ |
Edward Lemur | 0db01f0 | 2019-11-12 22:01:51 +0000 | [diff] [blame] | 1162 | assert not isinstance(accounts, str), type(accounts) |
Andrii Shyshkalov | ba7b0a4 | 2018-10-15 03:20:35 +0000 | [diff] [blame] | 1163 | accounts = list(set(accounts)) |
| 1164 | if not accounts: |
| 1165 | return {} |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 1166 | |
Andrii Shyshkalov | ba7b0a4 | 2018-10-15 03:20:35 +0000 | [diff] [blame] | 1167 | def get_one(account): |
| 1168 | try: |
| 1169 | return account, GetAccountDetails(host, account) |
| 1170 | except GerritError: |
| 1171 | return None, None |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 1172 | |
Andrii Shyshkalov | ba7b0a4 | 2018-10-15 03:20:35 +0000 | [diff] [blame] | 1173 | valid = {} |
| 1174 | with contextlib.closing(ThreadPool(min(max_threads, len(accounts)))) as pool: |
| 1175 | for account, details in pool.map(get_one, accounts): |
| 1176 | if account and details: |
| 1177 | valid[account] = details |
| 1178 | return valid |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 1179 | |
| 1180 | |
Nick Carter | 8692b18 | 2017-11-06 16:30:38 -0800 | [diff] [blame] | 1181 | def PercentEncodeForGitRef(original): |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 1182 | """Applies percent-encoding for strings sent to Gerrit via git ref metadata. |
Nick Carter | 8692b18 | 2017-11-06 16:30:38 -0800 | [diff] [blame] | 1183 | |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 1184 | The encoding used is based on but stricter than URL encoding (Section 2.1 of |
| 1185 | RFC 3986). The only non-escaped characters are alphanumerics, and 'SPACE' |
| 1186 | (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] | 1187 | |
| 1188 | For more information, see the Gerrit docs here: |
| 1189 | |
| 1190 | https://gerrit-review.googlesource.com/Documentation/user-upload.html#message |
| 1191 | """ |
| 1192 | safe = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ' |
| 1193 | encoded = ''.join(c if c in safe else '%%%02X' % ord(c) for c in original) |
| 1194 | |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 1195 | # Spaces are not allowed in git refs; gerrit will interpret either '_' or |
Nick Carter | 8692b18 | 2017-11-06 16:30:38 -0800 | [diff] [blame] | 1196 | # '+' (or '%20') as space. Use '_' since that has been supported the longest. |
| 1197 | return encoded.replace(' ', '_') |
| 1198 | |
| 1199 | |
Dan Jacques | 8d11e48 | 2016-11-15 14:25:56 -0800 | [diff] [blame] | 1200 | @contextlib.contextmanager |
| 1201 | def tempdir(): |
| 1202 | tdir = None |
| 1203 | try: |
| 1204 | tdir = tempfile.mkdtemp(suffix='gerrit_util') |
| 1205 | yield tdir |
| 1206 | finally: |
| 1207 | if tdir: |
| 1208 | gclient_utils.rmtree(tdir) |
Andrii Shyshkalov | 0ec9d15 | 2018-08-23 00:22:58 +0000 | [diff] [blame] | 1209 | |
| 1210 | |
| 1211 | def ChangeIdentifier(project, change_number): |
Edward Lemur | 687ca90 | 2018-12-05 02:30:30 +0000 | [diff] [blame] | 1212 | """Returns change identifier "project~number" suitable for |change| arg of |
Andrii Shyshkalov | 0ec9d15 | 2018-08-23 00:22:58 +0000 | [diff] [blame] | 1213 | this module API. |
| 1214 | |
| 1215 | Such format is allows for more efficient Gerrit routing of HTTP requests, |
| 1216 | comparing to specifying just change_number. |
| 1217 | """ |
| 1218 | assert int(change_number) |
Edward Lemur | 4ba192e | 2019-10-28 20:19:37 +0000 | [diff] [blame] | 1219 | return '%s~%s' % (urllib.parse.quote(project, ''), change_number) |