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