blob: 629d3a77c8cb6e1f89697e4ac38ba2ec967cd4b0 [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()
Steve Kobes56117722018-09-13 18:18:35 +000047# 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 Lemurb1ae4812019-10-23 04:52:47 +000049TRY_LIMIT = 3
szager@chromium.orgb4696232013-10-16 19:45:35 +000050
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +000051
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000052# Controls the transport protocol used to communicate with Gerrit.
szager@chromium.orgb4696232013-10-16 19:45:35 +000053# This is parameterized primarily to enable GerritTestCase.
54GERRIT_PROTOCOL = 'https'
55
56
Edward Lemur4ba192e2019-10-28 20:19:37 +000057def 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 Lemura3b6fd02020-03-02 22:16:15 +000063def 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.orgb4696232013-10-16 19:45:35 +000069class GerritError(Exception):
70 """Exception class for errors commuicating with the gerrit-on-borg service."""
Edward Lemur4ba192e2019-10-28 20:19:37 +000071 def __init__(self, http_status, message, *args, **kwargs):
szager@chromium.orgb4696232013-10-16 19:45:35 +000072 super(GerritError, self).__init__(*args, **kwargs)
73 self.http_status = http_status
Edward Lemur4ba192e2019-10-28 20:19:37 +000074 self.message = '(%d) %s' % (self.http_status, message)
nodir@chromium.orgce32b6e2014-05-12 20:31:32 +000075
76
Michael Achenbach6fbf12f2017-07-06 10:54:11 +020077def _QueryString(params, first_param=None):
szager@chromium.orgb4696232013-10-16 19:45:35 +000078 """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 Lemur4ba192e2019-10-28 20:19:37 +000082 q = [urllib.parse.quote(first_param)] if first_param else []
Michael Achenbach6fbf12f2017-07-06 10:54:11 +020083 q.extend(['%s:%s' % (key, val) for key, val in params])
szager@chromium.orgb4696232013-10-16 19:45:35 +000084 return '+'.join(q)
85
86
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +000087class 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 Shyshkalov733d4ec2018-04-19 11:48:58 -0700100 # 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 Lemur57d47422020-03-06 20:43:07 +0000104 # TODO(crbug.com/1059384): Automatically detect when running on cloudtop,
105 # and use CookiesAuthenticator instead.
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000106 if GceAuthenticator.is_gce():
107 return GceAuthenticator()
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000108 return CookiesAuthenticator()
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000109
110
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000111class CookiesAuthenticator(Authenticator):
112 """Authenticator implementation that uses ".netrc" or ".gitcookies" for token.
113
114 Expected case for developer workstations.
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000115 """
116
Vadim Shtayurab250ec12018-10-04 00:21:08 +0000117 _EMPTY = object()
118
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000119 def __init__(self):
Vadim Shtayurab250ec12018-10-04 00:21:08 +0000120 # 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.orga5a2c8a2015-09-29 16:22:55 +0000138
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000139 @classmethod
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200140 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.orgfe30f182016-04-13 12:15:04 +0000149 def get_new_password_message(cls, host):
William Hessee9e89e32019-03-03 19:02:32 +0000150 if host is None:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000151 return ('Git host for Gerrit upload is unknown. Check your remote '
William Hessee9e89e32019-03-03 19:02:32 +0000152 'and the branch your branch is tracking. This tool assumes '
153 'that you are using a git server at *.googlesource.com.')
Edward Lemur67fccdf2019-10-22 22:17:10 +0000154 url = cls.get_new_password_url(host)
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100155 return 'You can (re)generate your credentials by visiting %s' % url
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000156
157 @classmethod
158 def get_netrc_path(cls):
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000159 path = '_netrc' if sys.platform.startswith('win') else '.netrc'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000160 return os.path.expanduser(os.path.join('~', path))
161
162 @classmethod
163 def _get_netrc(cls):
Dan Jacques8d11e482016-11-15 14:25:56 -0800164 # Buffer the '.netrc' path. Use an empty file if it doesn't exist.
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000165 path = cls.get_netrc_path()
Sylvain Defresne2b138f72018-07-12 08:34:48 +0000166 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 Tambre80ee78e2019-05-06 22:41:05 +0000171 print(
Sylvain Defresne2b138f72018-07-12 08:34:48 +0000172 'WARNING: netrc file %s cannot be used because its file '
173 'permissions are insecure. netrc file permissions should be '
Raul Tambre80ee78e2019-05-06 22:41:05 +0000174 '600.' % path, file=sys.stderr)
Sylvain Defresne2b138f72018-07-12 08:34:48 +0000175 with open(path) as fd:
176 content = fd.read()
Dan Jacques8d11e482016-11-15 14:25:56 -0800177
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 Tambre80ee78e2019-05-06 22:41:05 +0000194 print('WARNING: Could not read netrc file %s' % path, file=sys.stderr)
Dan Jacques8d11e482016-11-15 14:25:56 -0800195 return netrc.netrc(os.devnull)
196 except netrc.NetrcParseError as e:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000197 print('ERROR: Cannot use netrc file %s due to a parsing error: %s' %
198 (path, e), file=sys.stderr)
Dan Jacques8d11e482016-11-15 14:25:56 -0800199 return netrc.netrc(os.devnull)
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000200
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000201 @classmethod
202 def get_gitcookies_path(cls):
Ravi Mistry0bfa9ad2016-11-21 12:58:31 -0500203 if os.getenv('GIT_COOKIES_PATH'):
204 return os.getenv('GIT_COOKIES_PATH')
Aaron Gable8797cab2018-03-06 13:55:00 -0800205 try:
Edward Lesmes5a5537d2020-04-01 20:52:30 +0000206 path = subprocess2.check_output(
207 ['git', 'config', '--path', 'http.cookiefile'])
208 return path.decode('utf-8', 'ignore').strip()
Aaron Gable8797cab2018-03-06 13:55:00 -0800209 except subprocess2.CalledProcessError:
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000210 return os.path.expanduser(os.path.join('~', '.gitcookies'))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000211
212 @classmethod
213 def _get_gitcookies(cls):
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000214 gitcookies = {}
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000215 path = cls.get_gitcookies_path()
216 if not os.path.exists(path):
217 return gitcookies
218
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000219 try:
Edward Lemur67fccdf2019-10-22 22:17:10 +0000220 f = gclient_utils.FileRead(path, 'rb').splitlines()
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000221 except IOError:
222 return gitcookies
223
Edward Lemur67fccdf2019-10-22 22:17:10 +0000224 for line in f:
225 try:
226 fields = line.strip().split('\t')
227 if line.strip().startswith('#') or len(fields) != 7:
228 continue
229 domain, xpath, key, value = fields[0], fields[2], fields[5], fields[6]
230 if xpath == '/' and key == 'o':
231 if value.startswith('git-'):
232 login, secret_token = value.split('=', 1)
233 gitcookies[domain] = (login, secret_token)
234 else:
235 gitcookies[domain] = ('', value)
236 except (IndexError, ValueError, TypeError) as exc:
237 LOGGER.warning(exc)
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000238 return gitcookies
239
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100240 def _get_auth_for_host(self, host):
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000241 for domain, creds in self.gitcookies.items():
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000242 if cookielib.domain_match(host, domain):
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100243 return (creds[0], None, creds[1])
244 return self.netrc.authenticators(host)
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000245
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100246 def get_auth_header(self, host):
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700247 a = self._get_auth_for_host(host)
248 if a:
Eric Boren2fb63102018-10-05 13:05:03 +0000249 if a[0]:
Edward Lemur67fccdf2019-10-22 22:17:10 +0000250 secret = base64.b64encode(('%s:%s' % (a[0], a[2])).encode('utf-8'))
251 return 'Basic %s' % secret.decode('utf-8')
Eric Boren2fb63102018-10-05 13:05:03 +0000252 else:
253 return 'Bearer %s' % a[2]
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000254 return None
255
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100256 def get_auth_email(self, host):
257 """Best effort parsing of email to be used for auth for the given host."""
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700258 a = self._get_auth_for_host(host)
259 if not a:
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100260 return None
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700261 login = a[0]
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100262 # login typically looks like 'git-xxx.example.com'
263 if not login.startswith('git-') or '.' not in login:
264 return None
265 username, domain = login[len('git-'):].split('.', 1)
266 return '%s@%s' % (username, domain)
267
Andrii Shyshkalov18975322017-01-25 16:44:13 +0100268
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000269# Backwards compatibility just in case somebody imports this outside of
270# depot_tools.
271NetrcAuthenticator = CookiesAuthenticator
272
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000273
274class GceAuthenticator(Authenticator):
275 """Authenticator implementation that uses GCE metadata service for token.
276 """
277
278 _INFO_URL = 'http://metadata.google.internal'
smut5e9401b2017-08-10 15:22:20 -0700279 _ACQUIRE_URL = ('%s/computeMetadata/v1/instance/'
280 'service-accounts/default/token' % _INFO_URL)
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000281 _ACQUIRE_HEADERS = {"Metadata-Flavor": "Google"}
282
283 _cache_is_gce = None
284 _token_cache = None
285 _token_expiration = None
286
287 @classmethod
288 def is_gce(cls):
Ravi Mistryfad941b2016-11-15 13:00:47 -0500289 if os.getenv('SKIP_GCE_AUTH_FOR_GIT'):
290 return False
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000291 if cls._cache_is_gce is None:
292 cls._cache_is_gce = cls._test_is_gce()
293 return cls._cache_is_gce
294
295 @classmethod
296 def _test_is_gce(cls):
297 # Based on https://cloud.google.com/compute/docs/metadata#runninggce
Edward Lemura3b6fd02020-03-02 22:16:15 +0000298 resp, _ = cls._get(cls._INFO_URL)
299 if resp is None:
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000300 return False
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100301 return resp.get('metadata-flavor') == 'Google'
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000302
303 @staticmethod
304 def _get(url, **kwargs):
305 next_delay_sec = 1
Edward Lemura3b6fd02020-03-02 22:16:15 +0000306 for i in range(TRY_LIMIT):
Edward Lemur4ba192e2019-10-28 20:19:37 +0000307 p = urllib.parse.urlparse(url)
308 if p.scheme not in ('http', 'https'):
309 raise RuntimeError(
310 "Don't know how to work with protocol '%s'" % protocol)
Edward Lemura3b6fd02020-03-02 22:16:15 +0000311 try:
312 resp, contents = httplib2.Http().request(url, 'GET', **kwargs)
313 except (socket.error, httplib2.HttpLib2Error) as e:
314 LOGGER.debug('GET [%s] raised %s', url, e)
315 return None, None
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000316 LOGGER.debug('GET [%s] #%d/%d (%d)', url, i+1, TRY_LIMIT, resp.status)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000317 if resp.status < 500:
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100318 return (resp, contents)
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000319
Aaron Gable92e9f382017-12-07 11:47:41 -0800320 # Retry server error status codes.
321 LOGGER.warn('Encountered server error')
322 if TRY_LIMIT - i > 1:
323 LOGGER.info('Will retry in %d seconds (%d more times)...',
324 next_delay_sec, TRY_LIMIT - i - 1)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000325 time_sleep(next_delay_sec)
Aaron Gable92e9f382017-12-07 11:47:41 -0800326 next_delay_sec *= 2
Edward Lemura3b6fd02020-03-02 22:16:15 +0000327 return None, None
Aaron Gable92e9f382017-12-07 11:47:41 -0800328
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000329 @classmethod
330 def _get_token_dict(cls):
Edward Lemura3b6fd02020-03-02 22:16:15 +0000331 # If cached token is valid for at least 25 seconds, return it.
332 if cls._token_cache and time_time() + 25 < cls._token_expiration:
333 return cls._token_cache
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000334
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100335 resp, contents = cls._get(cls._ACQUIRE_URL, headers=cls._ACQUIRE_HEADERS)
Edward Lemura3b6fd02020-03-02 22:16:15 +0000336 if resp is None or resp.status != 200:
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000337 return None
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100338 cls._token_cache = json.loads(contents)
Edward Lemura3b6fd02020-03-02 22:16:15 +0000339 cls._token_expiration = cls._token_cache['expires_in'] + time_time()
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000340 return cls._token_cache
341
342 def get_auth_header(self, _host):
343 token_dict = self._get_token_dict()
344 if not token_dict:
345 return None
346 return '%(token_type)s %(access_token)s' % token_dict
347
348
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700349class LuciContextAuthenticator(Authenticator):
350 """Authenticator implementation that uses LUCI_CONTEXT ambient local auth.
351 """
352
353 @staticmethod
354 def is_luci():
355 return auth.has_luci_context_local_auth()
356
357 def __init__(self):
Edward Lemur5b929a42019-10-21 17:57:39 +0000358 self._authenticator = auth.Authenticator(
359 ' '.join([auth.OAUTH_SCOPE_EMAIL, auth.OAUTH_SCOPE_GERRIT]))
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700360
361 def get_auth_header(self, _host):
Edward Lemur5b929a42019-10-21 17:57:39 +0000362 return 'Bearer %s' % self._authenticator.get_access_token().token
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700363
364
szager@chromium.orgb4696232013-10-16 19:45:35 +0000365def CreateHttpConn(host, path, reqtype='GET', headers=None, body=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000366 """Opens an HTTPS connection to a Gerrit service, and sends a request."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000367 headers = headers or {}
368 bare_host = host.partition(':')[0]
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000369
Edward Lemur447507e2020-03-31 17:33:54 +0000370 a = Authenticator.get()
371 # TODO(crbug.com/1059384): Automatically detect when running on cloudtop.
372 if isinstance(a, GceAuthenticator):
373 print('If you\'re on a cloudtop instance, export '
374 'SKIP_GCE_AUTH_FOR_GIT=1 in your env.')
375
376 a = a.get_auth_header(bare_host)
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700377 if a:
378 headers.setdefault('Authorization', a)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000379 else:
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000380 LOGGER.debug('No authorization found for %s.' % bare_host)
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000381
Dan Jacques6d5bcc22016-11-14 15:32:04 -0800382 url = path
383 if not url.startswith('/'):
384 url = '/' + url
385 if 'Authorization' in headers and not url.startswith('/a/'):
386 url = '/a%s' % url
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000387
szager@chromium.orgb4696232013-10-16 19:45:35 +0000388 if body:
Edward Lemur4ba192e2019-10-28 20:19:37 +0000389 body = json.dumps(body, sort_keys=True)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000390 headers.setdefault('Content-Type', 'application/json')
391 if LOGGER.isEnabledFor(logging.DEBUG):
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000392 LOGGER.debug('%s %s://%s%s' % (reqtype, GERRIT_PROTOCOL, host, url))
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000393 for key, val in headers.items():
szager@chromium.orgb4696232013-10-16 19:45:35 +0000394 if key == 'Authorization':
395 val = 'HIDDEN'
396 LOGGER.debug('%s: %s' % (key, val))
397 if body:
398 LOGGER.debug(body)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000399 conn = httplib2.Http()
400 # HACK: httplib2.Http has no such attribute; we store req_host here for later
Andrii Shyshkalov86c823e2018-09-18 19:51:33 +0000401 # use in ReadHttpResponse.
szager@chromium.orgb4696232013-10-16 19:45:35 +0000402 conn.req_host = host
403 conn.req_params = {
Edward Lemur4ba192e2019-10-28 20:19:37 +0000404 'uri': urllib.parse.urljoin('%s://%s' % (GERRIT_PROTOCOL, host), url),
szager@chromium.orgb4696232013-10-16 19:45:35 +0000405 'method': reqtype,
406 'headers': headers,
407 'body': body,
408 }
szager@chromium.orgb4696232013-10-16 19:45:35 +0000409 return conn
410
411
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700412def ReadHttpResponse(conn, accept_statuses=frozenset([200])):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000413 """Reads an HTTP response from a connection into a string buffer.
szager@chromium.orgb4696232013-10-16 19:45:35 +0000414
415 Args:
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100416 conn: An Http object created by CreateHttpConn above.
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700417 accept_statuses: Treat any of these statuses as success. Default: [200]
418 Common additions include 204, 400, and 404.
szager@chromium.orgb4696232013-10-16 19:45:35 +0000419 Returns: A string buffer containing the connection's reply.
420 """
Steve Kobes56117722018-09-13 18:18:35 +0000421 sleep_time = 1.5
szager@chromium.orgb4696232013-10-16 19:45:35 +0000422 for idx in range(TRY_LIMIT):
Edward Lemur5a9ff432018-10-30 19:00:22 +0000423 before_response = time.time()
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100424 response, contents = conn.request(**conn.req_params)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000425 contents = contents.decode('utf-8', 'replace')
nodir@chromium.orgce32b6e2014-05-12 20:31:32 +0000426
Edward Lemur5a9ff432018-10-30 19:00:22 +0000427 response_time = time.time() - before_response
428 metrics.collector.add_repeated(
429 'http_requests',
430 metrics_utils.extract_http_metrics(
431 conn.req_params['uri'], conn.req_params['method'], response.status,
432 response_time))
433
Edward Lemur4ba192e2019-10-28 20:19:37 +0000434 # If response.status is an accepted status,
435 # or response.status < 500 then the result is final; break retry loop.
436 # If the response is 404/409 it might be because of replication lag,
437 # so keep trying anyway.
438 if (response.status in accept_statuses
439 or response.status < 500 and response.status not in [404, 409]):
Andrii Shyshkalov5b04a572017-01-23 17:44:41 +0100440 LOGGER.debug('got response %d for %s %s', response.status,
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100441 conn.req_params['method'], conn.req_params['uri'])
Michael Mossb40a4512017-10-10 11:07:17 -0700442 # If 404 was in accept_statuses, then it's expected that the file might
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000443 # not exist, so don't return the gitiles error page because that's not
444 # the "content" that was actually requested.
Michael Mossb40a4512017-10-10 11:07:17 -0700445 if response.status == 404:
446 contents = ''
szager@chromium.orgb4696232013-10-16 19:45:35 +0000447 break
Edward Lemur4ba192e2019-10-28 20:19:37 +0000448
Edward Lemur49c8eaf2018-11-07 22:13:12 +0000449 # A status >=500 is assumed to be a possible transient error; retry.
450 http_version = 'HTTP/%s' % ('1.1' if response.version == 11 else '1.0')
451 LOGGER.warn('A transient error occurred while querying %s:\n'
452 '%s %s %s\n'
453 '%s %d %s',
454 conn.req_host, conn.req_params['method'],
455 conn.req_params['uri'],
456 http_version, http_version, response.status, response.reason)
Andrii Shyshkalovd4c86732018-09-25 04:29:31 +0000457
Edward Lemur4ba192e2019-10-28 20:19:37 +0000458 if idx < TRY_LIMIT - 1:
Aaron Gable92e9f382017-12-07 11:47:41 -0800459 LOGGER.info('Will retry in %d seconds (%d more times)...',
460 sleep_time, TRY_LIMIT - idx - 1)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000461 time_sleep(sleep_time)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000462 sleep_time = sleep_time * 2
Edward Lemur83bd7f42018-10-10 00:14:21 +0000463 # end of retries loop
Edward Lemur4ba192e2019-10-28 20:19:37 +0000464
465 if response.status in accept_statuses:
466 return StringIO(contents)
467
468 if response.status in (302, 401, 403):
469 www_authenticate = response.get('www-authenticate')
470 if not www_authenticate:
471 print('Your Gerrit credentials might be misconfigured.')
472 else:
473 auth_match = re.search('realm="([^"]+)"', www_authenticate, re.I)
474 host = auth_match.group(1) if auth_match else conn.req_host
475 print('Authentication failed. Please make sure your .gitcookies '
476 'file has credentials for %s.' % host)
477 print('Try:\n git cl creds-check')
478
479 reason = '%s: %s' % (response.reason, contents)
480 raise GerritError(response.status, reason)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000481
482
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700483def ReadHttpJsonResponse(conn, accept_statuses=frozenset([200])):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000484 """Parses an https response as json."""
Aaron Gable19ee16c2017-04-18 11:56:35 -0700485 fh = ReadHttpResponse(conn, accept_statuses)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000486 # The first line of the response should always be: )]}'
487 s = fh.readline()
488 if s and s.rstrip() != ")]}'":
489 raise GerritError(200, 'Unexpected json output: %s' % s)
490 s = fh.read()
491 if not s:
492 return None
493 return json.loads(s)
494
495
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200496def QueryChanges(host, params, first_param=None, limit=None, o_params=None,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100497 start=None):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000498 """
499 Queries a gerrit-on-borg server for changes matching query terms.
500
501 Args:
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200502 params: A list of key:value pairs for search parameters, as documented
503 here (e.g. ('is', 'owner') for a parameter 'is:owner'):
504 https://gerrit-review.googlesource.com/Documentation/user-search.html#search-operators
szager@chromium.orgb4696232013-10-16 19:45:35 +0000505 first_param: A change identifier
506 limit: Maximum number of results to return.
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100507 start: how many changes to skip (starting with the most recent)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000508 o_params: A list of additional output specifiers, as documented here:
509 https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000510
szager@chromium.orgb4696232013-10-16 19:45:35 +0000511 Returns:
512 A list of json-decoded query results.
513 """
514 # Note that no attempt is made to escape special characters; YMMV.
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200515 if not params and not first_param:
szager@chromium.orgb4696232013-10-16 19:45:35 +0000516 raise RuntimeError('QueryChanges requires search parameters')
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200517 path = 'changes/?q=%s' % _QueryString(params, first_param)
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100518 if start:
519 path = '%s&start=%s' % (path, start)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000520 if limit:
521 path = '%s&n=%d' % (path, limit)
522 if o_params:
523 path = '%s&%s' % (path, '&'.join(['o=%s' % p for p in o_params]))
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700524 return ReadHttpJsonResponse(CreateHttpConn(host, path))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000525
526
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200527def GenerateAllChanges(host, params, first_param=None, limit=500,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100528 o_params=None, start=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000529 """Queries a gerrit-on-borg server for all the changes matching the query
530 terms.
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000531
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100532 WARNING: this is unreliable if a change matching the query is modified while
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000533 this function is being called.
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100534
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000535 A single query to gerrit-on-borg is limited on the number of results by the
536 limit parameter on the request (see QueryChanges) and the server maximum
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100537 limit.
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000538
539 Args:
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200540 params, first_param: Refer to QueryChanges().
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000541 limit: Maximum number of requested changes per query.
542 o_params: Refer to QueryChanges().
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100543 start: Refer to QueryChanges().
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000544
545 Returns:
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100546 A generator object to the list of returned changes.
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000547 """
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100548 already_returned = set()
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000549
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100550 def at_most_once(cls):
551 for cl in cls:
552 if cl['_number'] not in already_returned:
553 already_returned.add(cl['_number'])
554 yield cl
555
556 start = start or 0
557 cur_start = start
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000558 more_changes = True
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100559
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000560 while more_changes:
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100561 # This will fetch changes[start..start+limit] sorted by most recently
562 # updated. Since the rank of any change in this list can be changed any time
563 # (say user posting comment), subsequent calls may overalp like this:
564 # > initial order ABCDEFGH
565 # query[0..3] => ABC
566 # > E get's updated. New order: EABCDFGH
567 # query[3..6] => CDF # C is a dup
568 # query[6..9] => GH # E is missed.
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200569 page = QueryChanges(host, params, first_param, limit, o_params,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100570 cur_start)
571 for cl in at_most_once(page):
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000572 yield cl
573
574 more_changes = [cl for cl in page if '_more_changes' in cl]
575 if len(more_changes) > 1:
576 raise GerritError(
577 200,
578 'Received %d changes with a _more_changes attribute set but should '
579 'receive at most one.' % len(more_changes))
580 if more_changes:
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100581 cur_start += len(page)
582
583 # If we paged through, query again the first page which in most circumstances
584 # will fetch all changes that were modified while this function was run.
585 if start != cur_start:
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200586 page = QueryChanges(host, params, first_param, limit, o_params, start)
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100587 for cl in at_most_once(page):
588 yield cl
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000589
590
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200591def MultiQueryChanges(host, params, change_list, limit=None, o_params=None,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100592 start=None):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000593 """Initiate a query composed of multiple sets of query parameters."""
594 if not change_list:
595 raise RuntimeError(
596 "MultiQueryChanges requires a list of change numbers/id's")
Edward Lemur4ba192e2019-10-28 20:19:37 +0000597 q = ['q=%s' % '+OR+'.join([urllib.parse.quote(str(x)) for x in change_list])]
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200598 if params:
599 q.append(_QueryString(params))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000600 if limit:
601 q.append('n=%d' % limit)
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100602 if start:
603 q.append('S=%s' % start)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000604 if o_params:
605 q.extend(['o=%s' % p for p in o_params])
606 path = 'changes/?%s' % '&'.join(q)
607 try:
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700608 result = ReadHttpJsonResponse(CreateHttpConn(host, path))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000609 except GerritError as e:
610 msg = '%s:\n%s' % (e.message, path)
611 raise GerritError(e.http_status, msg)
612 return result
613
614
615def GetGerritFetchUrl(host):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000616 """Given a Gerrit host name returns URL of a Gerrit instance to fetch from."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000617 return '%s://%s/' % (GERRIT_PROTOCOL, host)
618
619
Edward Lemur687ca902018-12-05 02:30:30 +0000620def GetCodeReviewTbrScore(host, project):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000621 """Given a Gerrit host name and project, return the Code-Review score for TBR.
Edward Lemur687ca902018-12-05 02:30:30 +0000622 """
Edward Lemur4ba192e2019-10-28 20:19:37 +0000623 conn = CreateHttpConn(
624 host, '/projects/%s' % urllib.parse.quote(project, ''))
Edward Lemur687ca902018-12-05 02:30:30 +0000625 project = ReadHttpJsonResponse(conn)
626 if ('labels' not in project
627 or 'Code-Review' not in project['labels']
628 or 'values' not in project['labels']['Code-Review']):
629 return 1
630 return max([int(x) for x in project['labels']['Code-Review']['values']])
631
632
szager@chromium.orgb4696232013-10-16 19:45:35 +0000633def GetChangePageUrl(host, change_number):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000634 """Given a Gerrit host name and change number, returns change page URL."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000635 return '%s://%s/#/c/%d/' % (GERRIT_PROTOCOL, host, change_number)
636
637
638def GetChangeUrl(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000639 """Given a Gerrit host name and change ID, returns a URL for the change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000640 return '%s://%s/a/changes/%s' % (GERRIT_PROTOCOL, host, change)
641
642
643def GetChange(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000644 """Queries a Gerrit server for information about a single change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000645 path = 'changes/%s' % change
646 return ReadHttpJsonResponse(CreateHttpConn(host, path))
647
648
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700649def GetChangeDetail(host, change, o_params=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000650 """Queries a Gerrit server for extended information about a single change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000651 path = 'changes/%s/detail' % change
652 if o_params:
653 path += '?%s' % '&'.join(['o=%s' % p for p in o_params])
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700654 return ReadHttpJsonResponse(CreateHttpConn(host, path))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000655
656
agable32978d92016-11-01 12:55:02 -0700657def GetChangeCommit(host, change, revision='current'):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000658 """Query a Gerrit server for a revision associated with a change."""
agable32978d92016-11-01 12:55:02 -0700659 path = 'changes/%s/revisions/%s/commit?links' % (change, revision)
660 return ReadHttpJsonResponse(CreateHttpConn(host, path))
661
662
szager@chromium.orgb4696232013-10-16 19:45:35 +0000663def GetChangeCurrentRevision(host, change):
664 """Get information about the latest revision for a given change."""
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200665 return QueryChanges(host, [], change, o_params=('CURRENT_REVISION',))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000666
667
668def GetChangeRevisions(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000669 """Gets information about all revisions associated with a change."""
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200670 return QueryChanges(host, [], change, o_params=('ALL_REVISIONS',))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000671
672
673def GetChangeReview(host, change, revision=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000674 """Gets the current review information for a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000675 if not revision:
676 jmsg = GetChangeRevisions(host, change)
677 if not jmsg:
678 return None
679 elif len(jmsg) > 1:
680 raise GerritError(200, 'Multiple changes found for ChangeId %s.' % change)
681 revision = jmsg[0]['current_revision']
682 path = 'changes/%s/revisions/%s/review'
683 return ReadHttpJsonResponse(CreateHttpConn(host, path))
684
685
Aaron Gable0ffdf2d2017-06-05 13:01:17 -0700686def GetChangeComments(host, change):
687 """Get the line- and file-level comments on a change."""
688 path = 'changes/%s/comments' % change
689 return ReadHttpJsonResponse(CreateHttpConn(host, path))
690
691
Quinten Yearsley0e617c02019-02-20 00:37:03 +0000692def GetChangeRobotComments(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000693 """Gets the line- and file-level robot comments on a change."""
Quinten Yearsley0e617c02019-02-20 00:37:03 +0000694 path = 'changes/%s/robotcomments' % change
695 return ReadHttpJsonResponse(CreateHttpConn(host, path))
696
697
szager@chromium.orgb4696232013-10-16 19:45:35 +0000698def AbandonChange(host, change, msg=''):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000699 """Abandons a Gerrit change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000700 path = 'changes/%s/abandon' % change
tandrii@chromium.orgc7da66a2016-03-24 09:52:24 +0000701 body = {'message': msg} if msg else {}
szager@chromium.orgb4696232013-10-16 19:45:35 +0000702 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700703 return ReadHttpJsonResponse(conn)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000704
705
706def RestoreChange(host, change, msg=''):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000707 """Restores a previously abandoned change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000708 path = 'changes/%s/restore' % 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
714def SubmitChange(host, change, wait_for_merge=True):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000715 """Submits a Gerrit change via Gerrit."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000716 path = 'changes/%s/submit' % change
717 body = {'wait_for_merge': wait_for_merge}
718 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700719 return ReadHttpJsonResponse(conn)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000720
721
dsansomee2d6fd92016-09-08 00:10:47 -0700722def HasPendingChangeEdit(host, change):
723 conn = CreateHttpConn(host, 'changes/%s/edit' % change)
724 try:
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700725 ReadHttpResponse(conn)
dsansomee2d6fd92016-09-08 00:10:47 -0700726 except GerritError as e:
Aaron Gable19ee16c2017-04-18 11:56:35 -0700727 # 204 No Content means no pending change.
728 if e.http_status == 204:
729 return False
730 raise
731 return True
dsansomee2d6fd92016-09-08 00:10:47 -0700732
733
734def DeletePendingChangeEdit(host, change):
735 conn = CreateHttpConn(host, 'changes/%s/edit' % change, reqtype='DELETE')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000736 # On success, Gerrit returns status 204; if the edit was already deleted it
Aaron Gable19ee16c2017-04-18 11:56:35 -0700737 # returns 404. Anything else is an error.
738 ReadHttpResponse(conn, accept_statuses=[204, 404])
dsansomee2d6fd92016-09-08 00:10:47 -0700739
740
Andrii Shyshkalovea4fc832016-12-01 14:53:23 +0100741def SetCommitMessage(host, change, description, notify='ALL'):
scottmg@chromium.org6d1266e2016-04-26 11:12:26 +0000742 """Updates a commit message."""
Aaron Gable7625d882017-06-26 09:47:26 -0700743 assert notify in ('ALL', 'NONE')
744 path = 'changes/%s/message' % change
Aaron Gable5a4ef452017-08-24 13:19:56 -0700745 body = {'message': description, 'notify': notify}
Aaron Gable7625d882017-06-26 09:47:26 -0700746 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
scottmg@chromium.org6d1266e2016-04-26 11:12:26 +0000747 try:
Aaron Gable7625d882017-06-26 09:47:26 -0700748 ReadHttpResponse(conn, accept_statuses=[200, 204])
749 except GerritError as e:
750 raise GerritError(
751 e.http_status,
752 'Received unexpected http status while editing message '
753 'in change %s' % change)
scottmg@chromium.org6d1266e2016-04-26 11:12:26 +0000754
755
szager@chromium.orgb4696232013-10-16 19:45:35 +0000756def GetReviewers(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000757 """Gets information about all reviewers attached to a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000758 path = 'changes/%s/reviewers' % change
759 return ReadHttpJsonResponse(CreateHttpConn(host, path))
760
761
762def GetReview(host, change, revision):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000763 """Gets review information about a specific revision of a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000764 path = 'changes/%s/revisions/%s/review' % (change, revision)
765 return ReadHttpJsonResponse(CreateHttpConn(host, path))
766
767
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700768def AddReviewers(host, change, reviewers=None, ccs=None, notify=True,
769 accept_statuses=frozenset([200, 400, 422])):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000770 """Add reviewers to a change."""
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700771 if not reviewers and not ccs:
Aaron Gabledf86e302016-11-08 10:48:03 -0800772 return None
Wiktor Garbacz6d0d0442017-05-15 12:34:40 +0200773 if not change:
774 return None
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700775 reviewers = frozenset(reviewers or [])
776 ccs = frozenset(ccs or [])
777 path = 'changes/%s/revisions/current/review' % change
778
779 body = {
Jonathan Nieder1ea21322017-11-10 11:45:42 -0800780 'drafts': 'KEEP',
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700781 'reviewers': [],
782 'notify': 'ALL' if notify else 'NONE',
783 }
784 for r in sorted(reviewers | ccs):
785 state = 'REVIEWER' if r in reviewers else 'CC'
786 body['reviewers'].append({
787 'reviewer': r,
788 'state': state,
789 'notify': 'NONE', # We handled `notify` argument above.
Raul Tambre80ee78e2019-05-06 22:41:05 +0000790 })
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700791
792 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
793 # Gerrit will return 400 if one or more of the requested reviewers are
794 # unprocessable. We read the response object to see which were rejected,
795 # warn about them, and retry with the remainder.
796 resp = ReadHttpJsonResponse(conn, accept_statuses=accept_statuses)
797
798 errored = set()
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000799 for result in resp.get('reviewers', {}).values():
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700800 r = result.get('input')
801 state = 'REVIEWER' if r in reviewers else 'CC'
802 if result.get('error'):
803 errored.add(r)
804 LOGGER.warn('Note: "%s" not added as a %s' % (r, state.lower()))
805 if errored:
806 # Try again, adding only those that didn't fail, and only accepting 200.
807 AddReviewers(host, change, reviewers=(reviewers-errored),
808 ccs=(ccs-errored), notify=notify, accept_statuses=[200])
szager@chromium.orgb4696232013-10-16 19:45:35 +0000809
810
Aaron Gable636b13f2017-07-14 10:42:48 -0700811def SetReview(host, change, msg=None, labels=None, notify=None, ready=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000812 """Sets labels and/or adds a message to a code review."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000813 if not msg and not labels:
814 return
815 path = 'changes/%s/revisions/current/review' % change
Jonathan Nieder1ea21322017-11-10 11:45:42 -0800816 body = {'drafts': 'KEEP'}
szager@chromium.orgb4696232013-10-16 19:45:35 +0000817 if msg:
818 body['message'] = msg
819 if labels:
820 body['labels'] = labels
Aaron Gablefc62f762017-07-17 11:12:07 -0700821 if notify is not None:
Aaron Gable75e78722017-06-09 10:40:16 -0700822 body['notify'] = 'ALL' if notify else 'NONE'
Aaron Gable636b13f2017-07-14 10:42:48 -0700823 if ready:
824 body['ready'] = True
szager@chromium.orgb4696232013-10-16 19:45:35 +0000825 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
826 response = ReadHttpJsonResponse(conn)
827 if labels:
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000828 for key, val in labels.items():
szager@chromium.orgb4696232013-10-16 19:45:35 +0000829 if ('labels' not in response or key not in response['labels'] or
830 int(response['labels'][key] != int(val))):
831 raise GerritError(200, 'Unable to set "%s" label on change %s.' % (
832 key, change))
833
834
835def ResetReviewLabels(host, change, label, value='0', message=None,
836 notify=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000837 """Resets the value of a given label for all reviewers on a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000838 # This is tricky, because we want to work on the "current revision", but
839 # there's always the risk that "current revision" will change in between
840 # API calls. So, we check "current revision" at the beginning and end; if
841 # it has changed, raise an exception.
842 jmsg = GetChangeCurrentRevision(host, change)
843 if not jmsg:
844 raise GerritError(
845 200, 'Could not get review information for change "%s"' % change)
846 value = str(value)
847 revision = jmsg[0]['current_revision']
848 path = 'changes/%s/revisions/%s/review' % (change, revision)
849 message = message or (
850 '%s label set to %s programmatically.' % (label, value))
851 jmsg = GetReview(host, change, revision)
852 if not jmsg:
853 raise GerritError(200, 'Could not get review information for revison %s '
854 'of change %s' % (revision, change))
855 for review in jmsg.get('labels', {}).get(label, {}).get('all', []):
856 if str(review.get('value', value)) != value:
857 body = {
Jonathan Nieder1ea21322017-11-10 11:45:42 -0800858 'drafts': 'KEEP',
szager@chromium.orgb4696232013-10-16 19:45:35 +0000859 'message': message,
860 'labels': {label: value},
861 'on_behalf_of': review['_account_id'],
862 }
863 if notify:
864 body['notify'] = notify
865 conn = CreateHttpConn(
866 host, path, reqtype='POST', body=body)
867 response = ReadHttpJsonResponse(conn)
868 if str(response['labels'][label]) != value:
869 username = review.get('email', jmsg.get('name', ''))
870 raise GerritError(200, 'Unable to set %s label for user "%s"'
871 ' on change %s.' % (label, username, change))
872 jmsg = GetChangeCurrentRevision(host, change)
873 if not jmsg:
874 raise GerritError(
875 200, 'Could not get review information for change "%s"' % change)
876 elif jmsg[0]['current_revision'] != revision:
877 raise GerritError(200, 'While resetting labels on change "%s", '
878 'a new patchset was uploaded.' % change)
Dan Jacques8d11e482016-11-15 14:25:56 -0800879
880
dimu833c94c2017-01-18 17:36:15 -0800881def CreateGerritBranch(host, project, branch, commit):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000882 """Creates a new branch from given project and commit
883
dimu833c94c2017-01-18 17:36:15 -0800884 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-branch
885
886 Returns:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000887 A JSON object with 'ref' key.
dimu833c94c2017-01-18 17:36:15 -0800888 """
889 path = 'projects/%s/branches/%s' % (project, branch)
890 body = {'revision': commit}
891 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
dimu7d1af2b2017-04-19 16:01:17 -0700892 response = ReadHttpJsonResponse(conn, accept_statuses=[201])
dimu833c94c2017-01-18 17:36:15 -0800893 if response:
894 return response
895 raise GerritError(200, 'Unable to create gerrit branch')
896
897
898def GetGerritBranch(host, project, branch):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000899 """Gets a branch from given project and commit.
900
901 See:
dimu833c94c2017-01-18 17:36:15 -0800902 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-branch
903
904 Returns:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000905 A JSON object with 'revision' key.
dimu833c94c2017-01-18 17:36:15 -0800906 """
907 path = 'projects/%s/branches/%s' % (project, branch)
908 conn = CreateHttpConn(host, path, reqtype='GET')
909 response = ReadHttpJsonResponse(conn)
910 if response:
911 return response
912 raise GerritError(200, 'Unable to get gerrit branch')
913
914
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100915def GetAccountDetails(host, account_id='self'):
916 """Returns details of the account.
917
918 If account_id is not given, uses magic value 'self' which corresponds to
919 whichever account user is authenticating as.
920
921 Documentation:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000922 https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-account
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000923
924 Returns None if account is not found (i.e., Gerrit returned 404).
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100925 """
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100926 conn = CreateHttpConn(host, '/accounts/%s' % account_id)
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000927 return ReadHttpJsonResponse(conn, accept_statuses=[200, 404])
928
929
930def ValidAccounts(host, accounts, max_threads=10):
931 """Returns a mapping from valid account to its details.
932
933 Invalid accounts, either not existing or without unique match,
934 are not present as returned dictionary keys.
935 """
Edward Lemur0db01f02019-11-12 22:01:51 +0000936 assert not isinstance(accounts, str), type(accounts)
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000937 accounts = list(set(accounts))
938 if not accounts:
939 return {}
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000940
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000941 def get_one(account):
942 try:
943 return account, GetAccountDetails(host, account)
944 except GerritError:
945 return None, None
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000946
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000947 valid = {}
948 with contextlib.closing(ThreadPool(min(max_threads, len(accounts)))) as pool:
949 for account, details in pool.map(get_one, accounts):
950 if account and details:
951 valid[account] = details
952 return valid
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100953
954
Nick Carter8692b182017-11-06 16:30:38 -0800955def PercentEncodeForGitRef(original):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000956 """Applies percent-encoding for strings sent to Gerrit via git ref metadata.
Nick Carter8692b182017-11-06 16:30:38 -0800957
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000958 The encoding used is based on but stricter than URL encoding (Section 2.1 of
959 RFC 3986). The only non-escaped characters are alphanumerics, and 'SPACE'
960 (U+0020) can be represented as 'LOW LINE' (U+005F) or 'PLUS SIGN' (U+002B).
Nick Carter8692b182017-11-06 16:30:38 -0800961
962 For more information, see the Gerrit docs here:
963
964 https://gerrit-review.googlesource.com/Documentation/user-upload.html#message
965 """
966 safe = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '
967 encoded = ''.join(c if c in safe else '%%%02X' % ord(c) for c in original)
968
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000969 # Spaces are not allowed in git refs; gerrit will interpret either '_' or
Nick Carter8692b182017-11-06 16:30:38 -0800970 # '+' (or '%20') as space. Use '_' since that has been supported the longest.
971 return encoded.replace(' ', '_')
972
973
Dan Jacques8d11e482016-11-15 14:25:56 -0800974@contextlib.contextmanager
975def tempdir():
976 tdir = None
977 try:
978 tdir = tempfile.mkdtemp(suffix='gerrit_util')
979 yield tdir
980 finally:
981 if tdir:
982 gclient_utils.rmtree(tdir)
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +0000983
984
985def ChangeIdentifier(project, change_number):
Edward Lemur687ca902018-12-05 02:30:30 +0000986 """Returns change identifier "project~number" suitable for |change| arg of
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +0000987 this module API.
988
989 Such format is allows for more efficient Gerrit routing of HTTP requests,
990 comparing to specifying just change_number.
991 """
992 assert int(change_number)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000993 return '%s~%s' % (urllib.parse.quote(project, ''), change_number)