gerrit_util.py 30.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""
Utilities for requesting information for a gerrit server via https.

https://gerrit-review.googlesource.com/Documentation/rest-api.html
"""

import base64
12
import contextlib
13
import cookielib
14
import httplib  # Still used for its constants.
15 16 17 18
import json
import logging
import netrc
import os
19
import re
20
import socket
21 22
import stat
import sys
23
import tempfile
24 25
import time
import urllib
26
import urlparse
27 28
from cStringIO import StringIO

29
import auth
30
import gclient_utils
31
import subprocess2
32
from third_party import httplib2
33

34
LOGGER = logging.getLogger()
35 36 37
# With a starting sleep time of 1 second, 2^n exponential backoff, and six
# total tries, the sleep time between the first and last tries will be 31s.
TRY_LIMIT = 6
38

39

40 41 42 43 44 45 46 47 48 49 50 51 52
# Controls the transport protocol used to communicate with gerrit.
# This is parameterized primarily to enable GerritTestCase.
GERRIT_PROTOCOL = 'https'


class GerritError(Exception):
  """Exception class for errors commuicating with the gerrit-on-borg service."""
  def __init__(self, http_status, *args, **kwargs):
    super(GerritError, self).__init__(*args, **kwargs)
    self.http_status = http_status
    self.message = '(%d) %s' % (self.http_status, self.message)


53 54 55 56
class GerritAuthenticationError(GerritError):
  """Exception class for authentication errors during Gerrit communication."""


57
def _QueryString(params, first_param=None):
58 59 60 61 62
  """Encodes query parameters in the key:val[+key:val...] format specified here:

  https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
  """
  q = [urllib.quote(first_param)] if first_param else []
63
  q.extend(['%s:%s' % (key, val) for key, val in params])
64 65 66
  return '+'.join(q)


67
def GetConnectionObject(protocol=None):
68 69
  if protocol is None:
    protocol = GERRIT_PROTOCOL
70
  if protocol in ('http', 'https'):
71
    return httplib2.Http()
72 73 74 75 76
  else:
    raise RuntimeError(
        "Don't know how to work with protocol '%s'" % protocol)


77 78 79 80 81 82 83 84 85 86 87 88 89
class Authenticator(object):
  """Base authenticator class for authenticator implementations to subclass."""

  def get_auth_header(self, host):
    raise NotImplementedError()

  @staticmethod
  def get():
    """Returns: (Authenticator) The identified Authenticator to use.

    Probes the local system and its environment and identifies the
    Authenticator instance to use.
    """
90 91 92 93
    # LUCI Context takes priority since it's normally present only on bots,
    # which then must use it.
    if LuciContextAuthenticator.is_luci():
      return LuciContextAuthenticator()
94 95
    if GceAuthenticator.is_gce():
      return GceAuthenticator()
96
    return CookiesAuthenticator()
97 98


99 100 101 102
class CookiesAuthenticator(Authenticator):
  """Authenticator implementation that uses ".netrc" or ".gitcookies" for token.

  Expected case for developer workstations.
103 104 105 106
  """

  def __init__(self):
    self.netrc = self._get_netrc()
107
    self.gitcookies = self._get_gitcookies()
108

109 110 111 112 113 114 115 116 117
  @classmethod
  def get_new_password_url(cls, host):
    assert not host.startswith('http')
    # Assume *.googlesource.com pattern.
    parts = host.split('.')
    if not parts[0].endswith('-review'):
      parts[0] += '-review'
    return 'https://%s/new-password' % ('.'.join(parts))

118 119 120 121 122 123 124 125
  @classmethod
  def get_new_password_message(cls, host):
    assert not host.startswith('http')
    # Assume *.googlesource.com pattern.
    parts = host.split('.')
    if not parts[0].endswith('-review'):
      parts[0] += '-review'
    url = 'https://%s/new-password' % ('.'.join(parts))
126
    return 'You can (re)generate your credentials by visiting %s' % url
127 128 129

  @classmethod
  def get_netrc_path(cls):
130
    path = '_netrc' if sys.platform.startswith('win') else '.netrc'
131 132 133 134
    return os.path.expanduser(os.path.join('~', path))

  @classmethod
  def _get_netrc(cls):
135
    # Buffer the '.netrc' path. Use an empty file if it doesn't exist.
136
    path = cls.get_netrc_path()
137 138 139 140 141 142 143 144 145 146 147
    if not os.path.exists(path):
      return netrc.netrc(os.devnull)

    st = os.stat(path)
    if st.st_mode & (stat.S_IRWXG | stat.S_IRWXO):
      print >> sys.stderr, (
          'WARNING: netrc file %s cannot be used because its file '
          'permissions are insecure.  netrc file permissions should be '
          '600.' % path)
    with open(path) as fd:
      content = fd.read()
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170

    # Load the '.netrc' file. We strip comments from it because processing them
    # can trigger a bug in Windows. See crbug.com/664664.
    content = '\n'.join(l for l in content.splitlines()
                        if l.strip() and not l.strip().startswith('#'))
    with tempdir() as tdir:
      netrc_path = os.path.join(tdir, 'netrc')
      with open(netrc_path, 'w') as fd:
        fd.write(content)
      os.chmod(netrc_path, (stat.S_IRUSR | stat.S_IWUSR))
      return cls._get_netrc_from_path(netrc_path)

  @classmethod
  def _get_netrc_from_path(cls, path):
    try:
      return netrc.netrc(path)
    except IOError:
      print >> sys.stderr, 'WARNING: Could not read netrc file %s' % path
      return netrc.netrc(os.devnull)
    except netrc.NetrcParseError as e:
      print >> sys.stderr, ('ERROR: Cannot use netrc file %s due to a '
                            'parsing error: %s' % (path, e))
      return netrc.netrc(os.devnull)
171

172 173
  @classmethod
  def get_gitcookies_path(cls):
174 175
    if os.getenv('GIT_COOKIES_PATH'):
      return os.getenv('GIT_COOKIES_PATH')
176 177 178 179 180
    try:
      return subprocess2.check_output(
          ['git', 'config', '--path', 'http.cookiefile']).strip()
    except subprocess2.CalledProcessError:
      return os.path.join(os.environ['HOME'], '.gitcookies')
181 182 183

  @classmethod
  def _get_gitcookies(cls):
184
    gitcookies = {}
185 186 187 188
    path = cls.get_gitcookies_path()
    if not os.path.exists(path):
      return gitcookies

189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    try:
      f = open(path, 'rb')
    except IOError:
      return gitcookies

    with f:
      for line in f:
        try:
          fields = line.strip().split('\t')
          if line.strip().startswith('#') or len(fields) != 7:
            continue
          domain, xpath, key, value = fields[0], fields[2], fields[5], fields[6]
          if xpath == '/' and key == 'o':
            login, secret_token = value.split('=', 1)
            gitcookies[domain] = (login, secret_token)
        except (IndexError, ValueError, TypeError) as exc:
205
          LOGGER.warning(exc)
206 207 208

    return gitcookies

209
  def _get_auth_for_host(self, host):
210 211
    for domain, creds in self.gitcookies.iteritems():
      if cookielib.domain_match(host, domain):
212 213
        return (creds[0], None, creds[1])
    return self.netrc.authenticators(host)
214

215
  def get_auth_header(self, host):
216 217 218
    a = self._get_auth_for_host(host)
    if a:
      return 'Basic %s' % (base64.b64encode('%s:%s' % (a[0], a[2])))
219 220
    return None

221 222
  def get_auth_email(self, host):
    """Best effort parsing of email to be used for auth for the given host."""
223 224
    a = self._get_auth_for_host(host)
    if not a:
225
      return None
226
    login = a[0]
227 228 229 230 231 232
    # login typically looks like 'git-xxx.example.com'
    if not login.startswith('git-') or '.' not in login:
      return None
    username, domain = login[len('git-'):].split('.', 1)
    return '%s@%s' % (username, domain)

233

234 235 236 237
# Backwards compatibility just in case somebody imports this outside of
# depot_tools.
NetrcAuthenticator = CookiesAuthenticator

238 239 240 241 242 243

class GceAuthenticator(Authenticator):
  """Authenticator implementation that uses GCE metadata service for token.
  """

  _INFO_URL = 'http://metadata.google.internal'
244 245
  _ACQUIRE_URL = ('%s/computeMetadata/v1/instance/'
                  'service-accounts/default/token' % _INFO_URL)
246 247 248 249 250 251 252 253
  _ACQUIRE_HEADERS = {"Metadata-Flavor": "Google"}

  _cache_is_gce = None
  _token_cache = None
  _token_expiration = None

  @classmethod
  def is_gce(cls):
254 255
    if os.getenv('SKIP_GCE_AUTH_FOR_GIT'):
      return False
256 257 258 259 260 261 262 263
    if cls._cache_is_gce is None:
      cls._cache_is_gce = cls._test_is_gce()
    return cls._cache_is_gce

  @classmethod
  def _test_is_gce(cls):
    # Based on https://cloud.google.com/compute/docs/metadata#runninggce
    try:
264
      resp, _ = cls._get(cls._INFO_URL)
265 266
    except (socket.error, httplib2.ServerNotFoundError,
            httplib2.socks.HTTPError):
267 268
      # Could not resolve URL.
      return False
269
    return resp.get('metadata-flavor') == 'Google'
270 271 272 273 274 275

  @staticmethod
  def _get(url, **kwargs):
    next_delay_sec = 1
    for i in xrange(TRY_LIMIT):
      p = urlparse.urlparse(url)
276
      c = GetConnectionObject(protocol=p.scheme)
277
      resp, contents = c.request(url, 'GET', **kwargs)
278 279
      LOGGER.debug('GET [%s] #%d/%d (%d)', url, i+1, TRY_LIMIT, resp.status)
      if resp.status < httplib.INTERNAL_SERVER_ERROR:
280
        return (resp, contents)
281

282 283 284 285 286 287 288 289 290
      # Retry server error status codes.
      LOGGER.warn('Encountered server error')
      if TRY_LIMIT - i > 1:
        LOGGER.info('Will retry in %d seconds (%d more times)...',
                    next_delay_sec, TRY_LIMIT - i - 1)
        time.sleep(next_delay_sec)
        next_delay_sec *= 2


291 292 293 294 295 296 297
  @classmethod
  def _get_token_dict(cls):
    if cls._token_cache:
      # If it expires within 25 seconds, refresh.
      if cls._token_expiration < time.time() - 25:
        return cls._token_cache

298
    resp, contents = cls._get(cls._ACQUIRE_URL, headers=cls._ACQUIRE_HEADERS)
299 300
    if resp.status != httplib.OK:
      return None
301
    cls._token_cache = json.loads(contents)
302 303 304 305 306 307 308 309 310 311
    cls._token_expiration = cls._token_cache['expires_in'] + time.time()
    return cls._token_cache

  def get_auth_header(self, _host):
    token_dict = self._get_token_dict()
    if not token_dict:
      return None
    return '%(token_type)s %(access_token)s' % token_dict


312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
class LuciContextAuthenticator(Authenticator):
  """Authenticator implementation that uses LUCI_CONTEXT ambient local auth.
  """

  @staticmethod
  def is_luci():
    return auth.has_luci_context_local_auth()

  def __init__(self):
    self._access_token = None
    self._ensure_fresh()

  def _ensure_fresh(self):
    if not self._access_token or self._access_token.needs_refresh():
      self._access_token = auth.get_luci_context_access_token(
          scopes=' '.join([auth.OAUTH_SCOPE_EMAIL, auth.OAUTH_SCOPE_GERRIT]))

  def get_auth_header(self, _host):
    self._ensure_fresh()
    return 'Bearer %s' % self._access_token.token


334 335 336 337
def CreateHttpConn(host, path, reqtype='GET', headers=None, body=None):
  """Opens an https connection to a gerrit service, and sends a request."""
  headers = headers or {}
  bare_host = host.partition(':')[0]
338

339 340 341
  a = Authenticator.get().get_auth_header(bare_host)
  if a:
    headers.setdefault('Authorization', a)
342
  else:
343
    LOGGER.debug('No authorization found for %s.' % bare_host)
344

345 346 347 348 349
  url = path
  if not url.startswith('/'):
    url = '/' + url
  if 'Authorization' in headers and not url.startswith('/a/'):
    url = '/a%s' % url
350

351 352 353 354
  if body:
    body = json.JSONEncoder().encode(body)
    headers.setdefault('Content-Type', 'application/json')
  if LOGGER.isEnabledFor(logging.DEBUG):
355
    LOGGER.debug('%s %s://%s%s' % (reqtype, GERRIT_PROTOCOL, host, url))
356 357 358 359 360 361
    for key, val in headers.iteritems():
      if key == 'Authorization':
        val = 'HIDDEN'
      LOGGER.debug('%s: %s' % (key, val))
    if body:
      LOGGER.debug(body)
362
  conn = GetConnectionObject()
363 364
  conn.req_host = host
  conn.req_params = {
365
      'uri': urlparse.urljoin('%s://%s' % (GERRIT_PROTOCOL, host), url),
366 367 368 369 370 371 372
      'method': reqtype,
      'headers': headers,
      'body': body,
  }
  return conn


373
def ReadHttpResponse(conn, accept_statuses=frozenset([200])):
374 375 376
  """Reads an http response from a connection into a string buffer.

  Args:
377
    conn: An Http object created by CreateHttpConn above.
378 379
    accept_statuses: Treat any of these statuses as success. Default: [200]
                     Common additions include 204, 400, and 404.
380 381
  Returns: A string buffer containing the connection's reply.
  """
382
  sleep_time = 1
383
  for idx in range(TRY_LIMIT):
384
    response, contents = conn.request(**conn.req_params)
385 386

    # Check if this is an authentication issue.
387
    www_authenticate = response.get('www-authenticate')
388 389 390 391
    if (response.status in (httplib.UNAUTHORIZED, httplib.FOUND) and
        www_authenticate):
      auth_match = re.search('realm="([^"]+)"', www_authenticate, re.I)
      host = auth_match.group(1) if auth_match else conn.req_host
392
      reason = ('Authentication failed. Please make sure your .gitcookies file '
393 394 395
                'has credentials for %s' % host)
      raise GerritAuthenticationError(response.status, reason)

396
    # If response.status < 500 then the result is final; break retry loop.
397
    # If the response is 404/409, it might be because of replication lag, so
398
    # keep trying anyway.
399
    if ((response.status < 500 and response.status not in [404, 409])
400
        or response.status in accept_statuses):
401
      LOGGER.debug('got response %d for %s %s', response.status,
402
                   conn.req_params['method'], conn.req_params['uri'])
403 404 405 406 407
      # If 404 was in accept_statuses, then it's expected that the file might
      # not exist, so don't return the gitiles error page because that's not the
      # "content" that was actually requested.
      if response.status == 404:
        contents = ''
408 409 410
      break
    # A status >=500 is assumed to be a possible transient error; retry.
    http_version = 'HTTP/%s' % ('1.1' if response.version == 11 else '1.0')
411 412 413
    LOGGER.warn('A transient error occurred while querying %s:\n'
                '%s %s %s\n'
                '%s %d %s',
414 415
                conn.req_host, conn.req_params['method'],
                conn.req_params['uri'],
416
                http_version, http_version, response.status, response.reason)
417
    if TRY_LIMIT - idx > 1:
418 419
      LOGGER.info('Will retry in %d seconds (%d more times)...',
                  sleep_time, TRY_LIMIT - idx - 1)
420 421
      time.sleep(sleep_time)
      sleep_time = sleep_time * 2
422
  if response.status not in accept_statuses:
423 424 425
    if response.status in (401, 403):
      print('Your Gerrit credentials might be misconfigured. Try: \n'
            '  git cl creds-check')
426
    reason = '%s: %s' % (response.reason, contents)
427
    raise GerritError(response.status, reason)
428
  return StringIO(contents)
429 430


431
def ReadHttpJsonResponse(conn, accept_statuses=frozenset([200])):
432
  """Parses an https response as json."""
433
  fh = ReadHttpResponse(conn, accept_statuses)
434 435 436 437 438 439 440 441 442 443
  # The first line of the response should always be: )]}'
  s = fh.readline()
  if s and s.rstrip() != ")]}'":
    raise GerritError(200, 'Unexpected json output: %s' % s)
  s = fh.read()
  if not s:
    return None
  return json.loads(s)


444
def QueryChanges(host, params, first_param=None, limit=None, o_params=None,
445
                 start=None):
446 447 448 449
  """
  Queries a gerrit-on-borg server for changes matching query terms.

  Args:
450 451 452
    params: A list of key:value pairs for search parameters, as documented
        here (e.g. ('is', 'owner') for a parameter 'is:owner'):
        https://gerrit-review.googlesource.com/Documentation/user-search.html#search-operators
453 454
    first_param: A change identifier
    limit: Maximum number of results to return.
455
    start: how many changes to skip (starting with the most recent)
456 457 458 459 460 461
    o_params: A list of additional output specifiers, as documented here:
        https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
  Returns:
    A list of json-decoded query results.
  """
  # Note that no attempt is made to escape special characters; YMMV.
462
  if not params and not first_param:
463
    raise RuntimeError('QueryChanges requires search parameters')
464
  path = 'changes/?q=%s' % _QueryString(params, first_param)
465 466
  if start:
    path = '%s&start=%s' % (path, start)
467 468 469 470
  if limit:
    path = '%s&n=%d' % (path, limit)
  if o_params:
    path = '%s&%s' % (path, '&'.join(['o=%s' % p for p in o_params]))
471
  return ReadHttpJsonResponse(CreateHttpConn(host, path))
472 473


474
def GenerateAllChanges(host, params, first_param=None, limit=500,
475
                       o_params=None, start=None):
476 477 478
  """
  Queries a gerrit-on-borg server for all the changes matching the query terms.

479 480 481
  WARNING: this is unreliable if a change matching the query is modified while
    this function is being called.

482 483
  A single query to gerrit-on-borg is limited on the number of results by the
  limit parameter on the request (see QueryChanges) and the server maximum
484
  limit.
485 486

  Args:
487
    params, first_param: Refer to QueryChanges().
488 489
    limit: Maximum number of requested changes per query.
    o_params: Refer to QueryChanges().
490
    start: Refer to QueryChanges().
491 492

  Returns:
493
    A generator object to the list of returned changes.
494
  """
495 496 497 498 499 500 501 502 503
  already_returned = set()
  def at_most_once(cls):
    for cl in cls:
      if cl['_number'] not in already_returned:
        already_returned.add(cl['_number'])
        yield cl

  start = start or 0
  cur_start = start
504
  more_changes = True
505

506
  while more_changes:
507 508 509 510 511 512 513 514
    # This will fetch changes[start..start+limit] sorted by most recently
    # updated. Since the rank of any change in this list can be changed any time
    # (say user posting comment), subsequent calls may overalp like this:
    #   > initial order ABCDEFGH
    #   query[0..3]  => ABC
    #   > E get's updated. New order: EABCDFGH
    #   query[3..6] => CDF   # C is a dup
    #   query[6..9] => GH    # E is missed.
515
    page = QueryChanges(host, params, first_param, limit, o_params,
516 517
                        cur_start)
    for cl in at_most_once(page):
518 519 520 521 522 523 524 525 526
      yield cl

    more_changes = [cl for cl in page if '_more_changes' in cl]
    if len(more_changes) > 1:
      raise GerritError(
          200,
          'Received %d changes with a _more_changes attribute set but should '
          'receive at most one.' % len(more_changes))
    if more_changes:
527 528 529 530 531
      cur_start += len(page)

  # If we paged through, query again the first page which in most circumstances
  # will fetch all changes that were modified while this function was run.
  if start != cur_start:
532
    page = QueryChanges(host, params, first_param, limit, o_params, start)
533 534
    for cl in at_most_once(page):
      yield cl
535 536


537
def MultiQueryChanges(host, params, change_list, limit=None, o_params=None,
538
                      start=None):
539 540 541 542 543
  """Initiate a query composed of multiple sets of query parameters."""
  if not change_list:
    raise RuntimeError(
        "MultiQueryChanges requires a list of change numbers/id's")
  q = ['q=%s' % '+OR+'.join([urllib.quote(str(x)) for x in change_list])]
544 545
  if params:
    q.append(_QueryString(params))
546 547
  if limit:
    q.append('n=%d' % limit)
548 549
  if start:
    q.append('S=%s' % start)
550 551 552 553
  if o_params:
    q.extend(['o=%s' % p for p in o_params])
  path = 'changes/?%s' % '&'.join(q)
  try:
554
    result = ReadHttpJsonResponse(CreateHttpConn(host, path))
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
  except GerritError as e:
    msg = '%s:\n%s' % (e.message, path)
    raise GerritError(e.http_status, msg)
  return result


def GetGerritFetchUrl(host):
  """Given a gerrit host name returns URL of a gerrit instance to fetch from."""
  return '%s://%s/' % (GERRIT_PROTOCOL, host)


def GetChangePageUrl(host, change_number):
  """Given a gerrit host name and change number, return change page url."""
  return '%s://%s/#/c/%d/' % (GERRIT_PROTOCOL, host, change_number)


def GetChangeUrl(host, change):
  """Given a gerrit host name and change id, return an url for the change."""
  return '%s://%s/a/changes/%s' % (GERRIT_PROTOCOL, host, change)


def GetChange(host, change):
  """Query a gerrit server for information about a single change."""
  path = 'changes/%s' % change
  return ReadHttpJsonResponse(CreateHttpConn(host, path))


582
def GetChangeDetail(host, change, o_params=None):
583 584 585 586
  """Query a gerrit server for extended information about a single change."""
  path = 'changes/%s/detail' % change
  if o_params:
    path += '?%s' % '&'.join(['o=%s' % p for p in o_params])
587
  return ReadHttpJsonResponse(CreateHttpConn(host, path))
588 589


590 591 592 593 594 595
def GetChangeCommit(host, change, revision='current'):
  """Query a gerrit server for a revision associated with a change."""
  path = 'changes/%s/revisions/%s/commit?links' % (change, revision)
  return ReadHttpJsonResponse(CreateHttpConn(host, path))


596 597
def GetChangeCurrentRevision(host, change):
  """Get information about the latest revision for a given change."""
598
  return QueryChanges(host, [], change, o_params=('CURRENT_REVISION',))
599 600 601 602


def GetChangeRevisions(host, change):
  """Get information about all revisions associated with a change."""
603
  return QueryChanges(host, [], change, o_params=('ALL_REVISIONS',))
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618


def GetChangeReview(host, change, revision=None):
  """Get the current review information for a change."""
  if not revision:
    jmsg = GetChangeRevisions(host, change)
    if not jmsg:
      return None
    elif len(jmsg) > 1:
      raise GerritError(200, 'Multiple changes found for ChangeId %s.' % change)
    revision = jmsg[0]['current_revision']
  path = 'changes/%s/revisions/%s/review'
  return ReadHttpJsonResponse(CreateHttpConn(host, path))


619 620 621 622 623 624
def GetChangeComments(host, change):
  """Get the line- and file-level comments on a change."""
  path = 'changes/%s/comments' % change
  return ReadHttpJsonResponse(CreateHttpConn(host, path))


625 626 627
def AbandonChange(host, change, msg=''):
  """Abandon a gerrit change."""
  path = 'changes/%s/abandon' % change
628
  body = {'message': msg} if msg else {}
629
  conn = CreateHttpConn(host, path, reqtype='POST', body=body)
630
  return ReadHttpJsonResponse(conn)
631 632 633 634 635


def RestoreChange(host, change, msg=''):
  """Restore a previously abandoned change."""
  path = 'changes/%s/restore' % change
636
  body = {'message': msg} if msg else {}
637
  conn = CreateHttpConn(host, path, reqtype='POST', body=body)
638
  return ReadHttpJsonResponse(conn)
639 640 641 642 643 644 645


def SubmitChange(host, change, wait_for_merge=True):
  """Submits a gerrit change via Gerrit."""
  path = 'changes/%s/submit' % change
  body = {'wait_for_merge': wait_for_merge}
  conn = CreateHttpConn(host, path, reqtype='POST', body=body)
646
  return ReadHttpJsonResponse(conn)
647 648


649 650 651
def HasPendingChangeEdit(host, change):
  conn = CreateHttpConn(host, 'changes/%s/edit' % change)
  try:
652
    ReadHttpResponse(conn)
653
  except GerritError as e:
654 655 656 657 658
    # 204 No Content means no pending change.
    if e.http_status == 204:
      return False
    raise
  return True
659 660 661 662


def DeletePendingChangeEdit(host, change):
  conn = CreateHttpConn(host, 'changes/%s/edit' % change, reqtype='DELETE')
663 664 665
  # On success, gerrit returns status 204; if the edit was already deleted it
  # returns 404.  Anything else is an error.
  ReadHttpResponse(conn, accept_statuses=[204, 404])
666 667


668
def SetCommitMessage(host, change, description, notify='ALL'):
669
  """Updates a commit message."""
670 671
  assert notify in ('ALL', 'NONE')
  path = 'changes/%s/message' % change
672
  body = {'message': description, 'notify': notify}
673
  conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
674
  try:
675 676 677 678 679 680
    ReadHttpResponse(conn, accept_statuses=[200, 204])
  except GerritError as e:
    raise GerritError(
        e.http_status,
        'Received unexpected http status while editing message '
        'in change %s' % change)
681 682


683 684 685 686 687 688 689 690 691 692 693 694
def GetReviewers(host, change):
  """Get information about all reviewers attached to a change."""
  path = 'changes/%s/reviewers' % change
  return ReadHttpJsonResponse(CreateHttpConn(host, path))


def GetReview(host, change, revision):
  """Get review information about a specific revision of a change."""
  path = 'changes/%s/revisions/%s/review' % (change, revision)
  return ReadHttpJsonResponse(CreateHttpConn(host, path))


695 696
def AddReviewers(host, change, reviewers=None, ccs=None, notify=True,
                 accept_statuses=frozenset([200, 400, 422])):
697
  """Add reviewers to a change."""
698
  if not reviewers and not ccs:
699
    return None
700 701
  if not change:
    return None
702 703 704 705 706
  reviewers = frozenset(reviewers or [])
  ccs = frozenset(ccs or [])
  path = 'changes/%s/revisions/current/review' % change

  body = {
707
    'drafts': 'KEEP',
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
    'reviewers': [],
    'notify': 'ALL' if notify else 'NONE',
  }
  for r in sorted(reviewers | ccs):
    state = 'REVIEWER' if r in reviewers else 'CC'
    body['reviewers'].append({
     'reviewer': r,
     'state': state,
     'notify': 'NONE',  # We handled `notify` argument above.
   })

  conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  # Gerrit will return 400 if one or more of the requested reviewers are
  # unprocessable. We read the response object to see which were rejected,
  # warn about them, and retry with the remainder.
  resp = ReadHttpJsonResponse(conn, accept_statuses=accept_statuses)

  errored = set()
  for result in resp.get('reviewers', {}).itervalues():
    r = result.get('input')
    state = 'REVIEWER' if r in reviewers else 'CC'
    if result.get('error'):
      errored.add(r)
      LOGGER.warn('Note: "%s" not added as a %s' % (r, state.lower()))
  if errored:
    # Try again, adding only those that didn't fail, and only accepting 200.
    AddReviewers(host, change, reviewers=(reviewers-errored),
                 ccs=(ccs-errored), notify=notify, accept_statuses=[200])
736 737 738 739 740 741 742 743 744 745 746 747


def RemoveReviewers(host, change, remove=None):
  """Remove reveiewers from a change."""
  if not remove:
    return
  if isinstance(remove, basestring):
    remove = (remove,)
  for r in remove:
    path = 'changes/%s/reviewers/%s' % (change, r)
    conn = CreateHttpConn(host, path, reqtype='DELETE')
    try:
748
      ReadHttpResponse(conn, accept_statuses=[204])
749 750
    except GerritError as e:
      raise GerritError(
751 752 753
          e.http_status,
          'Received unexpected http status while deleting reviewer "%s" '
          'from change %s' % (r, change))
754 755


756
def SetReview(host, change, msg=None, labels=None, notify=None, ready=None):
757 758 759 760
  """Set labels and/or add a message to a code review."""
  if not msg and not labels:
    return
  path = 'changes/%s/revisions/current/review' % change
761
  body = {'drafts': 'KEEP'}
762 763 764 765
  if msg:
    body['message'] = msg
  if labels:
    body['labels'] = labels
766
  if notify is not None:
767
    body['notify'] = 'ALL' if notify else 'NONE'
768 769
  if ready:
    body['ready'] = True
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
  conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  response = ReadHttpJsonResponse(conn)
  if labels:
    for key, val in labels.iteritems():
      if ('labels' not in response or key not in response['labels'] or
          int(response['labels'][key] != int(val))):
        raise GerritError(200, 'Unable to set "%s" label on change %s.' % (
            key, change))


def ResetReviewLabels(host, change, label, value='0', message=None,
                      notify=None):
  """Reset the value of a given label for all reviewers on a change."""
  # This is tricky, because we want to work on the "current revision", but
  # there's always the risk that "current revision" will change in between
  # API calls.  So, we check "current revision" at the beginning and end; if
  # it has changed, raise an exception.
  jmsg = GetChangeCurrentRevision(host, change)
  if not jmsg:
    raise GerritError(
        200, 'Could not get review information for change "%s"' % change)
  value = str(value)
  revision = jmsg[0]['current_revision']
  path = 'changes/%s/revisions/%s/review' % (change, revision)
  message = message or (
      '%s label set to %s programmatically.' % (label, value))
  jmsg = GetReview(host, change, revision)
  if not jmsg:
    raise GerritError(200, 'Could not get review information for revison %s '
                   'of change %s' % (revision, change))
  for review in jmsg.get('labels', {}).get(label, {}).get('all', []):
    if str(review.get('value', value)) != value:
      body = {
803
          'drafts': 'KEEP',
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
          'message': message,
          'labels': {label: value},
          'on_behalf_of': review['_account_id'],
      }
      if notify:
        body['notify'] = notify
      conn = CreateHttpConn(
          host, path, reqtype='POST', body=body)
      response = ReadHttpJsonResponse(conn)
      if str(response['labels'][label]) != value:
        username = review.get('email', jmsg.get('name', ''))
        raise GerritError(200, 'Unable to set %s label for user "%s"'
                       ' on change %s.' % (label, username, change))
  jmsg = GetChangeCurrentRevision(host, change)
  if not jmsg:
    raise GerritError(
        200, 'Could not get review information for change "%s"' % change)
  elif jmsg[0]['current_revision'] != revision:
    raise GerritError(200, 'While resetting labels on change "%s", '
                   'a new patchset was uploaded.' % change)
824 825


826 827 828 829 830 831 832 833 834 835 836
def CreateGerritBranch(host, project, branch, commit):
  """
  Create a new branch from given project and commit
  https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-branch

  Returns:
    A JSON with 'ref' key
  """
  path = 'projects/%s/branches/%s' % (project, branch)
  body = {'revision': commit}
  conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
837
  response = ReadHttpJsonResponse(conn, accept_statuses=[201])
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
  if response:
    return response
  raise GerritError(200, 'Unable to create gerrit branch')


def GetGerritBranch(host, project, branch):
  """
  Get a branch from given project and commit
  https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-branch

  Returns:
    A JSON object with 'revision' key
  """
  path = 'projects/%s/branches/%s' % (project, branch)
  conn = CreateHttpConn(host, path, reqtype='GET')
  response = ReadHttpJsonResponse(conn)
  if response:
    return response
  raise GerritError(200, 'Unable to get gerrit branch')


859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
def GetAccountDetails(host, account_id='self'):
  """Returns details of the account.

  If account_id is not given, uses magic value 'self' which corresponds to
  whichever account user is authenticating as.

  Documentation:
    https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-account
  """
  if account_id != 'self':
    account_id = int(account_id)
  conn = CreateHttpConn(host, '/accounts/%s' % account_id)
  return ReadHttpJsonResponse(conn)


874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
def PercentEncodeForGitRef(original):
  """Apply percent-encoding for strings sent to gerrit via git ref metadata.

  The encoding used is based on but stricter than URL encoding (Section 2.1
  of RFC 3986). The only non-escaped characters are alphanumerics, and
  'SPACE' (U+0020) can be represented as 'LOW LINE' (U+005F) or
  'PLUS SIGN' (U+002B).

  For more information, see the Gerrit docs here:

  https://gerrit-review.googlesource.com/Documentation/user-upload.html#message
  """
  safe = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '
  encoded = ''.join(c if c in safe else '%%%02X' % ord(c) for c in original)

  # spaces are not allowed in git refs; gerrit will interpret either '_' or
  # '+' (or '%20') as space. Use '_' since that has been supported the longest.
  return encoded.replace(' ', '_')


894 895 896 897 898 899 900 901 902
@contextlib.contextmanager
def tempdir():
  tdir = None
  try:
    tdir = tempfile.mkdtemp(suffix='gerrit_util')
    yield tdir
  finally:
    if tdir:
      gclient_utils.rmtree(tdir)
903 904 905 906 907 908 909 910 911 912 913


def ChangeIdentifier(project, change_number):
  """Returns change identifier "project~number" suitable for |chagne| arg of
  this module API.

  Such format is allows for more efficient Gerrit routing of HTTP requests,
  comparing to specifying just change_number.
  """
  assert int(change_number)
  return '%s~%s' % (urllib.quote(project, safe=''), change_number)