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