gerrit_util.py 38 KB

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