blob: 7704e23879e90d4a238345fcc01017816529e6d5 [file] [log] [blame]
szager@chromium.orgb4696232013-10-16 19:45:35 +00001# 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 Yearsleyd9cbe7a2019-09-03 16:49:11 +00006Utilities for requesting information for a Gerrit server via HTTPS.
szager@chromium.orgb4696232013-10-16 19:45:35 +00007
8https://gerrit-review.googlesource.com/Documentation/rest-api.html
9"""
10
Raul Tambre80ee78e2019-05-06 22:41:05 +000011from __future__ import print_function
Edward Lemur4ba192e2019-10-28 20:19:37 +000012from __future__ import unicode_literals
Raul Tambre80ee78e2019-05-06 22:41:05 +000013
szager@chromium.orgb4696232013-10-16 19:45:35 +000014import base64
Dan Jacques8d11e482016-11-15 14:25:56 -080015import contextlib
Edward Lemur202c5592019-10-21 22:44:52 +000016import httplib2
szager@chromium.orgb4696232013-10-16 19:45:35 +000017import json
18import logging
19import netrc
20import os
Andrii Shyshkalovd4c86732018-09-25 04:29:31 +000021import random
nodir@chromium.orgce32b6e2014-05-12 20:31:32 +000022import re
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +000023import socket
szager@chromium.orgf202a252014-05-27 18:55:52 +000024import stat
25import sys
Dan Jacques8d11e482016-11-15 14:25:56 -080026import tempfile
szager@chromium.orgb4696232013-10-16 19:45:35 +000027import time
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +000028from multiprocessing.pool import ThreadPool
szager@chromium.orgb4696232013-10-16 19:45:35 +000029
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -070030import auth
Dan Jacques8d11e482016-11-15 14:25:56 -080031import gclient_utils
Edward Lemur5a9ff432018-10-30 19:00:22 +000032import metrics
33import metrics_utils
Aaron Gable8797cab2018-03-06 13:55:00 -080034import subprocess2
szager@chromium.orgf202a252014-05-27 18:55:52 +000035
Edward Lemur4ba192e2019-10-28 20:19:37 +000036from third_party import six
37from six.moves import urllib
38
39if sys.version_info.major == 2:
40 import cookielib
41 from StringIO import StringIO
42else:
43 import http.cookiejar as cookielib
44 from io import StringIO
45
szager@chromium.orgb4696232013-10-16 19:45:35 +000046LOGGER = logging.getLogger()
George Engelbrecht888c0fe2020-04-17 15:00:20 +000047# 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.
49TRY_LIMIT = 5
50SLEEP_TIME = 10.0
51MAX_BACKOFF = 2.2
52MIN_BACKOFF = 1.8
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +000053
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000054# Controls the transport protocol used to communicate with Gerrit.
szager@chromium.orgb4696232013-10-16 19:45:35 +000055# This is parameterized primarily to enable GerritTestCase.
56GERRIT_PROTOCOL = 'https'
57
58
Edward Lemur4ba192e2019-10-28 20:19:37 +000059def 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 Lemura3b6fd02020-03-02 22:16:15 +000065def time_time():
66 # Use this so that it can be mocked in tests without interfering with python
67 # system machinery.
68 return time.time()
69
70
szager@chromium.orgb4696232013-10-16 19:45:35 +000071class GerritError(Exception):
72 """Exception class for errors commuicating with the gerrit-on-borg service."""
Edward Lemur4ba192e2019-10-28 20:19:37 +000073 def __init__(self, http_status, message, *args, **kwargs):
szager@chromium.orgb4696232013-10-16 19:45:35 +000074 super(GerritError, self).__init__(*args, **kwargs)
75 self.http_status = http_status
Edward Lemur4ba192e2019-10-28 20:19:37 +000076 self.message = '(%d) %s' % (self.http_status, message)
nodir@chromium.orgce32b6e2014-05-12 20:31:32 +000077
Josip Sokcevicdf9a8022020-12-08 00:10:19 +000078 def __str__(self):
79 return self.message
80
nodir@chromium.orgce32b6e2014-05-12 20:31:32 +000081
Michael Achenbach6fbf12f2017-07-06 10:54:11 +020082def _QueryString(params, first_param=None):
szager@chromium.orgb4696232013-10-16 19:45:35 +000083 """Encodes query parameters in the key:val[+key:val...] format specified here:
84
85 https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
86 """
Edward Lemur4ba192e2019-10-28 20:19:37 +000087 q = [urllib.parse.quote(first_param)] if first_param else []
Michael Achenbach6fbf12f2017-07-06 10:54:11 +020088 q.extend(['%s:%s' % (key, val) for key, val in params])
szager@chromium.orgb4696232013-10-16 19:45:35 +000089 return '+'.join(q)
90
91
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +000092class Authenticator(object):
93 """Base authenticator class for authenticator implementations to subclass."""
94
95 def get_auth_header(self, host):
96 raise NotImplementedError()
97
98 @staticmethod
99 def get():
100 """Returns: (Authenticator) The identified Authenticator to use.
101
102 Probes the local system and its environment and identifies the
103 Authenticator instance to use.
104 """
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700105 # LUCI Context takes priority since it's normally present only on bots,
106 # which then must use it.
107 if LuciContextAuthenticator.is_luci():
108 return LuciContextAuthenticator()
Edward Lemur57d47422020-03-06 20:43:07 +0000109 # TODO(crbug.com/1059384): Automatically detect when running on cloudtop,
110 # and use CookiesAuthenticator instead.
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000111 if GceAuthenticator.is_gce():
112 return GceAuthenticator()
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000113 return CookiesAuthenticator()
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000114
115
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000116class CookiesAuthenticator(Authenticator):
117 """Authenticator implementation that uses ".netrc" or ".gitcookies" for token.
118
119 Expected case for developer workstations.
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000120 """
121
Vadim Shtayurab250ec12018-10-04 00:21:08 +0000122 _EMPTY = object()
123
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000124 def __init__(self):
Vadim Shtayurab250ec12018-10-04 00:21:08 +0000125 # Credentials will be loaded lazily on first use. This ensures Authenticator
126 # get() can always construct an authenticator, even if something is broken.
127 # This allows 'creds-check' to proceed to actually checking creds later,
128 # rigorously (instead of blowing up with a cryptic error if they are wrong).
129 self._netrc = self._EMPTY
130 self._gitcookies = self._EMPTY
131
132 @property
133 def netrc(self):
134 if self._netrc is self._EMPTY:
135 self._netrc = self._get_netrc()
136 return self._netrc
137
138 @property
139 def gitcookies(self):
140 if self._gitcookies is self._EMPTY:
141 self._gitcookies = self._get_gitcookies()
142 return self._gitcookies
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000143
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000144 @classmethod
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200145 def get_new_password_url(cls, host):
146 assert not host.startswith('http')
147 # Assume *.googlesource.com pattern.
148 parts = host.split('.')
149 if not parts[0].endswith('-review'):
150 parts[0] += '-review'
151 return 'https://%s/new-password' % ('.'.join(parts))
152
153 @classmethod
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000154 def get_new_password_message(cls, host):
William Hessee9e89e32019-03-03 19:02:32 +0000155 if host is None:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000156 return ('Git host for Gerrit upload is unknown. Check your remote '
William Hessee9e89e32019-03-03 19:02:32 +0000157 'and the branch your branch is tracking. This tool assumes '
158 'that you are using a git server at *.googlesource.com.')
Edward Lemur67fccdf2019-10-22 22:17:10 +0000159 url = cls.get_new_password_url(host)
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100160 return 'You can (re)generate your credentials by visiting %s' % url
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000161
162 @classmethod
163 def get_netrc_path(cls):
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000164 path = '_netrc' if sys.platform.startswith('win') else '.netrc'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000165 return os.path.expanduser(os.path.join('~', path))
166
167 @classmethod
168 def _get_netrc(cls):
Dan Jacques8d11e482016-11-15 14:25:56 -0800169 # Buffer the '.netrc' path. Use an empty file if it doesn't exist.
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000170 path = cls.get_netrc_path()
Sylvain Defresne2b138f72018-07-12 08:34:48 +0000171 if not os.path.exists(path):
172 return netrc.netrc(os.devnull)
173
174 st = os.stat(path)
175 if st.st_mode & (stat.S_IRWXG | stat.S_IRWXO):
Raul Tambre80ee78e2019-05-06 22:41:05 +0000176 print(
Sylvain Defresne2b138f72018-07-12 08:34:48 +0000177 'WARNING: netrc file %s cannot be used because its file '
178 'permissions are insecure. netrc file permissions should be '
Raul Tambre80ee78e2019-05-06 22:41:05 +0000179 '600.' % path, file=sys.stderr)
Sylvain Defresne2b138f72018-07-12 08:34:48 +0000180 with open(path) as fd:
181 content = fd.read()
Dan Jacques8d11e482016-11-15 14:25:56 -0800182
183 # Load the '.netrc' file. We strip comments from it because processing them
184 # can trigger a bug in Windows. See crbug.com/664664.
185 content = '\n'.join(l for l in content.splitlines()
186 if l.strip() and not l.strip().startswith('#'))
187 with tempdir() as tdir:
188 netrc_path = os.path.join(tdir, 'netrc')
189 with open(netrc_path, 'w') as fd:
190 fd.write(content)
191 os.chmod(netrc_path, (stat.S_IRUSR | stat.S_IWUSR))
192 return cls._get_netrc_from_path(netrc_path)
193
194 @classmethod
195 def _get_netrc_from_path(cls, path):
196 try:
197 return netrc.netrc(path)
198 except IOError:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000199 print('WARNING: Could not read netrc file %s' % path, file=sys.stderr)
Dan Jacques8d11e482016-11-15 14:25:56 -0800200 return netrc.netrc(os.devnull)
201 except netrc.NetrcParseError as e:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000202 print('ERROR: Cannot use netrc file %s due to a parsing error: %s' %
203 (path, e), file=sys.stderr)
Dan Jacques8d11e482016-11-15 14:25:56 -0800204 return netrc.netrc(os.devnull)
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000205
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000206 @classmethod
207 def get_gitcookies_path(cls):
Ravi Mistry0bfa9ad2016-11-21 12:58:31 -0500208 if os.getenv('GIT_COOKIES_PATH'):
209 return os.getenv('GIT_COOKIES_PATH')
Aaron Gable8797cab2018-03-06 13:55:00 -0800210 try:
Edward Lesmes5a5537d2020-04-01 20:52:30 +0000211 path = subprocess2.check_output(
212 ['git', 'config', '--path', 'http.cookiefile'])
213 return path.decode('utf-8', 'ignore').strip()
Aaron Gable8797cab2018-03-06 13:55:00 -0800214 except subprocess2.CalledProcessError:
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000215 return os.path.expanduser(os.path.join('~', '.gitcookies'))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000216
217 @classmethod
218 def _get_gitcookies(cls):
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000219 gitcookies = {}
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000220 path = cls.get_gitcookies_path()
221 if not os.path.exists(path):
222 return gitcookies
223
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000224 try:
Edward Lemur67fccdf2019-10-22 22:17:10 +0000225 f = gclient_utils.FileRead(path, 'rb').splitlines()
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000226 except IOError:
227 return gitcookies
228
Edward Lemur67fccdf2019-10-22 22:17:10 +0000229 for line in f:
230 try:
231 fields = line.strip().split('\t')
232 if line.strip().startswith('#') or len(fields) != 7:
233 continue
234 domain, xpath, key, value = fields[0], fields[2], fields[5], fields[6]
235 if xpath == '/' and key == 'o':
236 if value.startswith('git-'):
237 login, secret_token = value.split('=', 1)
238 gitcookies[domain] = (login, secret_token)
239 else:
240 gitcookies[domain] = ('', value)
241 except (IndexError, ValueError, TypeError) as exc:
242 LOGGER.warning(exc)
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000243 return gitcookies
244
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100245 def _get_auth_for_host(self, host):
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000246 for domain, creds in self.gitcookies.items():
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000247 if cookielib.domain_match(host, domain):
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100248 return (creds[0], None, creds[1])
249 return self.netrc.authenticators(host)
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000250
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100251 def get_auth_header(self, host):
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700252 a = self._get_auth_for_host(host)
253 if a:
Eric Boren2fb63102018-10-05 13:05:03 +0000254 if a[0]:
Edward Lemur67fccdf2019-10-22 22:17:10 +0000255 secret = base64.b64encode(('%s:%s' % (a[0], a[2])).encode('utf-8'))
256 return 'Basic %s' % secret.decode('utf-8')
Eric Boren2fb63102018-10-05 13:05:03 +0000257 else:
258 return 'Bearer %s' % a[2]
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000259 return None
260
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100261 def get_auth_email(self, host):
262 """Best effort parsing of email to be used for auth for the given host."""
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700263 a = self._get_auth_for_host(host)
264 if not a:
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100265 return None
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700266 login = a[0]
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100267 # login typically looks like 'git-xxx.example.com'
268 if not login.startswith('git-') or '.' not in login:
269 return None
270 username, domain = login[len('git-'):].split('.', 1)
271 return '%s@%s' % (username, domain)
272
Andrii Shyshkalov18975322017-01-25 16:44:13 +0100273
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000274# Backwards compatibility just in case somebody imports this outside of
275# depot_tools.
276NetrcAuthenticator = CookiesAuthenticator
277
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000278
279class GceAuthenticator(Authenticator):
280 """Authenticator implementation that uses GCE metadata service for token.
281 """
282
283 _INFO_URL = 'http://metadata.google.internal'
smut5e9401b2017-08-10 15:22:20 -0700284 _ACQUIRE_URL = ('%s/computeMetadata/v1/instance/'
285 'service-accounts/default/token' % _INFO_URL)
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000286 _ACQUIRE_HEADERS = {"Metadata-Flavor": "Google"}
287
288 _cache_is_gce = None
289 _token_cache = None
290 _token_expiration = None
291
292 @classmethod
293 def is_gce(cls):
Ravi Mistryfad941b2016-11-15 13:00:47 -0500294 if os.getenv('SKIP_GCE_AUTH_FOR_GIT'):
295 return False
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000296 if cls._cache_is_gce is None:
297 cls._cache_is_gce = cls._test_is_gce()
298 return cls._cache_is_gce
299
300 @classmethod
301 def _test_is_gce(cls):
302 # Based on https://cloud.google.com/compute/docs/metadata#runninggce
Edward Lemura3b6fd02020-03-02 22:16:15 +0000303 resp, _ = cls._get(cls._INFO_URL)
304 if resp is None:
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000305 return False
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100306 return resp.get('metadata-flavor') == 'Google'
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000307
308 @staticmethod
309 def _get(url, **kwargs):
George Engelbrecht888c0fe2020-04-17 15:00:20 +0000310 next_delay_sec = 1.0
Edward Lemura3b6fd02020-03-02 22:16:15 +0000311 for i in range(TRY_LIMIT):
Edward Lemur4ba192e2019-10-28 20:19:37 +0000312 p = urllib.parse.urlparse(url)
313 if p.scheme not in ('http', 'https'):
314 raise RuntimeError(
315 "Don't know how to work with protocol '%s'" % protocol)
Edward Lemura3b6fd02020-03-02 22:16:15 +0000316 try:
317 resp, contents = httplib2.Http().request(url, 'GET', **kwargs)
318 except (socket.error, httplib2.HttpLib2Error) as e:
319 LOGGER.debug('GET [%s] raised %s', url, e)
320 return None, None
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000321 LOGGER.debug('GET [%s] #%d/%d (%d)', url, i+1, TRY_LIMIT, resp.status)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000322 if resp.status < 500:
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100323 return (resp, contents)
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000324
Aaron Gable92e9f382017-12-07 11:47:41 -0800325 # Retry server error status codes.
326 LOGGER.warn('Encountered server error')
327 if TRY_LIMIT - i > 1:
328 LOGGER.info('Will retry in %d seconds (%d more times)...',
329 next_delay_sec, TRY_LIMIT - i - 1)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000330 time_sleep(next_delay_sec)
George Engelbrecht888c0fe2020-04-17 15:00:20 +0000331 next_delay_sec *= random.uniform(MIN_BACKOFF, MAX_BACKOFF)
Edward Lemura3b6fd02020-03-02 22:16:15 +0000332 return None, None
Aaron Gable92e9f382017-12-07 11:47:41 -0800333
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000334 @classmethod
335 def _get_token_dict(cls):
Edward Lemura3b6fd02020-03-02 22:16:15 +0000336 # If cached token is valid for at least 25 seconds, return it.
337 if cls._token_cache and time_time() + 25 < cls._token_expiration:
338 return cls._token_cache
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000339
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100340 resp, contents = cls._get(cls._ACQUIRE_URL, headers=cls._ACQUIRE_HEADERS)
Edward Lemura3b6fd02020-03-02 22:16:15 +0000341 if resp is None or resp.status != 200:
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000342 return None
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100343 cls._token_cache = json.loads(contents)
Edward Lemura3b6fd02020-03-02 22:16:15 +0000344 cls._token_expiration = cls._token_cache['expires_in'] + time_time()
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000345 return cls._token_cache
346
347 def get_auth_header(self, _host):
348 token_dict = self._get_token_dict()
349 if not token_dict:
350 return None
351 return '%(token_type)s %(access_token)s' % token_dict
352
353
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700354class LuciContextAuthenticator(Authenticator):
355 """Authenticator implementation that uses LUCI_CONTEXT ambient local auth.
356 """
357
358 @staticmethod
359 def is_luci():
360 return auth.has_luci_context_local_auth()
361
362 def __init__(self):
Edward Lemur5b929a42019-10-21 17:57:39 +0000363 self._authenticator = auth.Authenticator(
364 ' '.join([auth.OAUTH_SCOPE_EMAIL, auth.OAUTH_SCOPE_GERRIT]))
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700365
366 def get_auth_header(self, _host):
Edward Lemur5b929a42019-10-21 17:57:39 +0000367 return 'Bearer %s' % self._authenticator.get_access_token().token
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700368
369
szager@chromium.orgb4696232013-10-16 19:45:35 +0000370def CreateHttpConn(host, path, reqtype='GET', headers=None, body=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000371 """Opens an HTTPS connection to a Gerrit service, and sends a request."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000372 headers = headers or {}
373 bare_host = host.partition(':')[0]
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000374
Edward Lemur447507e2020-03-31 17:33:54 +0000375 a = Authenticator.get()
376 # TODO(crbug.com/1059384): Automatically detect when running on cloudtop.
377 if isinstance(a, GceAuthenticator):
378 print('If you\'re on a cloudtop instance, export '
379 'SKIP_GCE_AUTH_FOR_GIT=1 in your env.')
380
381 a = a.get_auth_header(bare_host)
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700382 if a:
383 headers.setdefault('Authorization', a)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000384 else:
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000385 LOGGER.debug('No authorization found for %s.' % bare_host)
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000386
Dan Jacques6d5bcc22016-11-14 15:32:04 -0800387 url = path
388 if not url.startswith('/'):
389 url = '/' + url
390 if 'Authorization' in headers and not url.startswith('/a/'):
391 url = '/a%s' % url
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000392
szager@chromium.orgb4696232013-10-16 19:45:35 +0000393 if body:
Edward Lemur4ba192e2019-10-28 20:19:37 +0000394 body = json.dumps(body, sort_keys=True)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000395 headers.setdefault('Content-Type', 'application/json')
396 if LOGGER.isEnabledFor(logging.DEBUG):
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000397 LOGGER.debug('%s %s://%s%s' % (reqtype, GERRIT_PROTOCOL, host, url))
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000398 for key, val in headers.items():
szager@chromium.orgb4696232013-10-16 19:45:35 +0000399 if key == 'Authorization':
400 val = 'HIDDEN'
401 LOGGER.debug('%s: %s' % (key, val))
402 if body:
403 LOGGER.debug(body)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000404 conn = httplib2.Http()
405 # HACK: httplib2.Http has no such attribute; we store req_host here for later
Andrii Shyshkalov86c823e2018-09-18 19:51:33 +0000406 # use in ReadHttpResponse.
szager@chromium.orgb4696232013-10-16 19:45:35 +0000407 conn.req_host = host
408 conn.req_params = {
Edward Lemur4ba192e2019-10-28 20:19:37 +0000409 'uri': urllib.parse.urljoin('%s://%s' % (GERRIT_PROTOCOL, host), url),
szager@chromium.orgb4696232013-10-16 19:45:35 +0000410 'method': reqtype,
411 'headers': headers,
412 'body': body,
413 }
szager@chromium.orgb4696232013-10-16 19:45:35 +0000414 return conn
415
416
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700417def ReadHttpResponse(conn, accept_statuses=frozenset([200])):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000418 """Reads an HTTP response from a connection into a string buffer.
szager@chromium.orgb4696232013-10-16 19:45:35 +0000419
420 Args:
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100421 conn: An Http object created by CreateHttpConn above.
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700422 accept_statuses: Treat any of these statuses as success. Default: [200]
423 Common additions include 204, 400, and 404.
szager@chromium.orgb4696232013-10-16 19:45:35 +0000424 Returns: A string buffer containing the connection's reply.
425 """
George Engelbrecht888c0fe2020-04-17 15:00:20 +0000426 sleep_time = SLEEP_TIME
szager@chromium.orgb4696232013-10-16 19:45:35 +0000427 for idx in range(TRY_LIMIT):
Edward Lemur5a9ff432018-10-30 19:00:22 +0000428 before_response = time.time()
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100429 response, contents = conn.request(**conn.req_params)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000430 contents = contents.decode('utf-8', 'replace')
nodir@chromium.orgce32b6e2014-05-12 20:31:32 +0000431
Edward Lemur5a9ff432018-10-30 19:00:22 +0000432 response_time = time.time() - before_response
433 metrics.collector.add_repeated(
434 'http_requests',
435 metrics_utils.extract_http_metrics(
436 conn.req_params['uri'], conn.req_params['method'], response.status,
437 response_time))
438
Edward Lemur4ba192e2019-10-28 20:19:37 +0000439 # If response.status is an accepted status,
440 # or response.status < 500 then the result is final; break retry loop.
441 # If the response is 404/409 it might be because of replication lag,
George Engelbrecht888c0fe2020-04-17 15:00:20 +0000442 # so keep trying anyway. If it is 429, it is generally ok to retry after
443 # a backoff.
Edward Lemur4ba192e2019-10-28 20:19:37 +0000444 if (response.status in accept_statuses
George Engelbrecht888c0fe2020-04-17 15:00:20 +0000445 or response.status < 500 and response.status not in [404, 409, 429]):
Andrii Shyshkalov5b04a572017-01-23 17:44:41 +0100446 LOGGER.debug('got response %d for %s %s', response.status,
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100447 conn.req_params['method'], conn.req_params['uri'])
Michael Mossb40a4512017-10-10 11:07:17 -0700448 # If 404 was in accept_statuses, then it's expected that the file might
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000449 # not exist, so don't return the gitiles error page because that's not
450 # the "content" that was actually requested.
Michael Mossb40a4512017-10-10 11:07:17 -0700451 if response.status == 404:
452 contents = ''
szager@chromium.orgb4696232013-10-16 19:45:35 +0000453 break
Edward Lemur4ba192e2019-10-28 20:19:37 +0000454
Edward Lemur49c8eaf2018-11-07 22:13:12 +0000455 # A status >=500 is assumed to be a possible transient error; retry.
456 http_version = 'HTTP/%s' % ('1.1' if response.version == 11 else '1.0')
457 LOGGER.warn('A transient error occurred while querying %s:\n'
458 '%s %s %s\n'
Edward Lesmesb0739992020-10-09 23:15:44 +0000459 '%s %d %s\n'
460 '%s',
Edward Lemur49c8eaf2018-11-07 22:13:12 +0000461 conn.req_host, conn.req_params['method'],
462 conn.req_params['uri'],
Edward Lesmesb0739992020-10-09 23:15:44 +0000463 http_version, http_version, response.status, response.reason,
464 contents)
Andrii Shyshkalovd4c86732018-09-25 04:29:31 +0000465
Edward Lemur4ba192e2019-10-28 20:19:37 +0000466 if idx < TRY_LIMIT - 1:
Aaron Gable92e9f382017-12-07 11:47:41 -0800467 LOGGER.info('Will retry in %d seconds (%d more times)...',
468 sleep_time, TRY_LIMIT - idx - 1)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000469 time_sleep(sleep_time)
George Engelbrecht888c0fe2020-04-17 15:00:20 +0000470 sleep_time *= random.uniform(MIN_BACKOFF, MAX_BACKOFF)
Edward Lemur83bd7f42018-10-10 00:14:21 +0000471 # end of retries loop
Edward Lemur4ba192e2019-10-28 20:19:37 +0000472
473 if response.status in accept_statuses:
474 return StringIO(contents)
475
476 if response.status in (302, 401, 403):
477 www_authenticate = response.get('www-authenticate')
478 if not www_authenticate:
479 print('Your Gerrit credentials might be misconfigured.')
480 else:
481 auth_match = re.search('realm="([^"]+)"', www_authenticate, re.I)
482 host = auth_match.group(1) if auth_match else conn.req_host
483 print('Authentication failed. Please make sure your .gitcookies '
484 'file has credentials for %s.' % host)
485 print('Try:\n git cl creds-check')
486
487 reason = '%s: %s' % (response.reason, contents)
488 raise GerritError(response.status, reason)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000489
490
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700491def ReadHttpJsonResponse(conn, accept_statuses=frozenset([200])):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000492 """Parses an https response as json."""
Aaron Gable19ee16c2017-04-18 11:56:35 -0700493 fh = ReadHttpResponse(conn, accept_statuses)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000494 # The first line of the response should always be: )]}'
495 s = fh.readline()
496 if s and s.rstrip() != ")]}'":
497 raise GerritError(200, 'Unexpected json output: %s' % s)
498 s = fh.read()
499 if not s:
500 return None
501 return json.loads(s)
502
503
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200504def QueryChanges(host, params, first_param=None, limit=None, o_params=None,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100505 start=None):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000506 """
507 Queries a gerrit-on-borg server for changes matching query terms.
508
509 Args:
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200510 params: A list of key:value pairs for search parameters, as documented
511 here (e.g. ('is', 'owner') for a parameter 'is:owner'):
512 https://gerrit-review.googlesource.com/Documentation/user-search.html#search-operators
szager@chromium.orgb4696232013-10-16 19:45:35 +0000513 first_param: A change identifier
514 limit: Maximum number of results to return.
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100515 start: how many changes to skip (starting with the most recent)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000516 o_params: A list of additional output specifiers, as documented here:
517 https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000518
szager@chromium.orgb4696232013-10-16 19:45:35 +0000519 Returns:
520 A list of json-decoded query results.
521 """
522 # Note that no attempt is made to escape special characters; YMMV.
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200523 if not params and not first_param:
szager@chromium.orgb4696232013-10-16 19:45:35 +0000524 raise RuntimeError('QueryChanges requires search parameters')
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200525 path = 'changes/?q=%s' % _QueryString(params, first_param)
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100526 if start:
527 path = '%s&start=%s' % (path, start)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000528 if limit:
529 path = '%s&n=%d' % (path, limit)
530 if o_params:
531 path = '%s&%s' % (path, '&'.join(['o=%s' % p for p in o_params]))
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700532 return ReadHttpJsonResponse(CreateHttpConn(host, path))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000533
534
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200535def GenerateAllChanges(host, params, first_param=None, limit=500,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100536 o_params=None, start=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000537 """Queries a gerrit-on-borg server for all the changes matching the query
538 terms.
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000539
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100540 WARNING: this is unreliable if a change matching the query is modified while
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000541 this function is being called.
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100542
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000543 A single query to gerrit-on-borg is limited on the number of results by the
544 limit parameter on the request (see QueryChanges) and the server maximum
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100545 limit.
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000546
547 Args:
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200548 params, first_param: Refer to QueryChanges().
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000549 limit: Maximum number of requested changes per query.
550 o_params: Refer to QueryChanges().
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100551 start: Refer to QueryChanges().
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000552
553 Returns:
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100554 A generator object to the list of returned changes.
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000555 """
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100556 already_returned = set()
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000557
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100558 def at_most_once(cls):
559 for cl in cls:
560 if cl['_number'] not in already_returned:
561 already_returned.add(cl['_number'])
562 yield cl
563
564 start = start or 0
565 cur_start = start
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000566 more_changes = True
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100567
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000568 while more_changes:
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100569 # This will fetch changes[start..start+limit] sorted by most recently
570 # updated. Since the rank of any change in this list can be changed any time
571 # (say user posting comment), subsequent calls may overalp like this:
572 # > initial order ABCDEFGH
573 # query[0..3] => ABC
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000574 # > E gets updated. New order: EABCDFGH
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100575 # query[3..6] => CDF # C is a dup
576 # query[6..9] => GH # E is missed.
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200577 page = QueryChanges(host, params, first_param, limit, o_params,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100578 cur_start)
579 for cl in at_most_once(page):
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000580 yield cl
581
582 more_changes = [cl for cl in page if '_more_changes' in cl]
583 if len(more_changes) > 1:
584 raise GerritError(
585 200,
586 'Received %d changes with a _more_changes attribute set but should '
587 'receive at most one.' % len(more_changes))
588 if more_changes:
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100589 cur_start += len(page)
590
591 # If we paged through, query again the first page which in most circumstances
592 # will fetch all changes that were modified while this function was run.
593 if start != cur_start:
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200594 page = QueryChanges(host, params, first_param, limit, o_params, start)
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100595 for cl in at_most_once(page):
596 yield cl
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000597
598
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200599def MultiQueryChanges(host, params, change_list, limit=None, o_params=None,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100600 start=None):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000601 """Initiate a query composed of multiple sets of query parameters."""
602 if not change_list:
603 raise RuntimeError(
604 "MultiQueryChanges requires a list of change numbers/id's")
Edward Lemur4ba192e2019-10-28 20:19:37 +0000605 q = ['q=%s' % '+OR+'.join([urllib.parse.quote(str(x)) for x in change_list])]
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200606 if params:
607 q.append(_QueryString(params))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000608 if limit:
609 q.append('n=%d' % limit)
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100610 if start:
611 q.append('S=%s' % start)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000612 if o_params:
613 q.extend(['o=%s' % p for p in o_params])
614 path = 'changes/?%s' % '&'.join(q)
615 try:
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700616 result = ReadHttpJsonResponse(CreateHttpConn(host, path))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000617 except GerritError as e:
618 msg = '%s:\n%s' % (e.message, path)
619 raise GerritError(e.http_status, msg)
620 return result
621
622
623def GetGerritFetchUrl(host):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000624 """Given a Gerrit host name returns URL of a Gerrit instance to fetch from."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000625 return '%s://%s/' % (GERRIT_PROTOCOL, host)
626
627
Edward Lemur687ca902018-12-05 02:30:30 +0000628def GetCodeReviewTbrScore(host, project):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000629 """Given a Gerrit host name and project, return the Code-Review score for TBR.
Edward Lemur687ca902018-12-05 02:30:30 +0000630 """
Edward Lemur4ba192e2019-10-28 20:19:37 +0000631 conn = CreateHttpConn(
632 host, '/projects/%s' % urllib.parse.quote(project, ''))
Edward Lemur687ca902018-12-05 02:30:30 +0000633 project = ReadHttpJsonResponse(conn)
634 if ('labels' not in project
635 or 'Code-Review' not in project['labels']
636 or 'values' not in project['labels']['Code-Review']):
637 return 1
638 return max([int(x) for x in project['labels']['Code-Review']['values']])
639
640
szager@chromium.orgb4696232013-10-16 19:45:35 +0000641def GetChangePageUrl(host, change_number):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000642 """Given a Gerrit host name and change number, returns change page URL."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000643 return '%s://%s/#/c/%d/' % (GERRIT_PROTOCOL, host, change_number)
644
645
646def GetChangeUrl(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000647 """Given a Gerrit host name and change ID, returns a URL for the change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000648 return '%s://%s/a/changes/%s' % (GERRIT_PROTOCOL, host, change)
649
650
651def GetChange(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000652 """Queries a Gerrit server for information about a single change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000653 path = 'changes/%s' % change
654 return ReadHttpJsonResponse(CreateHttpConn(host, path))
655
656
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700657def GetChangeDetail(host, change, o_params=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000658 """Queries a Gerrit server for extended information about a single change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000659 path = 'changes/%s/detail' % change
660 if o_params:
661 path += '?%s' % '&'.join(['o=%s' % p for p in o_params])
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700662 return ReadHttpJsonResponse(CreateHttpConn(host, path))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000663
664
agable32978d92016-11-01 12:55:02 -0700665def GetChangeCommit(host, change, revision='current'):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000666 """Query a Gerrit server for a revision associated with a change."""
agable32978d92016-11-01 12:55:02 -0700667 path = 'changes/%s/revisions/%s/commit?links' % (change, revision)
668 return ReadHttpJsonResponse(CreateHttpConn(host, path))
669
670
szager@chromium.orgb4696232013-10-16 19:45:35 +0000671def GetChangeCurrentRevision(host, change):
672 """Get information about the latest revision for a given change."""
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200673 return QueryChanges(host, [], change, o_params=('CURRENT_REVISION',))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000674
675
676def GetChangeRevisions(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000677 """Gets information about all revisions associated with a change."""
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200678 return QueryChanges(host, [], change, o_params=('ALL_REVISIONS',))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000679
680
681def GetChangeReview(host, change, revision=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000682 """Gets the current review information for a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000683 if not revision:
684 jmsg = GetChangeRevisions(host, change)
685 if not jmsg:
686 return None
687 elif len(jmsg) > 1:
688 raise GerritError(200, 'Multiple changes found for ChangeId %s.' % change)
689 revision = jmsg[0]['current_revision']
690 path = 'changes/%s/revisions/%s/review'
691 return ReadHttpJsonResponse(CreateHttpConn(host, path))
692
693
Aaron Gable0ffdf2d2017-06-05 13:01:17 -0700694def GetChangeComments(host, change):
695 """Get the line- and file-level comments on a change."""
696 path = 'changes/%s/comments' % change
697 return ReadHttpJsonResponse(CreateHttpConn(host, path))
698
699
Quinten Yearsley0e617c02019-02-20 00:37:03 +0000700def GetChangeRobotComments(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000701 """Gets the line- and file-level robot comments on a change."""
Quinten Yearsley0e617c02019-02-20 00:37:03 +0000702 path = 'changes/%s/robotcomments' % change
703 return ReadHttpJsonResponse(CreateHttpConn(host, path))
704
705
szager@chromium.orgb4696232013-10-16 19:45:35 +0000706def AbandonChange(host, change, msg=''):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000707 """Abandons a Gerrit change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000708 path = 'changes/%s/abandon' % change
tandrii@chromium.orgc7da66a2016-03-24 09:52:24 +0000709 body = {'message': msg} if msg else {}
szager@chromium.orgb4696232013-10-16 19:45:35 +0000710 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700711 return ReadHttpJsonResponse(conn)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000712
713
Josip Sokcevicc39ab992020-09-24 20:09:15 +0000714def MoveChange(host, change, destination_branch):
715 """Move a Gerrit change to different destination branch."""
716 path = 'changes/%s/move' % change
Mike Frysingerf1c7d0d2020-12-15 20:05:36 +0000717 body = {'destination_branch': destination_branch,
718 'keep_all_votes': True}
Josip Sokcevicc39ab992020-09-24 20:09:15 +0000719 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
720 return ReadHttpJsonResponse(conn)
721
722
723
szager@chromium.orgb4696232013-10-16 19:45:35 +0000724def RestoreChange(host, change, msg=''):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000725 """Restores a previously abandoned change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000726 path = 'changes/%s/restore' % change
tandrii@chromium.orgc7da66a2016-03-24 09:52:24 +0000727 body = {'message': msg} if msg else {}
szager@chromium.orgb4696232013-10-16 19:45:35 +0000728 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700729 return ReadHttpJsonResponse(conn)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000730
731
732def SubmitChange(host, change, wait_for_merge=True):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000733 """Submits a Gerrit change via Gerrit."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000734 path = 'changes/%s/submit' % change
735 body = {'wait_for_merge': wait_for_merge}
736 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700737 return ReadHttpJsonResponse(conn)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000738
739
dsansomee2d6fd92016-09-08 00:10:47 -0700740def HasPendingChangeEdit(host, change):
741 conn = CreateHttpConn(host, 'changes/%s/edit' % change)
742 try:
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700743 ReadHttpResponse(conn)
dsansomee2d6fd92016-09-08 00:10:47 -0700744 except GerritError as e:
Aaron Gable19ee16c2017-04-18 11:56:35 -0700745 # 204 No Content means no pending change.
746 if e.http_status == 204:
747 return False
748 raise
749 return True
dsansomee2d6fd92016-09-08 00:10:47 -0700750
751
752def DeletePendingChangeEdit(host, change):
753 conn = CreateHttpConn(host, 'changes/%s/edit' % change, reqtype='DELETE')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000754 # On success, Gerrit returns status 204; if the edit was already deleted it
Aaron Gable19ee16c2017-04-18 11:56:35 -0700755 # returns 404. Anything else is an error.
756 ReadHttpResponse(conn, accept_statuses=[204, 404])
dsansomee2d6fd92016-09-08 00:10:47 -0700757
758
Andrii Shyshkalovea4fc832016-12-01 14:53:23 +0100759def SetCommitMessage(host, change, description, notify='ALL'):
scottmg@chromium.org6d1266e2016-04-26 11:12:26 +0000760 """Updates a commit message."""
Aaron Gable7625d882017-06-26 09:47:26 -0700761 assert notify in ('ALL', 'NONE')
762 path = 'changes/%s/message' % change
Aaron Gable5a4ef452017-08-24 13:19:56 -0700763 body = {'message': description, 'notify': notify}
Aaron Gable7625d882017-06-26 09:47:26 -0700764 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
scottmg@chromium.org6d1266e2016-04-26 11:12:26 +0000765 try:
Aaron Gable7625d882017-06-26 09:47:26 -0700766 ReadHttpResponse(conn, accept_statuses=[200, 204])
767 except GerritError as e:
768 raise GerritError(
769 e.http_status,
770 'Received unexpected http status while editing message '
771 'in change %s' % change)
scottmg@chromium.org6d1266e2016-04-26 11:12:26 +0000772
773
Edward Lesmes110823b2021-02-05 21:42:27 +0000774def IsCodeOwnersEnabled(host):
775 """Check if the code-owners plugin is enabled for the host."""
776 path = 'config/server/capabilities'
777 capabilities = ReadHttpJsonResponse(CreateHttpConn(host, path))
778 return 'code-owners-checkCodeOwner' in capabilities
779
780
Gavin Makc94b21d2020-12-10 20:27:32 +0000781def GetOwnersForFile(host, project, branch, path, limit=100,
Gavin Mak7d690052021-02-25 19:14:22 +0000782 resolve_all_users=True, o_params=('DETAILS',)):
Gavin Makc94b21d2020-12-10 20:27:32 +0000783 """Gets information about owners attached to a file."""
784 path = 'projects/%s/branches/%s/code_owners/%s' % (
785 urllib.parse.quote(project, ''),
786 urllib.parse.quote(branch, ''),
787 urllib.parse.quote(path, ''))
Gavin Mak7d690052021-02-25 19:14:22 +0000788 q = ['resolve-all-users=%s' % json.dumps(resolve_all_users)]
Gavin Makc94b21d2020-12-10 20:27:32 +0000789 if limit:
790 q.append('n=%d' % limit)
791 if o_params:
792 q.extend(['o=%s' % p for p in o_params])
793 if q:
794 path = '%s?%s' % (path, '&'.join(q))
795 return ReadHttpJsonResponse(CreateHttpConn(host, path))
796
797
szager@chromium.orgb4696232013-10-16 19:45:35 +0000798def GetReviewers(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000799 """Gets information about all reviewers attached to a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000800 path = 'changes/%s/reviewers' % change
801 return ReadHttpJsonResponse(CreateHttpConn(host, path))
802
803
804def GetReview(host, change, revision):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000805 """Gets review information about a specific revision of a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000806 path = 'changes/%s/revisions/%s/review' % (change, revision)
807 return ReadHttpJsonResponse(CreateHttpConn(host, path))
808
809
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700810def AddReviewers(host, change, reviewers=None, ccs=None, notify=True,
811 accept_statuses=frozenset([200, 400, 422])):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000812 """Add reviewers to a change."""
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700813 if not reviewers and not ccs:
Aaron Gabledf86e302016-11-08 10:48:03 -0800814 return None
Wiktor Garbacz6d0d0442017-05-15 12:34:40 +0200815 if not change:
816 return None
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700817 reviewers = frozenset(reviewers or [])
818 ccs = frozenset(ccs or [])
819 path = 'changes/%s/revisions/current/review' % change
820
821 body = {
Jonathan Nieder1ea21322017-11-10 11:45:42 -0800822 'drafts': 'KEEP',
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700823 'reviewers': [],
824 'notify': 'ALL' if notify else 'NONE',
825 }
826 for r in sorted(reviewers | ccs):
827 state = 'REVIEWER' if r in reviewers else 'CC'
828 body['reviewers'].append({
829 'reviewer': r,
830 'state': state,
831 'notify': 'NONE', # We handled `notify` argument above.
Raul Tambre80ee78e2019-05-06 22:41:05 +0000832 })
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700833
834 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
835 # Gerrit will return 400 if one or more of the requested reviewers are
836 # unprocessable. We read the response object to see which were rejected,
837 # warn about them, and retry with the remainder.
838 resp = ReadHttpJsonResponse(conn, accept_statuses=accept_statuses)
839
840 errored = set()
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000841 for result in resp.get('reviewers', {}).values():
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700842 r = result.get('input')
843 state = 'REVIEWER' if r in reviewers else 'CC'
844 if result.get('error'):
845 errored.add(r)
846 LOGGER.warn('Note: "%s" not added as a %s' % (r, state.lower()))
847 if errored:
848 # Try again, adding only those that didn't fail, and only accepting 200.
849 AddReviewers(host, change, reviewers=(reviewers-errored),
850 ccs=(ccs-errored), notify=notify, accept_statuses=[200])
szager@chromium.orgb4696232013-10-16 19:45:35 +0000851
852
Aaron Gable636b13f2017-07-14 10:42:48 -0700853def SetReview(host, change, msg=None, labels=None, notify=None, ready=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000854 """Sets labels and/or adds a message to a code review."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000855 if not msg and not labels:
856 return
857 path = 'changes/%s/revisions/current/review' % change
Jonathan Nieder1ea21322017-11-10 11:45:42 -0800858 body = {'drafts': 'KEEP'}
szager@chromium.orgb4696232013-10-16 19:45:35 +0000859 if msg:
860 body['message'] = msg
861 if labels:
862 body['labels'] = labels
Aaron Gablefc62f762017-07-17 11:12:07 -0700863 if notify is not None:
Aaron Gable75e78722017-06-09 10:40:16 -0700864 body['notify'] = 'ALL' if notify else 'NONE'
Aaron Gable636b13f2017-07-14 10:42:48 -0700865 if ready:
866 body['ready'] = True
szager@chromium.orgb4696232013-10-16 19:45:35 +0000867 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
868 response = ReadHttpJsonResponse(conn)
869 if labels:
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000870 for key, val in labels.items():
szager@chromium.orgb4696232013-10-16 19:45:35 +0000871 if ('labels' not in response or key not in response['labels'] or
872 int(response['labels'][key] != int(val))):
873 raise GerritError(200, 'Unable to set "%s" label on change %s.' % (
874 key, change))
875
876
877def ResetReviewLabels(host, change, label, value='0', message=None,
878 notify=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000879 """Resets the value of a given label for all reviewers on a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000880 # This is tricky, because we want to work on the "current revision", but
881 # there's always the risk that "current revision" will change in between
882 # API calls. So, we check "current revision" at the beginning and end; if
883 # it has changed, raise an exception.
884 jmsg = GetChangeCurrentRevision(host, change)
885 if not jmsg:
886 raise GerritError(
887 200, 'Could not get review information for change "%s"' % change)
888 value = str(value)
889 revision = jmsg[0]['current_revision']
890 path = 'changes/%s/revisions/%s/review' % (change, revision)
891 message = message or (
892 '%s label set to %s programmatically.' % (label, value))
893 jmsg = GetReview(host, change, revision)
894 if not jmsg:
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000895 raise GerritError(200, 'Could not get review information for revision %s '
szager@chromium.orgb4696232013-10-16 19:45:35 +0000896 'of change %s' % (revision, change))
897 for review in jmsg.get('labels', {}).get(label, {}).get('all', []):
898 if str(review.get('value', value)) != value:
899 body = {
Jonathan Nieder1ea21322017-11-10 11:45:42 -0800900 'drafts': 'KEEP',
szager@chromium.orgb4696232013-10-16 19:45:35 +0000901 'message': message,
902 'labels': {label: value},
903 'on_behalf_of': review['_account_id'],
904 }
905 if notify:
906 body['notify'] = notify
907 conn = CreateHttpConn(
908 host, path, reqtype='POST', body=body)
909 response = ReadHttpJsonResponse(conn)
910 if str(response['labels'][label]) != value:
911 username = review.get('email', jmsg.get('name', ''))
912 raise GerritError(200, 'Unable to set %s label for user "%s"'
913 ' on change %s.' % (label, username, change))
914 jmsg = GetChangeCurrentRevision(host, change)
915 if not jmsg:
916 raise GerritError(
917 200, 'Could not get review information for change "%s"' % change)
918 elif jmsg[0]['current_revision'] != revision:
919 raise GerritError(200, 'While resetting labels on change "%s", '
920 'a new patchset was uploaded.' % change)
Dan Jacques8d11e482016-11-15 14:25:56 -0800921
922
dimu833c94c2017-01-18 17:36:15 -0800923def CreateGerritBranch(host, project, branch, commit):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000924 """Creates a new branch from given project and commit
925
dimu833c94c2017-01-18 17:36:15 -0800926 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-branch
927
928 Returns:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000929 A JSON object with 'ref' key.
dimu833c94c2017-01-18 17:36:15 -0800930 """
931 path = 'projects/%s/branches/%s' % (project, branch)
932 body = {'revision': commit}
933 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
dimu7d1af2b2017-04-19 16:01:17 -0700934 response = ReadHttpJsonResponse(conn, accept_statuses=[201])
dimu833c94c2017-01-18 17:36:15 -0800935 if response:
936 return response
937 raise GerritError(200, 'Unable to create gerrit branch')
938
939
Josip Sokcevicdf9a8022020-12-08 00:10:19 +0000940def GetHead(host, project):
941 """Retrieves current HEAD of Gerrit project
942
943 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-head
944
945 Returns:
946 A JSON object with 'ref' key.
947 """
948 path = 'projects/%s/HEAD' % (project)
949 conn = CreateHttpConn(host, path, reqtype='GET')
950 response = ReadHttpJsonResponse(conn, accept_statuses=[200])
951 if response:
952 return response
953 raise GerritError(200, 'Unable to update gerrit HEAD')
954
955
956def UpdateHead(host, project, branch):
957 """Updates Gerrit HEAD to point to branch
958
959 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#set-head
960
961 Returns:
962 A JSON object with 'ref' key.
963 """
964 path = 'projects/%s/HEAD' % (project)
965 body = {'ref': branch}
966 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
967 response = ReadHttpJsonResponse(conn, accept_statuses=[200])
968 if response:
969 return response
970 raise GerritError(200, 'Unable to update gerrit HEAD')
971
972
dimu833c94c2017-01-18 17:36:15 -0800973def GetGerritBranch(host, project, branch):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000974 """Gets a branch from given project and commit.
975
976 See:
dimu833c94c2017-01-18 17:36:15 -0800977 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-branch
978
979 Returns:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000980 A JSON object with 'revision' key.
dimu833c94c2017-01-18 17:36:15 -0800981 """
982 path = 'projects/%s/branches/%s' % (project, branch)
983 conn = CreateHttpConn(host, path, reqtype='GET')
984 response = ReadHttpJsonResponse(conn)
985 if response:
986 return response
987 raise GerritError(200, 'Unable to get gerrit branch')
988
989
Josip Sokcevicf736cab2020-10-20 23:41:38 +0000990def GetProjectHead(host, project):
991 conn = CreateHttpConn(host,
992 '/projects/%s/HEAD' % urllib.parse.quote(project, ''))
993 return ReadHttpJsonResponse(conn, accept_statuses=[200])
994
995
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100996def GetAccountDetails(host, account_id='self'):
997 """Returns details of the account.
998
999 If account_id is not given, uses magic value 'self' which corresponds to
1000 whichever account user is authenticating as.
1001
1002 Documentation:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001003 https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-account
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +00001004
1005 Returns None if account is not found (i.e., Gerrit returned 404).
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001006 """
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001007 conn = CreateHttpConn(host, '/accounts/%s' % account_id)
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +00001008 return ReadHttpJsonResponse(conn, accept_statuses=[200, 404])
1009
1010
1011def ValidAccounts(host, accounts, max_threads=10):
1012 """Returns a mapping from valid account to its details.
1013
1014 Invalid accounts, either not existing or without unique match,
1015 are not present as returned dictionary keys.
1016 """
Edward Lemur0db01f02019-11-12 22:01:51 +00001017 assert not isinstance(accounts, str), type(accounts)
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +00001018 accounts = list(set(accounts))
1019 if not accounts:
1020 return {}
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001021
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +00001022 def get_one(account):
1023 try:
1024 return account, GetAccountDetails(host, account)
1025 except GerritError:
1026 return None, None
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001027
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +00001028 valid = {}
1029 with contextlib.closing(ThreadPool(min(max_threads, len(accounts)))) as pool:
1030 for account, details in pool.map(get_one, accounts):
1031 if account and details:
1032 valid[account] = details
1033 return valid
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001034
1035
Nick Carter8692b182017-11-06 16:30:38 -08001036def PercentEncodeForGitRef(original):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001037 """Applies percent-encoding for strings sent to Gerrit via git ref metadata.
Nick Carter8692b182017-11-06 16:30:38 -08001038
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001039 The encoding used is based on but stricter than URL encoding (Section 2.1 of
1040 RFC 3986). The only non-escaped characters are alphanumerics, and 'SPACE'
1041 (U+0020) can be represented as 'LOW LINE' (U+005F) or 'PLUS SIGN' (U+002B).
Nick Carter8692b182017-11-06 16:30:38 -08001042
1043 For more information, see the Gerrit docs here:
1044
1045 https://gerrit-review.googlesource.com/Documentation/user-upload.html#message
1046 """
1047 safe = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '
1048 encoded = ''.join(c if c in safe else '%%%02X' % ord(c) for c in original)
1049
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001050 # Spaces are not allowed in git refs; gerrit will interpret either '_' or
Nick Carter8692b182017-11-06 16:30:38 -08001051 # '+' (or '%20') as space. Use '_' since that has been supported the longest.
1052 return encoded.replace(' ', '_')
1053
1054
Dan Jacques8d11e482016-11-15 14:25:56 -08001055@contextlib.contextmanager
1056def tempdir():
1057 tdir = None
1058 try:
1059 tdir = tempfile.mkdtemp(suffix='gerrit_util')
1060 yield tdir
1061 finally:
1062 if tdir:
1063 gclient_utils.rmtree(tdir)
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001064
1065
1066def ChangeIdentifier(project, change_number):
Edward Lemur687ca902018-12-05 02:30:30 +00001067 """Returns change identifier "project~number" suitable for |change| arg of
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001068 this module API.
1069
1070 Such format is allows for more efficient Gerrit routing of HTTP requests,
1071 comparing to specifying just change_number.
1072 """
1073 assert int(change_number)
Edward Lemur4ba192e2019-10-28 20:19:37 +00001074 return '%s~%s' % (urllib.parse.quote(project, ''), change_number)