gerrit_util.py 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868
  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 annotations
  9. import base64
  10. import contextlib
  11. import http.cookiejar
  12. import json
  13. import logging
  14. import os
  15. import random
  16. import re
  17. import shutil
  18. import socket
  19. import subprocess
  20. import sys
  21. import tempfile
  22. import threading
  23. import time
  24. import urllib.parse
  25. from dataclasses import dataclass
  26. from io import StringIO
  27. from multiprocessing.pool import ThreadPool
  28. from typing import Any, Container, Dict, List, Optional
  29. from typing import Tuple, TypedDict, cast
  30. import httplib2
  31. import httplib2.socks
  32. import auth
  33. import gclient_utils
  34. import metrics
  35. import metrics_utils
  36. import newauth
  37. import scm
  38. import subprocess2
  39. # HACK: httplib2 has significant bugs with its proxy support in
  40. # python3. All httplib2 code should be rewritten to just use python
  41. # stdlib which does not have these bugs.
  42. #
  43. # Prior to that, however, we will directly patch the buggy
  44. # implementation of httplib2.socks.socksocket.__rewriteproxy which does
  45. # not properly expect bytes as its argument instead of str.
  46. #
  47. # Note that __rewriteproxy is inherently buggy, as it relies on the
  48. # python stdlib client to send the entire request header in a single
  49. # call to socket.sendall, which is not explicitly guaranteed.
  50. #
  51. # Changes:
  52. # * all string literals changed to bytes literals.
  53. # * all __symbols changed to _socksocket__symbols.
  54. # * Type annotations added to function signature.
  55. def __fixed_rewrite_proxy(self: httplib2.socks.socksocket, header: bytes):
  56. """ rewrite HTTP request headers to support non-tunneling proxies
  57. (i.e. those which do not support the CONNECT method).
  58. This only works for HTTP (not HTTPS) since HTTPS requires tunneling.
  59. """
  60. host, endpt = None, None
  61. hdrs = header.split(b"\r\n")
  62. for hdr in hdrs:
  63. if hdr.lower().startswith(b"host:"):
  64. host = hdr
  65. elif hdr.lower().startswith(b"get") or hdr.lower().startswith(b"post"):
  66. endpt = hdr
  67. if host and endpt:
  68. hdrs.remove(host)
  69. hdrs.remove(endpt)
  70. host = host.split(b" ")[1]
  71. endpt = endpt.split(b" ")
  72. if self._socksocket__proxy[4] != None \
  73. and self._socksocket__proxy[5] != None:
  74. hdrs.insert(0, self._socksocket__getauthheader())
  75. hdrs.insert(0, b"Host: %s" % host)
  76. hdrs.insert(0,
  77. b"%s http://%s%s %s" % (endpt[0], host, endpt[1], endpt[2]))
  78. return b"\r\n".join(hdrs)
  79. httplib2.socks.socksocket._socksocket__rewriteproxy = __fixed_rewrite_proxy
  80. # TODO: Should fix these warnings.
  81. # pylint: disable=line-too-long
  82. LOGGER = logging.getLogger()
  83. # With a starting sleep time of 12.0 seconds, x <= [1.8-2.2]x backoff, and six
  84. # total tries, the sleep time between the first and last tries will be ~6 min
  85. # (excluding time for each try).
  86. TRY_LIMIT = 6
  87. SLEEP_TIME = 12.0
  88. MAX_BACKOFF = 2.2
  89. MIN_BACKOFF = 1.8
  90. # Controls the transport protocol used to communicate with Gerrit.
  91. # This is parameterized primarily to enable GerritTestCase.
  92. GERRIT_PROTOCOL = 'https'
  93. # Controls how many concurrent Gerrit connections there can be.
  94. MAX_CONCURRENT_CONNECTION = 20
  95. def time_sleep(seconds):
  96. # Use this so that it can be mocked in tests without interfering with python
  97. # system machinery.
  98. return time.sleep(seconds)
  99. def time_time():
  100. # Use this so that it can be mocked in tests without interfering with python
  101. # system machinery.
  102. return time.time()
  103. def log_retry_and_sleep(seconds, attempt):
  104. LOGGER.info('Will retry in %d seconds (%d more times)...', seconds,
  105. TRY_LIMIT - attempt - 1)
  106. time_sleep(seconds)
  107. return seconds * random.uniform(MIN_BACKOFF, MAX_BACKOFF)
  108. class GerritError(Exception):
  109. """Exception class for errors commuicating with the gerrit-on-borg service."""
  110. def __init__(self, http_status, message, *args, **kwargs):
  111. super(GerritError, self).__init__(*args, **kwargs)
  112. self.http_status = http_status
  113. self.message = '(%d) %s' % (self.http_status, message)
  114. def __str__(self):
  115. return self.message
  116. def _QueryString(params, first_param=None):
  117. """Encodes query parameters in the key:val[+key:val...] format specified here:
  118. https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
  119. """
  120. q = [urllib.parse.quote(first_param)] if first_param else []
  121. q.extend(['%s:%s' % (key, val.replace(" ", "+")) for key, val in params])
  122. return '+'.join(q)
  123. class SSOHelper(object):
  124. """SSOHelper finds a Google-internal SSO helper."""
  125. _sso_cmd: Optional[str] = None
  126. def find_cmd(self) -> str:
  127. """Returns the cached command-line to invoke git-remote-sso.
  128. If git-remote-sso is not in $PATH, returns None.
  129. """
  130. if self._sso_cmd is not None:
  131. return self._sso_cmd
  132. cmd = shutil.which('git-remote-sso')
  133. if cmd is None:
  134. cmd = ''
  135. self._sso_cmd = cmd
  136. return cmd
  137. # Global instance
  138. ssoHelper = SSOHelper()
  139. def ShouldUseSSO(host: str, email: str) -> bool:
  140. """Return True if we should use SSO for the given Gerrit host and user."""
  141. LOGGER.debug("Determining whether we should use SSO...")
  142. if not newauth.Enabled():
  143. LOGGER.debug("SSO=False: not opted in")
  144. return False
  145. if newauth.SkipSSO():
  146. LOGGER.debug("SSO=False: set skip SSO config")
  147. return False
  148. if not ssoHelper.find_cmd():
  149. LOGGER.debug("SSO=False: no SSO command")
  150. return False
  151. if not email:
  152. LOGGER.debug(
  153. "SSO=True: email is empty or missing (and SSO command available)")
  154. return True
  155. if email.endswith('@google.com'):
  156. LOGGER.debug("SSO=True: email is google.com")
  157. return True
  158. if not email.endswith('@chromium.org'):
  159. LOGGER.debug("SSO=False: not chromium.org")
  160. return False
  161. authenticator = SSOAuthenticator()
  162. records = GetAccountEmails(host, 'self', authenticator=authenticator)
  163. if any(email == r['email'] for r in records):
  164. LOGGER.debug("SSO=True: email is linked to google.com")
  165. return True
  166. LOGGER.debug("SSO=False: unlinked chromium.org")
  167. return False
  168. class _Authenticator(object):
  169. """Base authenticator class for authenticator implementations to subclass."""
  170. # Cached _Authenticator subclass instance, resolved via get().
  171. _resolved: Optional[_Authenticator] = None
  172. _resolved_lock = threading.Lock()
  173. def authenticate(self, conn: HttpConn):
  174. """Adds authentication information to the HttpConn."""
  175. raise NotImplementedError()
  176. def debug_summary_state(self) -> str:
  177. """If this _Authenticator has any debugging information about its state,
  178. _WriteGitPushTraces will call this to include in the git push traces.
  179. Return value is any relevant debugging information with all PII/secrets
  180. redacted.
  181. """
  182. raise NotImplementedError()
  183. @classmethod
  184. def is_applicable(cls, *, conn: Optional[HttpConn] = None) -> bool:
  185. """Must return True if this Authenticator is available in the current
  186. environment.
  187. If conn is not None, return True if this Authenticator is
  188. applicable to the given conn in the current environment.
  189. """
  190. raise NotImplementedError()
  191. def ensure_authenticated(self, gerrit_host: str, git_host: str) -> Tuple[bool, str]:
  192. """Returns (bypassable, error message).
  193. If the error message is empty, there is no error to report.
  194. If bypassable is true, the caller will allow the user to continue past the
  195. error.
  196. """
  197. return (True, '')
  198. @classmethod
  199. def get(cls):
  200. """Returns: (_Authenticator) The identified _Authenticator to use.
  201. Probes the local system and its environment and identifies the
  202. _Authenticator instance to use.
  203. The resolved _Authenticator instance is cached as a class variable.
  204. """
  205. with cls._resolved_lock:
  206. if ret := cls._resolved:
  207. return ret
  208. use_new_auth = newauth.Enabled()
  209. # Allow skipping SSOAuthenticator for local testing purposes.
  210. skip_sso = newauth.SkipSSO()
  211. if use_new_auth:
  212. LOGGER.debug('_Authenticator.get: using new auth stack')
  213. if LuciContextAuthenticator.is_applicable():
  214. LOGGER.debug(
  215. '_Authenticator.get: using LUCI context authenticator')
  216. ret = LuciContextAuthenticator()
  217. else:
  218. LOGGER.debug(
  219. '_Authenticator.get: using chained authenticator')
  220. a = [
  221. SSOAuthenticator(),
  222. # GCE detection can't distinguish cloud workstations.
  223. GceAuthenticator(),
  224. LuciAuthAuthenticator(),
  225. ]
  226. if skip_sso:
  227. LOGGER.debug(
  228. 'Authenticator.get: skipping SSOAuthenticator.')
  229. a = a[1:]
  230. ret = ChainedAuthenticator(a)
  231. cls._resolved = ret
  232. return ret
  233. authenticators = [
  234. LuciContextAuthenticator,
  235. GceAuthenticator,
  236. CookiesAuthenticator,
  237. ]
  238. for candidate in authenticators:
  239. if candidate.is_applicable():
  240. LOGGER.debug('_Authenticator.get: Selected %s.',
  241. candidate.__name__)
  242. ret = candidate()
  243. cls._resolved = ret
  244. return ret
  245. auth_names = ', '.join(a.__name__ for a in authenticators)
  246. raise ValueError(
  247. f"Could not find suitable authenticator, tried: [{auth_names}]."
  248. )
  249. def debug_auth() -> Tuple[str, str]:
  250. """Returns the name of the chosen auth scheme and any additional debugging
  251. information for that authentication scheme. """
  252. authn = _Authenticator.get()
  253. return authn.__class__.__name__, authn.debug_summary_state()
  254. def ensure_authenticated(gerrit_host: str, git_host: str) -> Tuple[bool, str]:
  255. """Returns (bypassable, error message).
  256. If the error message is empty, there is no error to report. If bypassable is
  257. true, the caller will allow the user to continue past the error.
  258. """
  259. return _Authenticator.get().ensure_authenticated(gerrit_host, git_host)
  260. class SSOAuthenticator(_Authenticator):
  261. """SSOAuthenticator implements a Google-internal authentication scheme.
  262. TEMPORARY configuration for Googlers (one `url` block for each Gerrit host):
  263. [url "sso://chromium/"]
  264. insteadOf = https://chromium.googlesource.com/
  265. insteadOf = http://chromium.googlesource.com/
  266. [depot-tools]
  267. useNewAuthStack = 1
  268. """
  269. # This is set to true in tests, allows _parse_config to consume expired
  270. # cookies.
  271. _testing_load_expired_cookies = False
  272. # How long we should wait for the sso helper to write and close stdout.
  273. # Overridden in tests.
  274. _timeout_secs = 5
  275. @dataclass
  276. class SSOInfo:
  277. proxy: httplib2.ProxyInfo
  278. cookies: http.cookiejar.CookieJar
  279. headers: Dict[str, str]
  280. # SSOInfo is a cached blob of information used by the `authenticate` method.
  281. _sso_info: Optional[SSOInfo] = None
  282. _sso_info_lock = threading.Lock()
  283. @classmethod
  284. def _resolve_sso_cmd(cls) -> Tuple[str, ...]:
  285. """Returns the cached command-line to invoke git-remote-sso.
  286. If git-remote-sso is not in $PATH, returns ().
  287. """
  288. cmd = ssoHelper.find_cmd()
  289. if not cmd:
  290. return ()
  291. return (
  292. cmd,
  293. '-print_config',
  294. 'sso://*.git.corp.google.com',
  295. )
  296. @classmethod
  297. def is_applicable(cls, *, conn: Optional[HttpConn] = None) -> bool:
  298. if not cls._resolve_sso_cmd():
  299. return False
  300. email: str = scm.GIT.GetConfig(os.getcwd(), 'user.email', default='')
  301. if conn is not None:
  302. return ShouldUseSSO(conn.host, email)
  303. return email.endswith('@google.com')
  304. @classmethod
  305. def _parse_config(cls, config: str) -> SSOInfo:
  306. parsed: Dict[str, str] = dict(line.strip().split('=', 1)
  307. for line in config.splitlines())
  308. fullAuthHeader = cast(
  309. str,
  310. scm.GIT.Capture([
  311. 'config',
  312. '-f',
  313. parsed['include.path'],
  314. 'http.extraHeader',
  315. ]))
  316. headerKey, headerValue = fullAuthHeader.split(':', 1)
  317. headers = {headerKey.strip(): headerValue.strip()}
  318. proxy_host, proxy_port = parsed['http.proxy'].split(':', 1)
  319. cfpath = parsed['http.cookiefile']
  320. cj = http.cookiejar.MozillaCookieJar(cfpath)
  321. # NOTE: python3.8 doesn't support httponly cookie lines, so we parse
  322. # this manually. Once we move to python3.10+, this hack can be removed.
  323. with open(cfpath) as cf:
  324. cookiedata = cf.read().replace('#HttpOnly_', '')
  325. # _really_load is the way that MozillaCookieJar subclasses
  326. # FileCookieJar. Calling this directly is better than reimplementing the
  327. # entire _really_load function manually.
  328. cj._really_load(
  329. StringIO(cookiedata),
  330. cfpath,
  331. ignore_discard=False,
  332. ignore_expires=cls._testing_load_expired_cookies,
  333. )
  334. return cls.SSOInfo(proxy=httplib2.ProxyInfo(
  335. httplib2.socks.PROXY_TYPE_HTTP_NO_TUNNEL, proxy_host.encode(),
  336. int(proxy_port)),
  337. cookies=cj,
  338. headers=headers)
  339. @classmethod
  340. def _launch_sso_helper(cls) -> SSOInfo:
  341. """Launches the git-remote-sso process and extracts the parsed SSOInfo.
  342. Raises an exception if something goes wrong.
  343. """
  344. cmd = cls._resolve_sso_cmd()
  345. with tempdir() as tdir:
  346. tf = os.path.join(tdir, 'git-remote-sso.stderr')
  347. with open(tf, mode='w') as stderr_file:
  348. # NOTE: The git-remote-sso helper does the following:
  349. #
  350. # 1. writes files to disk.
  351. # 2. writes config to stdout, referencing those files.
  352. # 3. closes stdout (thus sending EOF to us, allowing
  353. # sys.stdout.read() to complete).
  354. # 4. waits for stdin to close.
  355. # 5. deletes files on disk (which is why we make sys.stdin a PIPE
  356. # instead of closing it outright).
  357. #
  358. # NOTE: the http.proxy value in the emitted config points to
  359. # a socket which is owned by a system service, not `proc` itself.
  360. with subprocess2.Popen(cmd,
  361. stdout=subprocess2.PIPE,
  362. stderr=stderr_file,
  363. stdin=subprocess2.PIPE,
  364. encoding='utf-8') as proc:
  365. stderr_file.close() # we can close after process starts.
  366. timedout = False
  367. def _fire_timeout():
  368. nonlocal timedout
  369. timedout = True
  370. proc.kill()
  371. timer = threading.Timer(cls._timeout_secs, _fire_timeout)
  372. timer.start()
  373. try:
  374. stdout_data = proc.stdout.read()
  375. finally:
  376. timer.cancel()
  377. if timedout:
  378. LOGGER.error(
  379. 'SSOAuthenticator: Timeout: %r: reading config.',
  380. cmd)
  381. raise subprocess.TimeoutExpired(
  382. cmd=cmd, timeout=cls._timeout_secs)
  383. # if the process already ended, then something is wrong.
  384. retcode = proc.poll()
  385. # if stdout was closed without any data, we need to wait for
  386. # end-of-process here and hope for an error message - the
  387. # poll above is racy in this case (we could see stdout EOF
  388. # but the process may not have quit yet).
  389. if not retcode and not stdout_data:
  390. retcode = proc.wait(timeout=cls._timeout_secs)
  391. # We timed out while doing `wait` - we can't safely open
  392. # stderr on windows, so just emit a generic timeout
  393. # exception.
  394. if retcode is None:
  395. LOGGER.error(
  396. 'SSOAuthenticator: Timeout: %r: waiting error output.',
  397. cmd)
  398. raise subprocess.TimeoutExpired(
  399. cmd=cmd, timeout=cls._timeout_secs)
  400. # Finally, if the poll or wait ended up getting the retcode,
  401. # it means the process failed, so we can read the stderr
  402. # file and reflect it back to the user.
  403. if retcode is not None:
  404. # process failed - we should be able to read the tempfile.
  405. with open(tf, encoding='utf-8') as stderr:
  406. sys.exit(
  407. f'SSOAuthenticator: exit {retcode}: {stderr.read().strip()}'
  408. )
  409. return cls._parse_config(stdout_data)
  410. @classmethod
  411. def _get_sso_info(cls) -> SSOInfo:
  412. with cls._sso_info_lock:
  413. info = cls._sso_info
  414. if not info:
  415. info = cls._launch_sso_helper()
  416. # HACK: `git-remote-sso` doesn't always properly warm up the
  417. # cookies - in this case, run a canned git operation against
  418. # a public repo to cause `git-remote-sso` to warm the cookies
  419. # up, and then try pulling config again.
  420. #
  421. # BUG: b/342644760
  422. if not any(c.domain == '.google.com' for c in info.cookies):
  423. LOGGER.debug('SSO: Refreshing .google.com cookies.')
  424. scm.GIT.Capture(['ls-remote', 'sso://chromium/All-Projects'])
  425. info = cls._launch_sso_helper()
  426. if not any(c.domain == '.google.com' for c in info.cookies):
  427. raise ValueError('Unable to extract .google.com cookie.')
  428. cls._sso_info = info
  429. return info
  430. def authenticate(self, conn: HttpConn):
  431. sso_info = self._get_sso_info()
  432. conn.proxy_info = sso_info.proxy
  433. conn.req_headers.update(sso_info.headers)
  434. # Now we must rewrite:
  435. # https://xxx.googlesource.com ->
  436. # http://xxx.git.corp.google.com
  437. parsed = urllib.parse.urlparse(conn.req_uri)
  438. parsed = parsed._replace(scheme='http')
  439. if (hostname :=
  440. parsed.hostname) and hostname.endswith('.googlesource.com'):
  441. assert not parsed.port, "SSOAuthenticator: netloc: port not supported"
  442. assert not parsed.username, "SSOAuthenticator: netloc: username not supported"
  443. assert not parsed.password, "SSOAuthenticator: netloc: password not supported"
  444. hostname_parts = hostname.rsplit('.', 2) # X, googlesource, com
  445. conn.req_host = hostname_parts[0] + '.git.corp.google.com'
  446. parsed = parsed._replace(netloc=conn.req_host)
  447. conn.req_uri = parsed.geturl()
  448. # Finally, add cookies
  449. sso_info.cookies.add_cookie_header(conn)
  450. assert 'Cookie' in conn.req_headers, (
  451. 'sso_info.cookies.add_cookie_header failed to add Cookie.')
  452. def debug_summary_state(self) -> str:
  453. return ''
  454. class CookiesAuthenticator(_Authenticator):
  455. """_Authenticator implementation that uses ".gitcookies" for token.
  456. Expected case for developer workstations.
  457. """
  458. _EMPTY = object()
  459. def __init__(self):
  460. # Credentials will be loaded lazily on first use. This ensures
  461. # _Authenticator get() can always construct an authenticator, even if
  462. # something is broken. This allows 'creds-check' to proceed to actually
  463. # checking creds later, rigorously (instead of blowing up with a cryptic
  464. # error if they are wrong).
  465. self._gitcookies = self._EMPTY
  466. @classmethod
  467. def is_applicable(cls, *, conn: Optional[HttpConn] = None) -> bool:
  468. # We consider CookiesAuthenticator always applicable for now.
  469. return True
  470. @property
  471. def gitcookies(self):
  472. if self._gitcookies is self._EMPTY:
  473. self._gitcookies = self._get_gitcookies()
  474. return self._gitcookies
  475. @classmethod
  476. def get_new_password_url(cls, host):
  477. assert not host.startswith('http')
  478. # Assume *.googlesource.com pattern.
  479. parts = host.split('.')
  480. # remove -review suffix if present.
  481. if parts[0].endswith('-review'):
  482. parts[0] = parts[0][:-len('-review')]
  483. return 'https://%s/new-password' % ('.'.join(parts))
  484. @classmethod
  485. def _get_new_password_message(cls, host):
  486. if host is None:
  487. return ('Git host for Gerrit upload is unknown. Check your remote '
  488. 'and the branch your branch is tracking. This tool assumes '
  489. 'that you are using a git server at *.googlesource.com.')
  490. url = cls.get_new_password_url(host)
  491. return 'You can (re)generate your credentials by visiting %s' % url
  492. @classmethod
  493. def get_gitcookies_path(cls) -> str:
  494. if envVal := os.getenv('GIT_COOKIES_PATH'):
  495. return envVal
  496. return os.path.expanduser(
  497. scm.GIT.GetConfig(os.getcwd(), 'http.cookiefile',
  498. os.path.join('~', '.gitcookies')))
  499. @classmethod
  500. def _get_gitcookies(cls):
  501. gitcookies = {}
  502. path = cls.get_gitcookies_path()
  503. if not os.path.exists(path):
  504. return gitcookies
  505. try:
  506. f = gclient_utils.FileRead(path, 'rb').splitlines()
  507. except IOError:
  508. return gitcookies
  509. for line in f:
  510. try:
  511. fields = line.strip().split('\t')
  512. if line.strip().startswith('#') or len(fields) != 7:
  513. continue
  514. domain, xpath, key, value = fields[0], fields[2], fields[
  515. 5], fields[6]
  516. if xpath == '/' and key == 'o':
  517. if value.startswith('git-'):
  518. login, secret_token = value.split('=', 1)
  519. gitcookies[domain] = (login, secret_token)
  520. else:
  521. gitcookies[domain] = ('', value)
  522. except (IndexError, ValueError, TypeError) as exc:
  523. LOGGER.warning(exc)
  524. return gitcookies
  525. def _get_auth_for_host(self, host):
  526. for domain, creds in self.gitcookies.items():
  527. if http.cookiejar.domain_match(host, domain):
  528. return (creds[0], creds[1])
  529. return None
  530. def authenticate(self, conn: HttpConn):
  531. a = self._get_auth_for_host(conn.req_host)
  532. if a:
  533. login, cred = a
  534. if login:
  535. secret = base64.b64encode(f'{login}:{cred}'.encode('utf-8'))
  536. conn.req_headers[
  537. 'Authorization'] = f'Basic {secret.decode("utf-8")}'
  538. else:
  539. conn.req_headers['Authorization'] = f'Bearer {cred}'
  540. def ensure_authenticated(self, gerrit_host: str, git_host: str) -> Tuple[bool, str]:
  541. """Returns (bypassable, error message).
  542. If the error message is empty, there is no error to report.
  543. If bypassable is true, the caller will allow the user to continue past the
  544. error.
  545. """
  546. # Lazy-loader to identify Gerrit and Git hosts.
  547. gerrit_auth = self._get_auth_for_host(gerrit_host)
  548. git_auth = self._get_auth_for_host(git_host)
  549. if gerrit_auth and git_auth:
  550. if gerrit_auth == git_auth:
  551. return True, ''
  552. all_gsrc = self._get_auth_for_host('d0esN0tEx1st.googlesource.com')
  553. print(
  554. 'WARNING: You have different credentials for Gerrit and git hosts:\n'
  555. ' %s\n'
  556. ' %s\n'
  557. ' Consider running the following command:\n'
  558. ' git cl creds-check\n'
  559. ' %s\n'
  560. ' %s' %
  561. (git_host, gerrit_host,
  562. ('Hint: delete creds for .googlesource.com' if all_gsrc else
  563. ''), self._get_new_password_message(git_host)))
  564. return True, 'If you know what you are doing'
  565. missing = (([] if gerrit_auth else [gerrit_host]) +
  566. ([] if git_auth else [git_host]))
  567. return False, ('Credentials for the following hosts are required:\n'
  568. ' %s\n'
  569. 'These are read from %s\n'
  570. '%s' % ('\n '.join(missing), self.get_gitcookies_path(),
  571. self._get_new_password_message(git_host)))
  572. # Used to redact the cookies from the gitcookies file.
  573. GITCOOKIES_REDACT_RE = re.compile(r'1/.*')
  574. def debug_summary_state(self) -> str:
  575. gitcookies_path = self.get_gitcookies_path()
  576. if os.path.isfile(gitcookies_path):
  577. gitcookies = gclient_utils.FileRead(gitcookies_path)
  578. return self.GITCOOKIES_REDACT_RE.sub('REDACTED', gitcookies)
  579. return ''
  580. def get_auth_email(self, host):
  581. """Best effort parsing of email to be used for auth for the given host."""
  582. a = self._get_auth_for_host(host)
  583. if not a:
  584. return None
  585. login = a[0]
  586. # login typically looks like 'git-xxx.example.com'
  587. if not login.startswith('git-') or '.' not in login:
  588. return None
  589. username, domain = login[len('git-'):].split('.', 1)
  590. return '%s@%s' % (username, domain)
  591. class GceAuthenticator(_Authenticator):
  592. """_Authenticator implementation that uses GCE metadata service for token.
  593. """
  594. _INFO_URL = 'http://metadata.google.internal'
  595. _ACQUIRE_URL = ('%s/computeMetadata/v1/instance/'
  596. 'service-accounts/default/token' % _INFO_URL)
  597. _ACQUIRE_HEADERS = {"Metadata-Flavor": "Google"}
  598. _cache_is_gce = None
  599. _token_cache = None
  600. _token_expiration = None
  601. @classmethod
  602. def is_applicable(cls, *, conn: Optional[HttpConn] = None):
  603. if os.getenv('SKIP_GCE_AUTH_FOR_GIT'):
  604. return False
  605. if cls._cache_is_gce is None:
  606. cls._cache_is_gce = cls._test_is_gce()
  607. return cls._cache_is_gce
  608. @classmethod
  609. def _test_is_gce(cls):
  610. # Based on https://cloud.google.com/compute/docs/metadata#runninggce
  611. resp, _ = cls._get(cls._INFO_URL)
  612. if resp is None:
  613. return False
  614. return resp.get('metadata-flavor') == 'Google'
  615. @staticmethod
  616. def _get(url, **kwargs):
  617. next_delay_sec = 1.0
  618. for i in range(TRY_LIMIT):
  619. p = urllib.parse.urlparse(url)
  620. if p.scheme not in ('http', 'https'):
  621. raise RuntimeError("Don't know how to work with protocol '%s'" %
  622. p.scheme)
  623. try:
  624. resp, contents = httplib2.Http().request(url, 'GET', **kwargs)
  625. except (socket.error, httplib2.HttpLib2Error,
  626. httplib2.socks.ProxyError) as e:
  627. LOGGER.debug('GET [%s] raised %s', url, e)
  628. return None, None
  629. LOGGER.debug('GET [%s] #%d/%d (%d)', url, i + 1, TRY_LIMIT,
  630. resp.status)
  631. if resp.status < 500:
  632. return (resp, contents)
  633. # Retry server error status codes.
  634. LOGGER.warning('Encountered server error')
  635. if TRY_LIMIT - i > 1:
  636. next_delay_sec = log_retry_and_sleep(next_delay_sec, i)
  637. return None, None
  638. @classmethod
  639. def _get_token_dict(cls):
  640. # If cached token is valid for at least 25 seconds, return it.
  641. if cls._token_cache and time_time() + 25 < cls._token_expiration:
  642. return cls._token_cache
  643. resp, contents = cls._get(cls._ACQUIRE_URL,
  644. headers=cls._ACQUIRE_HEADERS)
  645. if resp is None or resp.status != 200:
  646. return None
  647. cls._token_cache = json.loads(contents)
  648. cls._token_expiration = cls._token_cache['expires_in'] + time_time()
  649. return cls._token_cache
  650. def authenticate(self, conn: HttpConn):
  651. token_dict = self._get_token_dict()
  652. if not token_dict:
  653. return
  654. conn.req_headers[
  655. 'Authorization'] = '%(token_type)s %(access_token)s' % token_dict
  656. def debug_summary_state(self) -> str:
  657. # TODO(b/343230702) - report ambient account name.
  658. return ''
  659. class LuciContextAuthenticator(_Authenticator):
  660. """_Authenticator implementation that uses LUCI_CONTEXT ambient local auth.
  661. """
  662. @staticmethod
  663. def is_applicable(*, conn: Optional[HttpConn] = None):
  664. return auth.has_luci_context_local_auth()
  665. def __init__(self):
  666. self._authenticator = auth.Authenticator(' '.join(
  667. [auth.OAUTH_SCOPE_EMAIL, auth.OAUTH_SCOPE_GERRIT]))
  668. def authenticate(self, conn: HttpConn):
  669. conn.req_headers[
  670. 'Authorization'] = f'Bearer {self._authenticator.get_access_token().token}'
  671. def debug_summary_state(self) -> str:
  672. # TODO(b/343230702) - report ambient account name.
  673. return ''
  674. class LuciAuthAuthenticator(LuciContextAuthenticator):
  675. """_Authenticator implementation that uses `luci-auth` credentials.
  676. This is the same as LuciContextAuthenticator, except that it is for local
  677. non-google.com developer credentials.
  678. """
  679. @staticmethod
  680. def is_applicable(*, conn: Optional[HttpConn] = None):
  681. return True
  682. class ChainedAuthenticator(_Authenticator):
  683. """_Authenticator that delegates to others in sequence.
  684. Authenticators should implement the method `is_applicable_for`.
  685. """
  686. def __init__(self, authenticators: List[_Authenticator]):
  687. self.authenticators = list(authenticators)
  688. def is_applicable(self, *, conn: Optional[HttpConn] = None) -> bool:
  689. return bool(any(
  690. a.is_applicable(conn=conn) for a in self.authenticators))
  691. def authenticate(self, conn: HttpConn):
  692. for a in self.authenticators:
  693. if a.is_applicable(conn=conn):
  694. a.authenticate(conn)
  695. break
  696. else:
  697. raise ValueError(
  698. f'{self!r} has no applicable authenticator for {conn!r}')
  699. def debug_summary_state(self) -> str:
  700. return ''
  701. class ReqParams(TypedDict):
  702. uri: str
  703. method: str
  704. headers: Dict[str, str]
  705. body: Optional[str]
  706. class HttpConn(httplib2.Http):
  707. """HttpConn is an httplib2.Http with additional request-specific fields."""
  708. def __init__(self, *args, req_host: str, req_uri: str, req_method: str,
  709. req_headers: Dict[str, str], req_body: Optional[str],
  710. **kwargs) -> None:
  711. self.req_host = req_host
  712. self.req_uri = req_uri
  713. self.req_method = req_method
  714. self.req_headers = req_headers
  715. self.req_body = req_body
  716. super().__init__(*args, **kwargs)
  717. @property
  718. def req_params(self) -> ReqParams:
  719. return {
  720. 'uri': self.req_uri,
  721. 'method': self.req_method,
  722. 'headers': self.req_headers,
  723. 'body': self.req_body,
  724. }
  725. # NOTE: We want to use HttpConn with CookieJar.add_cookie_header, so have
  726. # compatible interface for that here.
  727. #
  728. # NOTE: Someone should really normalize this 'HttpConn' and httplib2
  729. # implementation to just be plain python3 stdlib instead. All of this was
  730. # written during the bad old days of python2.6/2.7, pre-vpython.
  731. def has_header(self, header: str) -> bool:
  732. return header in self.req_headers
  733. def get_full_url(self) -> str:
  734. return self.req_uri
  735. def get_header(self,
  736. header: str,
  737. default: Optional[str] = None) -> Optional[str]:
  738. return self.req_headers.get(header, default)
  739. def add_unredirected_header(self, header: str, value: str):
  740. # NOTE: httplib2 does not support unredirected headers.
  741. self.req_headers[header] = value
  742. @property
  743. def unverifiable(self) -> bool:
  744. return False
  745. @property
  746. def origin_req_host(self) -> str:
  747. return self.req_host
  748. @property
  749. def type(self) -> str:
  750. return urllib.parse.urlparse(self.req_uri).scheme
  751. @property
  752. def host(self) -> str:
  753. return self.req_host
  754. def CreateHttpConn(host: str,
  755. path: str,
  756. reqtype='GET',
  757. headers: Optional[Dict[str, str]] = None,
  758. body: Optional[Dict] = None,
  759. timeout=300,
  760. *,
  761. authenticator: Optional[_Authenticator] = None) -> HttpConn:
  762. """Opens an HTTPS connection to a Gerrit service, and sends a request."""
  763. headers = headers or {}
  764. bare_host = host.partition(':')[0]
  765. url = path
  766. if not url.startswith('/'):
  767. url = '/' + url
  768. if not url.startswith('/a/'):
  769. url = '/a%s' % url
  770. rendered_body: Optional[str] = None
  771. if body:
  772. rendered_body = json.dumps(body, sort_keys=True)
  773. headers.setdefault('Content-Type', 'application/json')
  774. uri = urllib.parse.urljoin(f'{GERRIT_PROTOCOL}://{host}', url)
  775. conn = HttpConn(timeout=timeout,
  776. req_host=host,
  777. req_uri=uri,
  778. req_method=reqtype,
  779. req_headers=headers,
  780. req_body=rendered_body)
  781. if authenticator is None:
  782. authenticator = _Authenticator.get()
  783. # TODO(crbug.com/1059384): Automatically detect when running on cloudtop.
  784. if isinstance(authenticator, GceAuthenticator):
  785. print('If you\'re on a cloudtop instance, export '
  786. 'SKIP_GCE_AUTH_FOR_GIT=1 in your env.')
  787. authenticator.authenticate(conn)
  788. if 'Authorization' not in conn.req_headers:
  789. LOGGER.debug('No authorization found for %s.' % bare_host)
  790. if LOGGER.isEnabledFor(logging.DEBUG):
  791. LOGGER.debug('%s %s', conn.req_method, conn.req_uri)
  792. LOGGER.debug('conn.proxy_info=%r', conn.proxy_info)
  793. for key, val in conn.req_headers.items():
  794. if key in ('Authorization', 'Cookie'):
  795. val = 'HIDDEN'
  796. LOGGER.debug('%s: %s', key, val)
  797. if conn.req_body:
  798. LOGGER.debug(conn.req_body)
  799. return conn
  800. def ReadHttpResponse(conn: HttpConn,
  801. accept_statuses: Container[int] = frozenset([200])):
  802. """Reads an HTTP response from a connection into a string buffer.
  803. Args:
  804. conn: An Http object created by CreateHttpConn above.
  805. accept_statuses: Treat any of these statuses as success. Default: [200]
  806. Common additions include 204, 400, and 404.
  807. Returns:
  808. A string buffer containing the connection's reply.
  809. """
  810. response = contents = None
  811. sleep_time = SLEEP_TIME
  812. for idx in range(TRY_LIMIT):
  813. before_response = time.time()
  814. try:
  815. response, contents = conn.request(**conn.req_params)
  816. except socket.timeout:
  817. if idx < TRY_LIMIT - 1:
  818. sleep_time = log_retry_and_sleep(sleep_time, idx)
  819. continue
  820. raise
  821. contents = contents.decode('utf-8', 'replace')
  822. response_time = time.time() - before_response
  823. metrics.collector.add_repeated(
  824. 'http_requests',
  825. metrics_utils.extract_http_metrics(conn.req_params['uri'],
  826. conn.req_params['method'],
  827. response.status, response_time))
  828. # If response.status is an accepted status,
  829. # or response.status < 500 then the result is final; break retry loop.
  830. # If the response is 404/409 it might be because of replication lag,
  831. # so keep trying anyway. If it is 429, it is generally ok to retry after
  832. # a backoff.
  833. if (response.status in accept_statuses or response.status < 500
  834. and response.status not in [404, 409, 429]):
  835. LOGGER.debug('got response %d for %s %s', response.status,
  836. conn.req_params['method'], conn.req_params['uri'])
  837. # If 404 was in accept_statuses, then it's expected that the file
  838. # might not exist, so don't return the gitiles error page because
  839. # that's not the "content" that was actually requested.
  840. if response.status == 404:
  841. contents = ''
  842. break
  843. # A status >=500 is assumed to be a possible transient error; retry.
  844. http_version = 'HTTP/%s' % ('1.1' if response.version == 11 else '1.0')
  845. LOGGER.warning(
  846. 'A transient error occurred while querying %s:\n'
  847. '%s %s %s\n'
  848. '%s %d %s\n'
  849. '%s', conn.req_host, conn.req_params['method'],
  850. conn.req_params['uri'], http_version, http_version, response.status,
  851. response.reason, contents)
  852. if idx < TRY_LIMIT - 1:
  853. sleep_time = log_retry_and_sleep(sleep_time, idx)
  854. # end of retries loop
  855. # Help the type checker a bit here - it can't figure out the `except` logic
  856. # in the loop above.
  857. assert response, (
  858. 'Impossible: End of retry loop without response or exception.')
  859. if response.status in accept_statuses:
  860. return StringIO(contents)
  861. if response.status in (302, 401, 403):
  862. www_authenticate = response.get('www-authenticate')
  863. if not www_authenticate:
  864. print('Your Gerrit credentials might be misconfigured.')
  865. else:
  866. auth_match = re.search('realm="([^"]+)"', www_authenticate, re.I)
  867. host = auth_match.group(1) if auth_match else conn.req_host
  868. new_password_url = CookiesAuthenticator.get_new_password_url(host)
  869. print('Authentication failed. Please make sure your .gitcookies '
  870. f'file has credentials for {host}.')
  871. print(f'(Re)generate credentials here: {new_password_url}')
  872. print('Try:\n git cl creds-check')
  873. reason = '%s: %s' % (response.reason, contents)
  874. raise GerritError(response.status, reason)
  875. def ReadHttpJsonResponse(
  876. conn, accept_statuses: Container[int] = frozenset([200])) -> dict:
  877. """Parses an https response as json."""
  878. fh = ReadHttpResponse(conn, accept_statuses)
  879. # The first line of the response should always be: )]}'
  880. s = fh.readline()
  881. if s and s.rstrip() != ")]}'":
  882. raise GerritError(200, 'Unexpected json output: %s' % s[:100])
  883. s = fh.read()
  884. if not s:
  885. return {}
  886. return json.loads(s)
  887. def CallGerritApi(host, path, **kwargs):
  888. """Helper for calling a Gerrit API that returns a JSON response."""
  889. conn_kwargs = {}
  890. conn_kwargs.update(
  891. (k, kwargs[k]) for k in ['reqtype', 'headers', 'body'] if k in kwargs)
  892. conn = CreateHttpConn(host, path, **conn_kwargs)
  893. read_kwargs = {}
  894. read_kwargs.update(
  895. (k, kwargs[k]) for k in ['accept_statuses'] if k in kwargs)
  896. return ReadHttpJsonResponse(conn, **read_kwargs)
  897. def QueryChanges(host,
  898. params,
  899. first_param=None,
  900. limit=None,
  901. o_params=None,
  902. start=None):
  903. """
  904. Queries a gerrit-on-borg server for changes matching query terms.
  905. Args:
  906. params: A list of key:value pairs for search parameters, as documented
  907. here (e.g. ('is', 'owner') for a parameter 'is:owner'):
  908. https://gerrit-review.googlesource.com/Documentation/user-search.html#search-operators
  909. first_param: A change identifier
  910. limit: Maximum number of results to return.
  911. start: how many changes to skip (starting with the most recent)
  912. o_params: A list of additional output specifiers, as documented here:
  913. https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
  914. Returns:
  915. A list of json-decoded query results.
  916. """
  917. # Note that no attempt is made to escape special characters; YMMV.
  918. if not params and not first_param:
  919. raise RuntimeError('QueryChanges requires search parameters')
  920. path = 'changes/?q=%s' % _QueryString(params, first_param)
  921. if start:
  922. path = '%s&start=%s' % (path, start)
  923. if limit:
  924. path = '%s&n=%d' % (path, limit)
  925. if o_params:
  926. path = '%s&%s' % (path, '&'.join(['o=%s' % p for p in o_params]))
  927. return ReadHttpJsonResponse(CreateHttpConn(host, path, timeout=30))
  928. def GenerateAllChanges(host,
  929. params,
  930. first_param=None,
  931. limit=500,
  932. o_params=None,
  933. start=None):
  934. """Queries a gerrit-on-borg server for all the changes matching the query
  935. terms.
  936. WARNING: this is unreliable if a change matching the query is modified while
  937. this function is being called.
  938. A single query to gerrit-on-borg is limited on the number of results by the
  939. limit parameter on the request (see QueryChanges) and the server maximum
  940. limit.
  941. Args:
  942. params, first_param: Refer to QueryChanges().
  943. limit: Maximum number of requested changes per query.
  944. o_params: Refer to QueryChanges().
  945. start: Refer to QueryChanges().
  946. Returns:
  947. A generator object to the list of returned changes.
  948. """
  949. already_returned = set()
  950. def at_most_once(cls):
  951. for cl in cls:
  952. if cl['_number'] not in already_returned:
  953. already_returned.add(cl['_number'])
  954. yield cl
  955. start = start or 0
  956. cur_start = start
  957. more_changes = True
  958. while more_changes:
  959. # This will fetch changes[start..start+limit] sorted by most recently
  960. # updated. Since the rank of any change in this list can be changed any
  961. # time (say user posting comment), subsequent calls may overalp like
  962. # this: > initial order ABCDEFGH query[0..3] => ABC > E gets updated.
  963. # New order: EABCDFGH query[3..6] => CDF # C is a dup query[6..9] =>
  964. # GH # E is missed.
  965. page = QueryChanges(host, params, first_param, limit, o_params,
  966. cur_start)
  967. for cl in at_most_once(page):
  968. yield cl
  969. more_changes = [cl for cl in page if '_more_changes' in cl]
  970. if len(more_changes) > 1:
  971. raise GerritError(
  972. 200,
  973. 'Received %d changes with a _more_changes attribute set but should '
  974. 'receive at most one.' % len(more_changes))
  975. if more_changes:
  976. cur_start += len(page)
  977. # If we paged through, query again the first page which in most
  978. # circumstances will fetch all changes that were modified while this
  979. # function was run.
  980. if start != cur_start:
  981. page = QueryChanges(host, params, first_param, limit, o_params, start)
  982. for cl in at_most_once(page):
  983. yield cl
  984. def MultiQueryChanges(host,
  985. params,
  986. change_list,
  987. limit=None,
  988. o_params=None,
  989. start=None):
  990. """Initiate a query composed of multiple sets of query parameters."""
  991. if not change_list:
  992. raise RuntimeError(
  993. "MultiQueryChanges requires a list of change numbers/id's")
  994. q = [
  995. 'q=%s' % '+OR+'.join([urllib.parse.quote(str(x)) for x in change_list])
  996. ]
  997. if params:
  998. q.append(_QueryString(params))
  999. if limit:
  1000. q.append('n=%d' % limit)
  1001. if start:
  1002. q.append('S=%s' % start)
  1003. if o_params:
  1004. q.extend(['o=%s' % p for p in o_params])
  1005. path = 'changes/?%s' % '&'.join(q)
  1006. try:
  1007. result = ReadHttpJsonResponse(CreateHttpConn(host, path))
  1008. except GerritError as e:
  1009. msg = '%s:\n%s' % (e.message, path)
  1010. raise GerritError(e.http_status, msg)
  1011. return result
  1012. def GetGerritFetchUrl(host):
  1013. """Given a Gerrit host name returns URL of a Gerrit instance to fetch from."""
  1014. return '%s://%s/' % (GERRIT_PROTOCOL, host)
  1015. def GetCodeReviewTbrScore(host, project):
  1016. """Given a Gerrit host name and project, return the Code-Review score for TBR.
  1017. """
  1018. conn = CreateHttpConn(host,
  1019. '/projects/%s' % urllib.parse.quote(project, ''))
  1020. project = ReadHttpJsonResponse(conn)
  1021. if ('labels' not in project or 'Code-Review' not in project['labels']
  1022. or 'values' not in project['labels']['Code-Review']):
  1023. return 1
  1024. return max([int(x) for x in project['labels']['Code-Review']['values']])
  1025. def GetChangePageUrl(host, change_number):
  1026. """Given a Gerrit host name and change number, returns change page URL."""
  1027. return '%s://%s/#/c/%d/' % (GERRIT_PROTOCOL, host, change_number)
  1028. def GetChangeUrl(host, change):
  1029. """Given a Gerrit host name and change ID, returns a URL for the change."""
  1030. return '%s://%s/a/changes/%s' % (GERRIT_PROTOCOL, host, change)
  1031. def GetChange(host, change, accept_statuses: Container[int] = frozenset([200])):
  1032. """Queries a Gerrit server for information about a single change."""
  1033. path = 'changes/%s' % change
  1034. return ReadHttpJsonResponse(CreateHttpConn(host, path),
  1035. accept_statuses=accept_statuses)
  1036. def GetChangeDetail(host, change, o_params=None):
  1037. """Queries a Gerrit server for extended information about a single change."""
  1038. path = 'changes/%s/detail' % change
  1039. if o_params:
  1040. path += '?%s' % '&'.join(['o=%s' % p for p in o_params])
  1041. return ReadHttpJsonResponse(CreateHttpConn(host, path))
  1042. def GetChangeCommit(host: str, change: str, revision: str = 'current') -> dict:
  1043. """Query a Gerrit server for a revision associated with a change."""
  1044. path = 'changes/%s/revisions/%s/commit?links' % (change, revision)
  1045. return ReadHttpJsonResponse(CreateHttpConn(host, path))
  1046. def GetChangeCurrentRevision(host, change):
  1047. """Get information about the latest revision for a given change."""
  1048. return QueryChanges(host, [], change, o_params=('CURRENT_REVISION', ))
  1049. def GetChangeRevisions(host, change):
  1050. """Gets information about all revisions associated with a change."""
  1051. return QueryChanges(host, [], change, o_params=('ALL_REVISIONS', ))
  1052. def GetChangeReview(host, change, revision=None):
  1053. """Gets the current review information for a change."""
  1054. if not revision:
  1055. jmsg = GetChangeRevisions(host, change)
  1056. if not jmsg:
  1057. return None
  1058. if len(jmsg) > 1:
  1059. raise GerritError(
  1060. 200, 'Multiple changes found for ChangeId %s.' % change)
  1061. revision = jmsg[0]['current_revision']
  1062. path = 'changes/%s/revisions/%s/review'
  1063. return ReadHttpJsonResponse(CreateHttpConn(host, path))
  1064. def GetChangeComments(host, change):
  1065. """Get the line- and file-level comments on a change."""
  1066. path = 'changes/%s/comments' % change
  1067. return ReadHttpJsonResponse(CreateHttpConn(host, path))
  1068. def GetChangeRobotComments(host, change):
  1069. """Gets the line- and file-level robot comments on a change."""
  1070. path = 'changes/%s/robotcomments' % change
  1071. return ReadHttpJsonResponse(CreateHttpConn(host, path))
  1072. def GetRelatedChanges(host, change, revision='current'):
  1073. """Gets the related changes for a given change and revision."""
  1074. path = 'changes/%s/revisions/%s/related' % (change, revision)
  1075. return ReadHttpJsonResponse(CreateHttpConn(host, path))
  1076. def AbandonChange(host, change, msg=''):
  1077. """Abandons a Gerrit change."""
  1078. path = 'changes/%s/abandon' % change
  1079. body = {'message': msg} if msg else {}
  1080. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1081. return ReadHttpJsonResponse(conn)
  1082. def MoveChange(host, change, destination_branch):
  1083. """Move a Gerrit change to different destination branch."""
  1084. path = 'changes/%s/move' % change
  1085. body = {'destination_branch': destination_branch, 'keep_all_votes': True}
  1086. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1087. return ReadHttpJsonResponse(conn)
  1088. def RestoreChange(host, change, msg=''):
  1089. """Restores a previously abandoned change."""
  1090. path = 'changes/%s/restore' % change
  1091. body = {'message': msg} if msg else {}
  1092. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1093. return ReadHttpJsonResponse(conn)
  1094. def RebaseChange(host, change, base=None):
  1095. """Rebases a change."""
  1096. path = f'changes/{change}/rebase'
  1097. body = {'base': base} if base else {}
  1098. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1099. return ReadHttpJsonResponse(conn)
  1100. def SubmitChange(host, change):
  1101. """Submits a Gerrit change via Gerrit."""
  1102. path = 'changes/%s/submit' % change
  1103. conn = CreateHttpConn(host, path, reqtype='POST')
  1104. return ReadHttpJsonResponse(conn)
  1105. def GetChangesSubmittedTogether(host, change):
  1106. """Get all changes submitted with the given one."""
  1107. path = 'changes/%s/submitted_together?o=NON_VISIBLE_CHANGES' % change
  1108. conn = CreateHttpConn(host, path, reqtype='GET')
  1109. return ReadHttpJsonResponse(conn)
  1110. def PublishChangeEdit(host, change, notify=True):
  1111. """Publish a Gerrit change edit."""
  1112. path = 'changes/%s/edit:publish' % change
  1113. body = {'notify': 'ALL' if notify else 'NONE'}
  1114. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1115. return ReadHttpJsonResponse(conn, accept_statuses=(204, ))
  1116. def ChangeEdit(host, change, path, data):
  1117. """Puts content of a file into a change edit."""
  1118. path = 'changes/%s/edit/%s' % (change, urllib.parse.quote(path, ''))
  1119. body = {
  1120. 'binary_content':
  1121. 'data:text/plain;base64,%s' %
  1122. base64.b64encode(data.encode('utf-8')).decode('utf-8')
  1123. }
  1124. conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
  1125. return ReadHttpJsonResponse(conn, accept_statuses=(204, 409))
  1126. def SetChangeEditMessage(host, change, message):
  1127. """Sets the commit message of a change edit."""
  1128. path = 'changes/%s/edit:message' % change
  1129. body = {'message': message}
  1130. conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
  1131. return ReadHttpJsonResponse(conn, accept_statuses=(204, 409))
  1132. def HasPendingChangeEdit(host, change):
  1133. conn = CreateHttpConn(host, 'changes/%s/edit' % change)
  1134. try:
  1135. ReadHttpResponse(conn)
  1136. except GerritError as e:
  1137. # 204 No Content means no pending change.
  1138. if e.http_status == 204:
  1139. return False
  1140. raise
  1141. return True
  1142. def DeletePendingChangeEdit(host, change):
  1143. conn = CreateHttpConn(host, 'changes/%s/edit' % change, reqtype='DELETE')
  1144. # On success, Gerrit returns status 204; if the edit was already deleted it
  1145. # returns 404. Anything else is an error.
  1146. ReadHttpResponse(conn, accept_statuses=[204, 404])
  1147. def CherryPick(host, change, destination, revision='current', message=None):
  1148. """Create a cherry-pick commit from the given change, onto the given
  1149. destination.
  1150. """
  1151. path = 'changes/%s/revisions/%s/cherrypick' % (change, revision)
  1152. body = {'destination': destination}
  1153. if message:
  1154. body['message'] = message
  1155. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1156. return ReadHttpJsonResponse(conn)
  1157. def CherryPickCommit(host, project, commit, destination):
  1158. """Cherry-pick a commit from a project to a destination branch."""
  1159. project = urllib.parse.quote(project, '')
  1160. path = f'projects/{project}/commits/{commit}/cherrypick'
  1161. body = {'destination': destination}
  1162. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1163. return ReadHttpJsonResponse(conn)
  1164. def GetFileContents(host, change, path):
  1165. """Get the contents of a file with the given path in the given revision.
  1166. Returns:
  1167. A bytes object with the file's contents.
  1168. """
  1169. path = 'changes/%s/revisions/current/files/%s/content' % (
  1170. change, urllib.parse.quote(path, ''))
  1171. conn = CreateHttpConn(host, path, reqtype='GET')
  1172. return base64.b64decode(ReadHttpResponse(conn).read())
  1173. def SetCommitMessage(host, change, description, notify='ALL'):
  1174. """Updates a commit message."""
  1175. assert notify in ('ALL', 'NONE')
  1176. path = 'changes/%s/message' % change
  1177. body = {'message': description, 'notify': notify}
  1178. conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
  1179. try:
  1180. ReadHttpResponse(conn, accept_statuses=[200, 204])
  1181. except GerritError as e:
  1182. raise GerritError(
  1183. e.http_status,
  1184. 'Received unexpected http status while editing message '
  1185. 'in change %s' % change)
  1186. def GetCommitIncludedIn(host, project, commit):
  1187. """Retrieves the branches and tags for a given commit.
  1188. https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-included-in
  1189. Returns:
  1190. A JSON object with keys of 'branches' and 'tags'.
  1191. """
  1192. path = 'projects/%s/commits/%s/in' % (urllib.parse.quote(project,
  1193. ''), commit)
  1194. conn = CreateHttpConn(host, path, reqtype='GET')
  1195. return ReadHttpJsonResponse(conn, accept_statuses=[200])
  1196. def IsCodeOwnersEnabledOnHost(host):
  1197. """Check if the code-owners plugin is enabled for the host."""
  1198. path = 'config/server/capabilities'
  1199. capabilities = ReadHttpJsonResponse(CreateHttpConn(host, path))
  1200. return 'code-owners-checkCodeOwner' in capabilities
  1201. def IsCodeOwnersEnabledOnRepo(host, repo):
  1202. """Check if the code-owners plugin is enabled for the repo."""
  1203. repo = PercentEncodeForGitRef(repo)
  1204. path = '/projects/%s/code_owners.project_config' % repo
  1205. config = ReadHttpJsonResponse(CreateHttpConn(host, path))
  1206. return not config['status'].get('disabled', False)
  1207. def GetOwnersForFile(host,
  1208. project,
  1209. branch,
  1210. path,
  1211. limit=100,
  1212. resolve_all_users=True,
  1213. highest_score_only=False,
  1214. seed=None,
  1215. o_params=('DETAILS', )):
  1216. """Gets information about owners attached to a file."""
  1217. path = 'projects/%s/branches/%s/code_owners/%s' % (urllib.parse.quote(
  1218. project, ''), urllib.parse.quote(branch,
  1219. ''), urllib.parse.quote(path, ''))
  1220. q = ['resolve-all-users=%s' % json.dumps(resolve_all_users)]
  1221. if highest_score_only:
  1222. q.append('highest-score-only=%s' % json.dumps(highest_score_only))
  1223. if seed:
  1224. q.append('seed=%d' % seed)
  1225. if limit:
  1226. q.append('n=%d' % limit)
  1227. if o_params:
  1228. q.extend(['o=%s' % p for p in o_params])
  1229. if q:
  1230. path = '%s?%s' % (path, '&'.join(q))
  1231. return ReadHttpJsonResponse(CreateHttpConn(host, path))
  1232. def GetReviewers(host, change):
  1233. """Gets information about all reviewers attached to a change."""
  1234. path = 'changes/%s/reviewers' % change
  1235. return ReadHttpJsonResponse(CreateHttpConn(host, path))
  1236. def GetReview(host, change, revision):
  1237. """Gets review information about a specific revision of a change."""
  1238. path = 'changes/%s/revisions/%s/review' % (change, revision)
  1239. return ReadHttpJsonResponse(CreateHttpConn(host, path))
  1240. def AddReviewers(host,
  1241. change,
  1242. reviewers=None,
  1243. ccs=None,
  1244. notify=True,
  1245. accept_statuses: Container[int] = frozenset([200, 400, 422])):
  1246. """Add reviewers to a change."""
  1247. if not reviewers and not ccs:
  1248. return None
  1249. if not change:
  1250. return None
  1251. reviewers = frozenset(reviewers or [])
  1252. ccs = frozenset(ccs or [])
  1253. path = 'changes/%s/revisions/current/review' % change
  1254. body = {
  1255. 'drafts': 'KEEP',
  1256. 'reviewers': [],
  1257. 'notify': 'ALL' if notify else 'NONE',
  1258. }
  1259. for r in sorted(reviewers | ccs):
  1260. state = 'REVIEWER' if r in reviewers else 'CC'
  1261. body['reviewers'].append({
  1262. 'reviewer': r,
  1263. 'state': state,
  1264. 'notify': 'NONE', # We handled `notify` argument above.
  1265. })
  1266. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1267. # Gerrit will return 400 if one or more of the requested reviewers are
  1268. # unprocessable. We read the response object to see which were rejected,
  1269. # warn about them, and retry with the remainder.
  1270. resp = ReadHttpJsonResponse(conn, accept_statuses=accept_statuses)
  1271. errored = set()
  1272. for result in resp.get('reviewers', {}).values():
  1273. r = result.get('input')
  1274. state = 'REVIEWER' if r in reviewers else 'CC'
  1275. if result.get('error'):
  1276. errored.add(r)
  1277. LOGGER.warning('Note: "%s" not added as a %s' % (r, state.lower()))
  1278. if errored:
  1279. # Try again, adding only those that didn't fail, and only accepting 200.
  1280. AddReviewers(host,
  1281. change,
  1282. reviewers=(reviewers - errored),
  1283. ccs=(ccs - errored),
  1284. notify=notify,
  1285. accept_statuses=[200])
  1286. def SetReview(host, change, msg=None, labels=None, notify=None, ready=None):
  1287. """Sets labels and/or adds a message to a code review."""
  1288. if not msg and not labels:
  1289. return
  1290. path = 'changes/%s/revisions/current/review' % change
  1291. body: Dict[str, Any] = {'drafts': 'KEEP'}
  1292. if msg:
  1293. body['message'] = msg
  1294. if labels:
  1295. body['labels'] = labels
  1296. if notify is not None:
  1297. body['notify'] = 'ALL' if notify else 'NONE'
  1298. if ready:
  1299. body['ready'] = True
  1300. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1301. response = ReadHttpJsonResponse(conn)
  1302. if labels:
  1303. for key, val in labels.items():
  1304. if ('labels' not in response or key not in response['labels']
  1305. or int(response['labels'][key] != int(val))):
  1306. raise GerritError(
  1307. 200,
  1308. 'Unable to set "%s" label on change %s.' % (key, change))
  1309. return response
  1310. def ResetReviewLabels(host,
  1311. change,
  1312. label,
  1313. value='0',
  1314. message=None,
  1315. notify=None):
  1316. """Resets the value of a given label for all reviewers on a change."""
  1317. # This is tricky, because we want to work on the "current revision", but
  1318. # there's always the risk that "current revision" will change in between
  1319. # API calls. So, we check "current revision" at the beginning and end; if
  1320. # it has changed, raise an exception.
  1321. jmsg = GetChangeCurrentRevision(host, change)
  1322. if not jmsg:
  1323. raise GerritError(
  1324. 200, 'Could not get review information for change "%s"' % change)
  1325. value = str(value)
  1326. revision = jmsg[0]['current_revision']
  1327. path = 'changes/%s/revisions/%s/review' % (change, revision)
  1328. message = message or ('%s label set to %s programmatically.' %
  1329. (label, value))
  1330. jmsg = GetReview(host, change, revision)
  1331. if not jmsg:
  1332. raise GerritError(
  1333. 200, 'Could not get review information for revision %s '
  1334. 'of change %s' % (revision, change))
  1335. for review in jmsg.get('labels', {}).get(label, {}).get('all', []):
  1336. if str(review.get('value', value)) != value:
  1337. body = {
  1338. 'drafts': 'KEEP',
  1339. 'message': message,
  1340. 'labels': {
  1341. label: value
  1342. },
  1343. 'on_behalf_of': review['_account_id'],
  1344. }
  1345. if notify:
  1346. body['notify'] = notify
  1347. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1348. response = ReadHttpJsonResponse(conn)
  1349. if str(response['labels'][label]) != value:
  1350. username = review.get('email', jmsg.get('name', ''))
  1351. raise GerritError(
  1352. 200, 'Unable to set %s label for user "%s"'
  1353. ' on change %s.' % (label, username, change))
  1354. jmsg = GetChangeCurrentRevision(host, change)
  1355. if not jmsg:
  1356. raise GerritError(
  1357. 200, 'Could not get review information for change "%s"' % change)
  1358. if jmsg[0]['current_revision'] != revision:
  1359. raise GerritError(
  1360. 200, 'While resetting labels on change "%s", '
  1361. 'a new patchset was uploaded.' % change)
  1362. def CreateChange(host, project, branch='main', subject='', params=()):
  1363. """
  1364. Creates a new change.
  1365. Args:
  1366. params: A list of additional ChangeInput specifiers, as documented here:
  1367. (e.g. ('is_private', 'true') to mark the change private.
  1368. https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#change-input
  1369. Returns:
  1370. ChangeInfo for the new change.
  1371. """
  1372. path = 'changes/'
  1373. body = {'project': project, 'branch': branch, 'subject': subject}
  1374. body.update(dict(params))
  1375. for key in 'project', 'branch', 'subject':
  1376. if not body[key]:
  1377. raise GerritError(200, '%s is required' % key.title())
  1378. conn = CreateHttpConn(host, path, reqtype='POST', body=body)
  1379. return ReadHttpJsonResponse(conn, accept_statuses=[201])
  1380. def CreateGerritBranch(host, project, branch, commit):
  1381. """Creates a new branch from given project and commit
  1382. https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-branch
  1383. Returns:
  1384. A JSON object with 'ref' key.
  1385. """
  1386. path = 'projects/%s/branches/%s' % (project, branch)
  1387. body = {'revision': commit}
  1388. conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
  1389. response = ReadHttpJsonResponse(conn, accept_statuses=[201, 409])
  1390. if response:
  1391. return response
  1392. raise GerritError(200, 'Unable to create gerrit branch')
  1393. def CreateGerritTag(host, project, tag, commit):
  1394. """Creates a new tag at the given commit.
  1395. https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-tag
  1396. Returns:
  1397. A JSON object with 'ref' key.
  1398. """
  1399. path = 'projects/%s/tags/%s' % (project, tag)
  1400. body = {'revision': commit}
  1401. conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
  1402. response = ReadHttpJsonResponse(conn, accept_statuses=[201])
  1403. if response:
  1404. return response
  1405. raise GerritError(200, 'Unable to create gerrit tag')
  1406. def GetHead(host, project):
  1407. """Retrieves current HEAD of Gerrit project
  1408. https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-head
  1409. Returns:
  1410. A JSON object with 'ref' key.
  1411. """
  1412. path = 'projects/%s/HEAD' % (project)
  1413. conn = CreateHttpConn(host, path, reqtype='GET')
  1414. response = ReadHttpJsonResponse(conn, accept_statuses=[200])
  1415. if response:
  1416. return response
  1417. raise GerritError(200, 'Unable to update gerrit HEAD')
  1418. def UpdateHead(host, project, branch):
  1419. """Updates Gerrit HEAD to point to branch
  1420. https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#set-head
  1421. Returns:
  1422. A JSON object with 'ref' key.
  1423. """
  1424. path = 'projects/%s/HEAD' % (project)
  1425. body = {'ref': branch}
  1426. conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
  1427. response = ReadHttpJsonResponse(conn, accept_statuses=[200])
  1428. if response:
  1429. return response
  1430. raise GerritError(200, 'Unable to update gerrit HEAD')
  1431. def GetGerritBranch(host, project, branch):
  1432. """Gets a branch info from given project and branch name.
  1433. See:
  1434. https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-branch
  1435. Returns:
  1436. A JSON object with 'revision' key if the branch exists, otherwise None.
  1437. """
  1438. path = 'projects/%s/branches/%s' % (project, branch)
  1439. conn = CreateHttpConn(host, path, reqtype='GET')
  1440. return ReadHttpJsonResponse(conn, accept_statuses=[200, 404])
  1441. def GetProjectHead(host, project):
  1442. conn = CreateHttpConn(host,
  1443. '/projects/%s/HEAD' % urllib.parse.quote(project, ''))
  1444. return ReadHttpJsonResponse(conn, accept_statuses=[200])
  1445. def GetAccountDetails(host, account_id='self'):
  1446. """Returns details of the account.
  1447. If account_id is not given, uses magic value 'self' which corresponds to
  1448. whichever account user is authenticating as.
  1449. Documentation:
  1450. https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-account
  1451. Returns None if account is not found (i.e., Gerrit returned 404).
  1452. """
  1453. conn = CreateHttpConn(host, '/accounts/%s' % account_id)
  1454. return ReadHttpJsonResponse(conn, accept_statuses=[200, 404])
  1455. class EmailRecord(TypedDict):
  1456. email: str
  1457. preferred: bool # This should be NotRequired[bool] in 3.11+
  1458. def GetAccountEmails(host,
  1459. account_id='self',
  1460. *,
  1461. authenticator: Optional[_Authenticator] = None
  1462. ) -> Optional[List[EmailRecord]]:
  1463. """Returns all emails for this account, and an indication of which of these
  1464. is preferred.
  1465. If account_id is not given, uses magic value 'self' which corresponds to
  1466. whichever account user is authenticating as.
  1467. Requires Modify Account permission to view emails other than 'self'.
  1468. Documentation:
  1469. https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#list-account-emails
  1470. Returns None if account is not found (i.e. Gerrit returned 404).
  1471. """
  1472. conn = CreateHttpConn(host,
  1473. '/accounts/%s/emails' % account_id,
  1474. authenticator=authenticator)
  1475. resp = ReadHttpJsonResponse(conn, accept_statuses=[200, 404])
  1476. if resp is None:
  1477. return None
  1478. return cast(List[EmailRecord], resp)
  1479. def ValidAccounts(host, accounts, max_threads=10):
  1480. """Returns a mapping from valid account to its details.
  1481. Invalid accounts, either not existing or without unique match,
  1482. are not present as returned dictionary keys.
  1483. """
  1484. assert not isinstance(accounts, str), type(accounts)
  1485. accounts = list(set(accounts))
  1486. if not accounts:
  1487. return {}
  1488. def get_one(account):
  1489. try:
  1490. return account, GetAccountDetails(host, account)
  1491. except GerritError:
  1492. return None, None
  1493. valid = {}
  1494. with contextlib.closing(ThreadPool(min(max_threads,
  1495. len(accounts)))) as pool:
  1496. for account, details in pool.map(get_one, accounts):
  1497. if account and details:
  1498. valid[account] = details
  1499. return valid
  1500. def PercentEncodeForGitRef(original):
  1501. """Applies percent-encoding for strings sent to Gerrit via git ref metadata.
  1502. The encoding used is based on but stricter than URL encoding (Section 2.1 of
  1503. RFC 3986). The only non-escaped characters are alphanumerics, and 'SPACE'
  1504. (U+0020) can be represented as 'LOW LINE' (U+005F) or 'PLUS SIGN' (U+002B).
  1505. For more information, see the Gerrit docs here:
  1506. https://gerrit-review.googlesource.com/Documentation/user-upload.html#message
  1507. """
  1508. safe = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '
  1509. encoded = ''.join(c if c in safe else '%%%02X' % ord(c) for c in original)
  1510. # Spaces are not allowed in git refs; gerrit will interpret either '_' or
  1511. # '+' (or '%20') as space. Use '_' since that has been supported the
  1512. # longest.
  1513. return encoded.replace(' ', '_')
  1514. @contextlib.contextmanager
  1515. def tempdir():
  1516. tdir = None
  1517. try:
  1518. tdir = tempfile.mkdtemp(suffix='gerrit_util')
  1519. yield tdir
  1520. finally:
  1521. if tdir:
  1522. gclient_utils.rmtree(tdir)
  1523. def ChangeIdentifier(project, change_number):
  1524. """Returns change identifier "project~number" suitable for |change| arg of
  1525. this module API.
  1526. Such format is allows for more efficient Gerrit routing of HTTP requests,
  1527. comparing to specifying just change_number.
  1528. """
  1529. assert int(change_number)
  1530. return '%s~%s' % (urllib.parse.quote(project, ''), change_number)