gerrit_util.py 35 KB

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