blob: 3a56fa9d6cb16cd477eb834cd20390e2bfdc592a [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
szager@chromium.orgb4696232013-10-16 19:45:35 +000063class GerritError(Exception):
64 """Exception class for errors commuicating with the gerrit-on-borg service."""
Edward Lemur4ba192e2019-10-28 20:19:37 +000065 def __init__(self, http_status, message, *args, **kwargs):
szager@chromium.orgb4696232013-10-16 19:45:35 +000066 super(GerritError, self).__init__(*args, **kwargs)
67 self.http_status = http_status
Edward Lemur4ba192e2019-10-28 20:19:37 +000068 self.message = '(%d) %s' % (self.http_status, message)
nodir@chromium.orgce32b6e2014-05-12 20:31:32 +000069
70
Michael Achenbach6fbf12f2017-07-06 10:54:11 +020071def _QueryString(params, first_param=None):
szager@chromium.orgb4696232013-10-16 19:45:35 +000072 """Encodes query parameters in the key:val[+key:val...] format specified here:
73
74 https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
75 """
Edward Lemur4ba192e2019-10-28 20:19:37 +000076 q = [urllib.parse.quote(first_param)] if first_param else []
Michael Achenbach6fbf12f2017-07-06 10:54:11 +020077 q.extend(['%s:%s' % (key, val) for key, val in params])
szager@chromium.orgb4696232013-10-16 19:45:35 +000078 return '+'.join(q)
79
80
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +000081class Authenticator(object):
82 """Base authenticator class for authenticator implementations to subclass."""
83
84 def get_auth_header(self, host):
85 raise NotImplementedError()
86
87 @staticmethod
88 def get():
89 """Returns: (Authenticator) The identified Authenticator to use.
90
91 Probes the local system and its environment and identifies the
92 Authenticator instance to use.
93 """
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -070094 # LUCI Context takes priority since it's normally present only on bots,
95 # which then must use it.
96 if LuciContextAuthenticator.is_luci():
97 return LuciContextAuthenticator()
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +000098 if GceAuthenticator.is_gce():
99 return GceAuthenticator()
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000100 return CookiesAuthenticator()
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000101
102
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000103class CookiesAuthenticator(Authenticator):
104 """Authenticator implementation that uses ".netrc" or ".gitcookies" for token.
105
106 Expected case for developer workstations.
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000107 """
108
Vadim Shtayurab250ec12018-10-04 00:21:08 +0000109 _EMPTY = object()
110
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000111 def __init__(self):
Vadim Shtayurab250ec12018-10-04 00:21:08 +0000112 # Credentials will be loaded lazily on first use. This ensures Authenticator
113 # get() can always construct an authenticator, even if something is broken.
114 # This allows 'creds-check' to proceed to actually checking creds later,
115 # rigorously (instead of blowing up with a cryptic error if they are wrong).
116 self._netrc = self._EMPTY
117 self._gitcookies = self._EMPTY
118
119 @property
120 def netrc(self):
121 if self._netrc is self._EMPTY:
122 self._netrc = self._get_netrc()
123 return self._netrc
124
125 @property
126 def gitcookies(self):
127 if self._gitcookies is self._EMPTY:
128 self._gitcookies = self._get_gitcookies()
129 return self._gitcookies
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000130
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000131 @classmethod
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200132 def get_new_password_url(cls, host):
133 assert not host.startswith('http')
134 # Assume *.googlesource.com pattern.
135 parts = host.split('.')
136 if not parts[0].endswith('-review'):
137 parts[0] += '-review'
138 return 'https://%s/new-password' % ('.'.join(parts))
139
140 @classmethod
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000141 def get_new_password_message(cls, host):
William Hessee9e89e32019-03-03 19:02:32 +0000142 if host is None:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000143 return ('Git host for Gerrit upload is unknown. Check your remote '
William Hessee9e89e32019-03-03 19:02:32 +0000144 'and the branch your branch is tracking. This tool assumes '
145 'that you are using a git server at *.googlesource.com.')
Edward Lemur67fccdf2019-10-22 22:17:10 +0000146 url = cls.get_new_password_url(host)
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100147 return 'You can (re)generate your credentials by visiting %s' % url
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000148
149 @classmethod
150 def get_netrc_path(cls):
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000151 path = '_netrc' if sys.platform.startswith('win') else '.netrc'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000152 return os.path.expanduser(os.path.join('~', path))
153
154 @classmethod
155 def _get_netrc(cls):
Dan Jacques8d11e482016-11-15 14:25:56 -0800156 # Buffer the '.netrc' path. Use an empty file if it doesn't exist.
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000157 path = cls.get_netrc_path()
Sylvain Defresne2b138f72018-07-12 08:34:48 +0000158 if not os.path.exists(path):
159 return netrc.netrc(os.devnull)
160
161 st = os.stat(path)
162 if st.st_mode & (stat.S_IRWXG | stat.S_IRWXO):
Raul Tambre80ee78e2019-05-06 22:41:05 +0000163 print(
Sylvain Defresne2b138f72018-07-12 08:34:48 +0000164 'WARNING: netrc file %s cannot be used because its file '
165 'permissions are insecure. netrc file permissions should be '
Raul Tambre80ee78e2019-05-06 22:41:05 +0000166 '600.' % path, file=sys.stderr)
Sylvain Defresne2b138f72018-07-12 08:34:48 +0000167 with open(path) as fd:
168 content = fd.read()
Dan Jacques8d11e482016-11-15 14:25:56 -0800169
170 # Load the '.netrc' file. We strip comments from it because processing them
171 # can trigger a bug in Windows. See crbug.com/664664.
172 content = '\n'.join(l for l in content.splitlines()
173 if l.strip() and not l.strip().startswith('#'))
174 with tempdir() as tdir:
175 netrc_path = os.path.join(tdir, 'netrc')
176 with open(netrc_path, 'w') as fd:
177 fd.write(content)
178 os.chmod(netrc_path, (stat.S_IRUSR | stat.S_IWUSR))
179 return cls._get_netrc_from_path(netrc_path)
180
181 @classmethod
182 def _get_netrc_from_path(cls, path):
183 try:
184 return netrc.netrc(path)
185 except IOError:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000186 print('WARNING: Could not read netrc file %s' % path, file=sys.stderr)
Dan Jacques8d11e482016-11-15 14:25:56 -0800187 return netrc.netrc(os.devnull)
188 except netrc.NetrcParseError as e:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000189 print('ERROR: Cannot use netrc file %s due to a parsing error: %s' %
190 (path, e), file=sys.stderr)
Dan Jacques8d11e482016-11-15 14:25:56 -0800191 return netrc.netrc(os.devnull)
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000192
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000193 @classmethod
194 def get_gitcookies_path(cls):
Ravi Mistry0bfa9ad2016-11-21 12:58:31 -0500195 if os.getenv('GIT_COOKIES_PATH'):
196 return os.getenv('GIT_COOKIES_PATH')
Aaron Gable8797cab2018-03-06 13:55:00 -0800197 try:
198 return subprocess2.check_output(
199 ['git', 'config', '--path', 'http.cookiefile']).strip()
200 except subprocess2.CalledProcessError:
201 return os.path.join(os.environ['HOME'], '.gitcookies')
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000202
203 @classmethod
204 def _get_gitcookies(cls):
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000205 gitcookies = {}
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000206 path = cls.get_gitcookies_path()
207 if not os.path.exists(path):
208 return gitcookies
209
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000210 try:
Edward Lemur67fccdf2019-10-22 22:17:10 +0000211 f = gclient_utils.FileRead(path, 'rb').splitlines()
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000212 except IOError:
213 return gitcookies
214
Edward Lemur67fccdf2019-10-22 22:17:10 +0000215 for line in f:
216 try:
217 fields = line.strip().split('\t')
218 if line.strip().startswith('#') or len(fields) != 7:
219 continue
220 domain, xpath, key, value = fields[0], fields[2], fields[5], fields[6]
221 if xpath == '/' and key == 'o':
222 if value.startswith('git-'):
223 login, secret_token = value.split('=', 1)
224 gitcookies[domain] = (login, secret_token)
225 else:
226 gitcookies[domain] = ('', value)
227 except (IndexError, ValueError, TypeError) as exc:
228 LOGGER.warning(exc)
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000229 return gitcookies
230
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100231 def _get_auth_for_host(self, host):
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000232 for domain, creds in self.gitcookies.items():
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000233 if cookielib.domain_match(host, domain):
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100234 return (creds[0], None, creds[1])
235 return self.netrc.authenticators(host)
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000236
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100237 def get_auth_header(self, host):
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700238 a = self._get_auth_for_host(host)
239 if a:
Eric Boren2fb63102018-10-05 13:05:03 +0000240 if a[0]:
Edward Lemur67fccdf2019-10-22 22:17:10 +0000241 secret = base64.b64encode(('%s:%s' % (a[0], a[2])).encode('utf-8'))
242 return 'Basic %s' % secret.decode('utf-8')
Eric Boren2fb63102018-10-05 13:05:03 +0000243 else:
244 return 'Bearer %s' % a[2]
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000245 return None
246
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100247 def get_auth_email(self, host):
248 """Best effort parsing of email to be used for auth for the given host."""
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700249 a = self._get_auth_for_host(host)
250 if not a:
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100251 return None
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700252 login = a[0]
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100253 # login typically looks like 'git-xxx.example.com'
254 if not login.startswith('git-') or '.' not in login:
255 return None
256 username, domain = login[len('git-'):].split('.', 1)
257 return '%s@%s' % (username, domain)
258
Andrii Shyshkalov18975322017-01-25 16:44:13 +0100259
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000260# Backwards compatibility just in case somebody imports this outside of
261# depot_tools.
262NetrcAuthenticator = CookiesAuthenticator
263
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000264
265class GceAuthenticator(Authenticator):
266 """Authenticator implementation that uses GCE metadata service for token.
267 """
268
269 _INFO_URL = 'http://metadata.google.internal'
smut5e9401b2017-08-10 15:22:20 -0700270 _ACQUIRE_URL = ('%s/computeMetadata/v1/instance/'
271 'service-accounts/default/token' % _INFO_URL)
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000272 _ACQUIRE_HEADERS = {"Metadata-Flavor": "Google"}
273
274 _cache_is_gce = None
275 _token_cache = None
276 _token_expiration = None
277
278 @classmethod
279 def is_gce(cls):
Ravi Mistryfad941b2016-11-15 13:00:47 -0500280 if os.getenv('SKIP_GCE_AUTH_FOR_GIT'):
281 return False
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000282 if cls._cache_is_gce is None:
283 cls._cache_is_gce = cls._test_is_gce()
284 return cls._cache_is_gce
285
286 @classmethod
287 def _test_is_gce(cls):
288 # Based on https://cloud.google.com/compute/docs/metadata#runninggce
289 try:
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100290 resp, _ = cls._get(cls._INFO_URL)
Edward Lemur3b44ac62020-02-25 23:42:24 +0000291 except (socket.error, httplib2.HttpLib2Error):
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000292 # Could not resolve URL.
293 return False
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100294 return resp.get('metadata-flavor') == 'Google'
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000295
296 @staticmethod
297 def _get(url, **kwargs):
298 next_delay_sec = 1
299 for i in xrange(TRY_LIMIT):
Edward Lemur4ba192e2019-10-28 20:19:37 +0000300 p = urllib.parse.urlparse(url)
301 if p.scheme not in ('http', 'https'):
302 raise RuntimeError(
303 "Don't know how to work with protocol '%s'" % protocol)
304 resp, contents = httplib2.Http().request(url, 'GET', **kwargs)
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000305 LOGGER.debug('GET [%s] #%d/%d (%d)', url, i+1, TRY_LIMIT, resp.status)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000306 if resp.status < 500:
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100307 return (resp, contents)
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000308
Aaron Gable92e9f382017-12-07 11:47:41 -0800309 # Retry server error status codes.
310 LOGGER.warn('Encountered server error')
311 if TRY_LIMIT - i > 1:
312 LOGGER.info('Will retry in %d seconds (%d more times)...',
313 next_delay_sec, TRY_LIMIT - i - 1)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000314 time_sleep(next_delay_sec)
Aaron Gable92e9f382017-12-07 11:47:41 -0800315 next_delay_sec *= 2
316
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000317 @classmethod
318 def _get_token_dict(cls):
319 if cls._token_cache:
320 # If it expires within 25 seconds, refresh.
321 if cls._token_expiration < time.time() - 25:
322 return cls._token_cache
323
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100324 resp, contents = cls._get(cls._ACQUIRE_URL, headers=cls._ACQUIRE_HEADERS)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000325 if resp.status != 200:
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000326 return None
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100327 cls._token_cache = json.loads(contents)
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000328 cls._token_expiration = cls._token_cache['expires_in'] + time.time()
329 return cls._token_cache
330
331 def get_auth_header(self, _host):
332 token_dict = self._get_token_dict()
333 if not token_dict:
334 return None
335 return '%(token_type)s %(access_token)s' % token_dict
336
337
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700338class LuciContextAuthenticator(Authenticator):
339 """Authenticator implementation that uses LUCI_CONTEXT ambient local auth.
340 """
341
342 @staticmethod
343 def is_luci():
344 return auth.has_luci_context_local_auth()
345
346 def __init__(self):
Edward Lemur5b929a42019-10-21 17:57:39 +0000347 self._authenticator = auth.Authenticator(
348 ' '.join([auth.OAUTH_SCOPE_EMAIL, auth.OAUTH_SCOPE_GERRIT]))
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700349
350 def get_auth_header(self, _host):
Edward Lemur5b929a42019-10-21 17:57:39 +0000351 return 'Bearer %s' % self._authenticator.get_access_token().token
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700352
353
szager@chromium.orgb4696232013-10-16 19:45:35 +0000354def CreateHttpConn(host, path, reqtype='GET', headers=None, body=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000355 """Opens an HTTPS connection to a Gerrit service, and sends a request."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000356 headers = headers or {}
357 bare_host = host.partition(':')[0]
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000358
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700359 a = Authenticator.get().get_auth_header(bare_host)
360 if a:
361 headers.setdefault('Authorization', a)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000362 else:
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000363 LOGGER.debug('No authorization found for %s.' % bare_host)
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000364
Dan Jacques6d5bcc22016-11-14 15:32:04 -0800365 url = path
366 if not url.startswith('/'):
367 url = '/' + url
368 if 'Authorization' in headers and not url.startswith('/a/'):
369 url = '/a%s' % url
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000370
szager@chromium.orgb4696232013-10-16 19:45:35 +0000371 if body:
Edward Lemur4ba192e2019-10-28 20:19:37 +0000372 body = json.dumps(body, sort_keys=True)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000373 headers.setdefault('Content-Type', 'application/json')
374 if LOGGER.isEnabledFor(logging.DEBUG):
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000375 LOGGER.debug('%s %s://%s%s' % (reqtype, GERRIT_PROTOCOL, host, url))
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000376 for key, val in headers.items():
szager@chromium.orgb4696232013-10-16 19:45:35 +0000377 if key == 'Authorization':
378 val = 'HIDDEN'
379 LOGGER.debug('%s: %s' % (key, val))
380 if body:
381 LOGGER.debug(body)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000382 conn = httplib2.Http()
383 # HACK: httplib2.Http has no such attribute; we store req_host here for later
Andrii Shyshkalov86c823e2018-09-18 19:51:33 +0000384 # use in ReadHttpResponse.
szager@chromium.orgb4696232013-10-16 19:45:35 +0000385 conn.req_host = host
386 conn.req_params = {
Edward Lemur4ba192e2019-10-28 20:19:37 +0000387 'uri': urllib.parse.urljoin('%s://%s' % (GERRIT_PROTOCOL, host), url),
szager@chromium.orgb4696232013-10-16 19:45:35 +0000388 'method': reqtype,
389 'headers': headers,
390 'body': body,
391 }
szager@chromium.orgb4696232013-10-16 19:45:35 +0000392 return conn
393
394
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700395def ReadHttpResponse(conn, accept_statuses=frozenset([200])):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000396 """Reads an HTTP response from a connection into a string buffer.
szager@chromium.orgb4696232013-10-16 19:45:35 +0000397
398 Args:
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100399 conn: An Http object created by CreateHttpConn above.
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700400 accept_statuses: Treat any of these statuses as success. Default: [200]
401 Common additions include 204, 400, and 404.
szager@chromium.orgb4696232013-10-16 19:45:35 +0000402 Returns: A string buffer containing the connection's reply.
403 """
Steve Kobes56117722018-09-13 18:18:35 +0000404 sleep_time = 1.5
szager@chromium.orgb4696232013-10-16 19:45:35 +0000405 for idx in range(TRY_LIMIT):
Edward Lemur5a9ff432018-10-30 19:00:22 +0000406 before_response = time.time()
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100407 response, contents = conn.request(**conn.req_params)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000408 contents = contents.decode('utf-8', 'replace')
nodir@chromium.orgce32b6e2014-05-12 20:31:32 +0000409
Edward Lemur5a9ff432018-10-30 19:00:22 +0000410 response_time = time.time() - before_response
411 metrics.collector.add_repeated(
412 'http_requests',
413 metrics_utils.extract_http_metrics(
414 conn.req_params['uri'], conn.req_params['method'], response.status,
415 response_time))
416
Edward Lemur4ba192e2019-10-28 20:19:37 +0000417 # If response.status is an accepted status,
418 # or response.status < 500 then the result is final; break retry loop.
419 # If the response is 404/409 it might be because of replication lag,
420 # so keep trying anyway.
421 if (response.status in accept_statuses
422 or response.status < 500 and response.status not in [404, 409]):
Andrii Shyshkalov5b04a572017-01-23 17:44:41 +0100423 LOGGER.debug('got response %d for %s %s', response.status,
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100424 conn.req_params['method'], conn.req_params['uri'])
Michael Mossb40a4512017-10-10 11:07:17 -0700425 # If 404 was in accept_statuses, then it's expected that the file might
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000426 # not exist, so don't return the gitiles error page because that's not
427 # the "content" that was actually requested.
Michael Mossb40a4512017-10-10 11:07:17 -0700428 if response.status == 404:
429 contents = ''
szager@chromium.orgb4696232013-10-16 19:45:35 +0000430 break
Edward Lemur4ba192e2019-10-28 20:19:37 +0000431
Edward Lemur49c8eaf2018-11-07 22:13:12 +0000432 # A status >=500 is assumed to be a possible transient error; retry.
433 http_version = 'HTTP/%s' % ('1.1' if response.version == 11 else '1.0')
434 LOGGER.warn('A transient error occurred while querying %s:\n'
435 '%s %s %s\n'
436 '%s %d %s',
437 conn.req_host, conn.req_params['method'],
438 conn.req_params['uri'],
439 http_version, http_version, response.status, response.reason)
Andrii Shyshkalovd4c86732018-09-25 04:29:31 +0000440
Edward Lemur4ba192e2019-10-28 20:19:37 +0000441 if idx < TRY_LIMIT - 1:
Aaron Gable92e9f382017-12-07 11:47:41 -0800442 LOGGER.info('Will retry in %d seconds (%d more times)...',
443 sleep_time, TRY_LIMIT - idx - 1)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000444 time_sleep(sleep_time)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000445 sleep_time = sleep_time * 2
Edward Lemur83bd7f42018-10-10 00:14:21 +0000446 # end of retries loop
Edward Lemur4ba192e2019-10-28 20:19:37 +0000447
448 if response.status in accept_statuses:
449 return StringIO(contents)
450
451 if response.status in (302, 401, 403):
452 www_authenticate = response.get('www-authenticate')
453 if not www_authenticate:
454 print('Your Gerrit credentials might be misconfigured.')
455 else:
456 auth_match = re.search('realm="([^"]+)"', www_authenticate, re.I)
457 host = auth_match.group(1) if auth_match else conn.req_host
458 print('Authentication failed. Please make sure your .gitcookies '
459 'file has credentials for %s.' % host)
460 print('Try:\n git cl creds-check')
461
462 reason = '%s: %s' % (response.reason, contents)
463 raise GerritError(response.status, reason)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000464
465
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700466def ReadHttpJsonResponse(conn, accept_statuses=frozenset([200])):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000467 """Parses an https response as json."""
Aaron Gable19ee16c2017-04-18 11:56:35 -0700468 fh = ReadHttpResponse(conn, accept_statuses)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000469 # The first line of the response should always be: )]}'
470 s = fh.readline()
471 if s and s.rstrip() != ")]}'":
472 raise GerritError(200, 'Unexpected json output: %s' % s)
473 s = fh.read()
474 if not s:
475 return None
476 return json.loads(s)
477
478
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200479def QueryChanges(host, params, first_param=None, limit=None, o_params=None,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100480 start=None):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000481 """
482 Queries a gerrit-on-borg server for changes matching query terms.
483
484 Args:
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200485 params: A list of key:value pairs for search parameters, as documented
486 here (e.g. ('is', 'owner') for a parameter 'is:owner'):
487 https://gerrit-review.googlesource.com/Documentation/user-search.html#search-operators
szager@chromium.orgb4696232013-10-16 19:45:35 +0000488 first_param: A change identifier
489 limit: Maximum number of results to return.
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100490 start: how many changes to skip (starting with the most recent)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000491 o_params: A list of additional output specifiers, as documented here:
492 https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000493
szager@chromium.orgb4696232013-10-16 19:45:35 +0000494 Returns:
495 A list of json-decoded query results.
496 """
497 # Note that no attempt is made to escape special characters; YMMV.
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200498 if not params and not first_param:
szager@chromium.orgb4696232013-10-16 19:45:35 +0000499 raise RuntimeError('QueryChanges requires search parameters')
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200500 path = 'changes/?q=%s' % _QueryString(params, first_param)
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100501 if start:
502 path = '%s&start=%s' % (path, start)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000503 if limit:
504 path = '%s&n=%d' % (path, limit)
505 if o_params:
506 path = '%s&%s' % (path, '&'.join(['o=%s' % p for p in o_params]))
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700507 return ReadHttpJsonResponse(CreateHttpConn(host, path))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000508
509
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200510def GenerateAllChanges(host, params, first_param=None, limit=500,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100511 o_params=None, start=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000512 """Queries a gerrit-on-borg server for all the changes matching the query
513 terms.
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000514
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100515 WARNING: this is unreliable if a change matching the query is modified while
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000516 this function is being called.
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100517
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000518 A single query to gerrit-on-borg is limited on the number of results by the
519 limit parameter on the request (see QueryChanges) and the server maximum
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100520 limit.
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000521
522 Args:
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200523 params, first_param: Refer to QueryChanges().
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000524 limit: Maximum number of requested changes per query.
525 o_params: Refer to QueryChanges().
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100526 start: Refer to QueryChanges().
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000527
528 Returns:
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100529 A generator object to the list of returned changes.
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000530 """
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100531 already_returned = set()
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000532
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100533 def at_most_once(cls):
534 for cl in cls:
535 if cl['_number'] not in already_returned:
536 already_returned.add(cl['_number'])
537 yield cl
538
539 start = start or 0
540 cur_start = start
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000541 more_changes = True
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100542
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000543 while more_changes:
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100544 # This will fetch changes[start..start+limit] sorted by most recently
545 # updated. Since the rank of any change in this list can be changed any time
546 # (say user posting comment), subsequent calls may overalp like this:
547 # > initial order ABCDEFGH
548 # query[0..3] => ABC
549 # > E get's updated. New order: EABCDFGH
550 # query[3..6] => CDF # C is a dup
551 # query[6..9] => GH # E is missed.
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200552 page = QueryChanges(host, params, first_param, limit, o_params,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100553 cur_start)
554 for cl in at_most_once(page):
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000555 yield cl
556
557 more_changes = [cl for cl in page if '_more_changes' in cl]
558 if len(more_changes) > 1:
559 raise GerritError(
560 200,
561 'Received %d changes with a _more_changes attribute set but should '
562 'receive at most one.' % len(more_changes))
563 if more_changes:
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100564 cur_start += len(page)
565
566 # If we paged through, query again the first page which in most circumstances
567 # will fetch all changes that were modified while this function was run.
568 if start != cur_start:
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200569 page = QueryChanges(host, params, first_param, limit, o_params, start)
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100570 for cl in at_most_once(page):
571 yield cl
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000572
573
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200574def MultiQueryChanges(host, params, change_list, limit=None, o_params=None,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100575 start=None):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000576 """Initiate a query composed of multiple sets of query parameters."""
577 if not change_list:
578 raise RuntimeError(
579 "MultiQueryChanges requires a list of change numbers/id's")
Edward Lemur4ba192e2019-10-28 20:19:37 +0000580 q = ['q=%s' % '+OR+'.join([urllib.parse.quote(str(x)) for x in change_list])]
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200581 if params:
582 q.append(_QueryString(params))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000583 if limit:
584 q.append('n=%d' % limit)
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100585 if start:
586 q.append('S=%s' % start)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000587 if o_params:
588 q.extend(['o=%s' % p for p in o_params])
589 path = 'changes/?%s' % '&'.join(q)
590 try:
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700591 result = ReadHttpJsonResponse(CreateHttpConn(host, path))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000592 except GerritError as e:
593 msg = '%s:\n%s' % (e.message, path)
594 raise GerritError(e.http_status, msg)
595 return result
596
597
598def GetGerritFetchUrl(host):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000599 """Given a Gerrit host name returns URL of a Gerrit instance to fetch from."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000600 return '%s://%s/' % (GERRIT_PROTOCOL, host)
601
602
Edward Lemur687ca902018-12-05 02:30:30 +0000603def GetCodeReviewTbrScore(host, project):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000604 """Given a Gerrit host name and project, return the Code-Review score for TBR.
Edward Lemur687ca902018-12-05 02:30:30 +0000605 """
Edward Lemur4ba192e2019-10-28 20:19:37 +0000606 conn = CreateHttpConn(
607 host, '/projects/%s' % urllib.parse.quote(project, ''))
Edward Lemur687ca902018-12-05 02:30:30 +0000608 project = ReadHttpJsonResponse(conn)
609 if ('labels' not in project
610 or 'Code-Review' not in project['labels']
611 or 'values' not in project['labels']['Code-Review']):
612 return 1
613 return max([int(x) for x in project['labels']['Code-Review']['values']])
614
615
szager@chromium.orgb4696232013-10-16 19:45:35 +0000616def GetChangePageUrl(host, change_number):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000617 """Given a Gerrit host name and change number, returns change page URL."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000618 return '%s://%s/#/c/%d/' % (GERRIT_PROTOCOL, host, change_number)
619
620
621def GetChangeUrl(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000622 """Given a Gerrit host name and change ID, returns a URL for the change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000623 return '%s://%s/a/changes/%s' % (GERRIT_PROTOCOL, host, change)
624
625
626def GetChange(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000627 """Queries a Gerrit server for information about a single change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000628 path = 'changes/%s' % change
629 return ReadHttpJsonResponse(CreateHttpConn(host, path))
630
631
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700632def GetChangeDetail(host, change, o_params=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000633 """Queries a Gerrit server for extended information about a single change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000634 path = 'changes/%s/detail' % change
635 if o_params:
636 path += '?%s' % '&'.join(['o=%s' % p for p in o_params])
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700637 return ReadHttpJsonResponse(CreateHttpConn(host, path))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000638
639
agable32978d92016-11-01 12:55:02 -0700640def GetChangeCommit(host, change, revision='current'):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000641 """Query a Gerrit server for a revision associated with a change."""
agable32978d92016-11-01 12:55:02 -0700642 path = 'changes/%s/revisions/%s/commit?links' % (change, revision)
643 return ReadHttpJsonResponse(CreateHttpConn(host, path))
644
645
szager@chromium.orgb4696232013-10-16 19:45:35 +0000646def GetChangeCurrentRevision(host, change):
647 """Get information about the latest revision for a given change."""
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200648 return QueryChanges(host, [], change, o_params=('CURRENT_REVISION',))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000649
650
651def GetChangeRevisions(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000652 """Gets information about all revisions associated with a change."""
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200653 return QueryChanges(host, [], change, o_params=('ALL_REVISIONS',))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000654
655
656def GetChangeReview(host, change, revision=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000657 """Gets the current review information for a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000658 if not revision:
659 jmsg = GetChangeRevisions(host, change)
660 if not jmsg:
661 return None
662 elif len(jmsg) > 1:
663 raise GerritError(200, 'Multiple changes found for ChangeId %s.' % change)
664 revision = jmsg[0]['current_revision']
665 path = 'changes/%s/revisions/%s/review'
666 return ReadHttpJsonResponse(CreateHttpConn(host, path))
667
668
Aaron Gable0ffdf2d2017-06-05 13:01:17 -0700669def GetChangeComments(host, change):
670 """Get the line- and file-level comments on a change."""
671 path = 'changes/%s/comments' % change
672 return ReadHttpJsonResponse(CreateHttpConn(host, path))
673
674
Quinten Yearsley0e617c02019-02-20 00:37:03 +0000675def GetChangeRobotComments(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000676 """Gets the line- and file-level robot comments on a change."""
Quinten Yearsley0e617c02019-02-20 00:37:03 +0000677 path = 'changes/%s/robotcomments' % change
678 return ReadHttpJsonResponse(CreateHttpConn(host, path))
679
680
szager@chromium.orgb4696232013-10-16 19:45:35 +0000681def AbandonChange(host, change, msg=''):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000682 """Abandons a Gerrit change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000683 path = 'changes/%s/abandon' % change
tandrii@chromium.orgc7da66a2016-03-24 09:52:24 +0000684 body = {'message': msg} if msg else {}
szager@chromium.orgb4696232013-10-16 19:45:35 +0000685 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700686 return ReadHttpJsonResponse(conn)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000687
688
689def RestoreChange(host, change, msg=''):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000690 """Restores a previously abandoned change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000691 path = 'changes/%s/restore' % change
tandrii@chromium.orgc7da66a2016-03-24 09:52:24 +0000692 body = {'message': msg} if msg else {}
szager@chromium.orgb4696232013-10-16 19:45:35 +0000693 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700694 return ReadHttpJsonResponse(conn)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000695
696
697def SubmitChange(host, change, wait_for_merge=True):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000698 """Submits a Gerrit change via Gerrit."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000699 path = 'changes/%s/submit' % change
700 body = {'wait_for_merge': wait_for_merge}
701 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700702 return ReadHttpJsonResponse(conn)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000703
704
dsansomee2d6fd92016-09-08 00:10:47 -0700705def HasPendingChangeEdit(host, change):
706 conn = CreateHttpConn(host, 'changes/%s/edit' % change)
707 try:
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700708 ReadHttpResponse(conn)
dsansomee2d6fd92016-09-08 00:10:47 -0700709 except GerritError as e:
Aaron Gable19ee16c2017-04-18 11:56:35 -0700710 # 204 No Content means no pending change.
711 if e.http_status == 204:
712 return False
713 raise
714 return True
dsansomee2d6fd92016-09-08 00:10:47 -0700715
716
717def DeletePendingChangeEdit(host, change):
718 conn = CreateHttpConn(host, 'changes/%s/edit' % change, reqtype='DELETE')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000719 # On success, Gerrit returns status 204; if the edit was already deleted it
Aaron Gable19ee16c2017-04-18 11:56:35 -0700720 # returns 404. Anything else is an error.
721 ReadHttpResponse(conn, accept_statuses=[204, 404])
dsansomee2d6fd92016-09-08 00:10:47 -0700722
723
Andrii Shyshkalovea4fc832016-12-01 14:53:23 +0100724def SetCommitMessage(host, change, description, notify='ALL'):
scottmg@chromium.org6d1266e2016-04-26 11:12:26 +0000725 """Updates a commit message."""
Aaron Gable7625d882017-06-26 09:47:26 -0700726 assert notify in ('ALL', 'NONE')
727 path = 'changes/%s/message' % change
Aaron Gable5a4ef452017-08-24 13:19:56 -0700728 body = {'message': description, 'notify': notify}
Aaron Gable7625d882017-06-26 09:47:26 -0700729 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
scottmg@chromium.org6d1266e2016-04-26 11:12:26 +0000730 try:
Aaron Gable7625d882017-06-26 09:47:26 -0700731 ReadHttpResponse(conn, accept_statuses=[200, 204])
732 except GerritError as e:
733 raise GerritError(
734 e.http_status,
735 'Received unexpected http status while editing message '
736 'in change %s' % change)
scottmg@chromium.org6d1266e2016-04-26 11:12:26 +0000737
738
szager@chromium.orgb4696232013-10-16 19:45:35 +0000739def GetReviewers(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000740 """Gets information about all reviewers attached to a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000741 path = 'changes/%s/reviewers' % change
742 return ReadHttpJsonResponse(CreateHttpConn(host, path))
743
744
745def GetReview(host, change, revision):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000746 """Gets review information about a specific revision of a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000747 path = 'changes/%s/revisions/%s/review' % (change, revision)
748 return ReadHttpJsonResponse(CreateHttpConn(host, path))
749
750
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700751def AddReviewers(host, change, reviewers=None, ccs=None, notify=True,
752 accept_statuses=frozenset([200, 400, 422])):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000753 """Add reviewers to a change."""
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700754 if not reviewers and not ccs:
Aaron Gabledf86e302016-11-08 10:48:03 -0800755 return None
Wiktor Garbacz6d0d0442017-05-15 12:34:40 +0200756 if not change:
757 return None
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700758 reviewers = frozenset(reviewers or [])
759 ccs = frozenset(ccs or [])
760 path = 'changes/%s/revisions/current/review' % change
761
762 body = {
Jonathan Nieder1ea21322017-11-10 11:45:42 -0800763 'drafts': 'KEEP',
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700764 'reviewers': [],
765 'notify': 'ALL' if notify else 'NONE',
766 }
767 for r in sorted(reviewers | ccs):
768 state = 'REVIEWER' if r in reviewers else 'CC'
769 body['reviewers'].append({
770 'reviewer': r,
771 'state': state,
772 'notify': 'NONE', # We handled `notify` argument above.
Raul Tambre80ee78e2019-05-06 22:41:05 +0000773 })
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700774
775 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
776 # Gerrit will return 400 if one or more of the requested reviewers are
777 # unprocessable. We read the response object to see which were rejected,
778 # warn about them, and retry with the remainder.
779 resp = ReadHttpJsonResponse(conn, accept_statuses=accept_statuses)
780
781 errored = set()
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000782 for result in resp.get('reviewers', {}).values():
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700783 r = result.get('input')
784 state = 'REVIEWER' if r in reviewers else 'CC'
785 if result.get('error'):
786 errored.add(r)
787 LOGGER.warn('Note: "%s" not added as a %s' % (r, state.lower()))
788 if errored:
789 # Try again, adding only those that didn't fail, and only accepting 200.
790 AddReviewers(host, change, reviewers=(reviewers-errored),
791 ccs=(ccs-errored), notify=notify, accept_statuses=[200])
szager@chromium.orgb4696232013-10-16 19:45:35 +0000792
793
Aaron Gable636b13f2017-07-14 10:42:48 -0700794def SetReview(host, change, msg=None, labels=None, notify=None, ready=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000795 """Sets labels and/or adds a message to a code review."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000796 if not msg and not labels:
797 return
798 path = 'changes/%s/revisions/current/review' % change
Jonathan Nieder1ea21322017-11-10 11:45:42 -0800799 body = {'drafts': 'KEEP'}
szager@chromium.orgb4696232013-10-16 19:45:35 +0000800 if msg:
801 body['message'] = msg
802 if labels:
803 body['labels'] = labels
Aaron Gablefc62f762017-07-17 11:12:07 -0700804 if notify is not None:
Aaron Gable75e78722017-06-09 10:40:16 -0700805 body['notify'] = 'ALL' if notify else 'NONE'
Aaron Gable636b13f2017-07-14 10:42:48 -0700806 if ready:
807 body['ready'] = True
szager@chromium.orgb4696232013-10-16 19:45:35 +0000808 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
809 response = ReadHttpJsonResponse(conn)
810 if labels:
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000811 for key, val in labels.items():
szager@chromium.orgb4696232013-10-16 19:45:35 +0000812 if ('labels' not in response or key not in response['labels'] or
813 int(response['labels'][key] != int(val))):
814 raise GerritError(200, 'Unable to set "%s" label on change %s.' % (
815 key, change))
816
817
818def ResetReviewLabels(host, change, label, value='0', message=None,
819 notify=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000820 """Resets the value of a given label for all reviewers on a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000821 # This is tricky, because we want to work on the "current revision", but
822 # there's always the risk that "current revision" will change in between
823 # API calls. So, we check "current revision" at the beginning and end; if
824 # it has changed, raise an exception.
825 jmsg = GetChangeCurrentRevision(host, change)
826 if not jmsg:
827 raise GerritError(
828 200, 'Could not get review information for change "%s"' % change)
829 value = str(value)
830 revision = jmsg[0]['current_revision']
831 path = 'changes/%s/revisions/%s/review' % (change, revision)
832 message = message or (
833 '%s label set to %s programmatically.' % (label, value))
834 jmsg = GetReview(host, change, revision)
835 if not jmsg:
836 raise GerritError(200, 'Could not get review information for revison %s '
837 'of change %s' % (revision, change))
838 for review in jmsg.get('labels', {}).get(label, {}).get('all', []):
839 if str(review.get('value', value)) != value:
840 body = {
Jonathan Nieder1ea21322017-11-10 11:45:42 -0800841 'drafts': 'KEEP',
szager@chromium.orgb4696232013-10-16 19:45:35 +0000842 'message': message,
843 'labels': {label: value},
844 'on_behalf_of': review['_account_id'],
845 }
846 if notify:
847 body['notify'] = notify
848 conn = CreateHttpConn(
849 host, path, reqtype='POST', body=body)
850 response = ReadHttpJsonResponse(conn)
851 if str(response['labels'][label]) != value:
852 username = review.get('email', jmsg.get('name', ''))
853 raise GerritError(200, 'Unable to set %s label for user "%s"'
854 ' on change %s.' % (label, username, change))
855 jmsg = GetChangeCurrentRevision(host, change)
856 if not jmsg:
857 raise GerritError(
858 200, 'Could not get review information for change "%s"' % change)
859 elif jmsg[0]['current_revision'] != revision:
860 raise GerritError(200, 'While resetting labels on change "%s", '
861 'a new patchset was uploaded.' % change)
Dan Jacques8d11e482016-11-15 14:25:56 -0800862
863
dimu833c94c2017-01-18 17:36:15 -0800864def CreateGerritBranch(host, project, branch, commit):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000865 """Creates a new branch from given project and commit
866
dimu833c94c2017-01-18 17:36:15 -0800867 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-branch
868
869 Returns:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000870 A JSON object with 'ref' key.
dimu833c94c2017-01-18 17:36:15 -0800871 """
872 path = 'projects/%s/branches/%s' % (project, branch)
873 body = {'revision': commit}
874 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
dimu7d1af2b2017-04-19 16:01:17 -0700875 response = ReadHttpJsonResponse(conn, accept_statuses=[201])
dimu833c94c2017-01-18 17:36:15 -0800876 if response:
877 return response
878 raise GerritError(200, 'Unable to create gerrit branch')
879
880
881def GetGerritBranch(host, project, branch):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000882 """Gets a branch from given project and commit.
883
884 See:
dimu833c94c2017-01-18 17:36:15 -0800885 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-branch
886
887 Returns:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000888 A JSON object with 'revision' key.
dimu833c94c2017-01-18 17:36:15 -0800889 """
890 path = 'projects/%s/branches/%s' % (project, branch)
891 conn = CreateHttpConn(host, path, reqtype='GET')
892 response = ReadHttpJsonResponse(conn)
893 if response:
894 return response
895 raise GerritError(200, 'Unable to get gerrit branch')
896
897
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100898def GetAccountDetails(host, account_id='self'):
899 """Returns details of the account.
900
901 If account_id is not given, uses magic value 'self' which corresponds to
902 whichever account user is authenticating as.
903
904 Documentation:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000905 https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-account
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000906
907 Returns None if account is not found (i.e., Gerrit returned 404).
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100908 """
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100909 conn = CreateHttpConn(host, '/accounts/%s' % account_id)
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000910 return ReadHttpJsonResponse(conn, accept_statuses=[200, 404])
911
912
913def ValidAccounts(host, accounts, max_threads=10):
914 """Returns a mapping from valid account to its details.
915
916 Invalid accounts, either not existing or without unique match,
917 are not present as returned dictionary keys.
918 """
Edward Lemur0db01f02019-11-12 22:01:51 +0000919 assert not isinstance(accounts, str), type(accounts)
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000920 accounts = list(set(accounts))
921 if not accounts:
922 return {}
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000923
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000924 def get_one(account):
925 try:
926 return account, GetAccountDetails(host, account)
927 except GerritError:
928 return None, None
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000929
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +0000930 valid = {}
931 with contextlib.closing(ThreadPool(min(max_threads, len(accounts)))) as pool:
932 for account, details in pool.map(get_one, accounts):
933 if account and details:
934 valid[account] = details
935 return valid
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100936
937
Nick Carter8692b182017-11-06 16:30:38 -0800938def PercentEncodeForGitRef(original):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000939 """Applies percent-encoding for strings sent to Gerrit via git ref metadata.
Nick Carter8692b182017-11-06 16:30:38 -0800940
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000941 The encoding used is based on but stricter than URL encoding (Section 2.1 of
942 RFC 3986). The only non-escaped characters are alphanumerics, and 'SPACE'
943 (U+0020) can be represented as 'LOW LINE' (U+005F) or 'PLUS SIGN' (U+002B).
Nick Carter8692b182017-11-06 16:30:38 -0800944
945 For more information, see the Gerrit docs here:
946
947 https://gerrit-review.googlesource.com/Documentation/user-upload.html#message
948 """
949 safe = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '
950 encoded = ''.join(c if c in safe else '%%%02X' % ord(c) for c in original)
951
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000952 # Spaces are not allowed in git refs; gerrit will interpret either '_' or
Nick Carter8692b182017-11-06 16:30:38 -0800953 # '+' (or '%20') as space. Use '_' since that has been supported the longest.
954 return encoded.replace(' ', '_')
955
956
Dan Jacques8d11e482016-11-15 14:25:56 -0800957@contextlib.contextmanager
958def tempdir():
959 tdir = None
960 try:
961 tdir = tempfile.mkdtemp(suffix='gerrit_util')
962 yield tdir
963 finally:
964 if tdir:
965 gclient_utils.rmtree(tdir)
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +0000966
967
968def ChangeIdentifier(project, change_number):
Edward Lemur687ca902018-12-05 02:30:30 +0000969 """Returns change identifier "project~number" suitable for |change| arg of
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +0000970 this module API.
971
972 Such format is allows for more efficient Gerrit routing of HTTP requests,
973 comparing to specifying just change_number.
974 """
975 assert int(change_number)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000976 return '%s~%s' % (urllib.parse.quote(project, ''), change_number)