git_cache.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  1. #!/usr/bin/env python3
  2. # Copyright 2014 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """A git command for managing a local cache of git repositories."""
  6. from __future__ import print_function
  7. import contextlib
  8. import errno
  9. import logging
  10. import optparse
  11. import os
  12. import re
  13. import subprocess
  14. import sys
  15. import tempfile
  16. import threading
  17. import time
  18. try:
  19. import urlparse
  20. except ImportError: # For Py3 compatibility
  21. import urllib.parse as urlparse
  22. from download_from_google_storage import Gsutil
  23. import gclient_utils
  24. import lockfile
  25. import metrics
  26. import subcommand
  27. # Analogous to gc.autopacklimit git config.
  28. GC_AUTOPACKLIMIT = 50
  29. GIT_CACHE_CORRUPT_MESSAGE = 'WARNING: The Git cache is corrupt.'
  30. # gsutil creates many processes and threads. Creating too many gsutil cp
  31. # processes may result in running out of resources, and may perform worse due to
  32. # contextr switching. This limits how many concurrent gsutil cp processes
  33. # git_cache runs.
  34. GSUTIL_CP_SEMAPHORE = threading.Semaphore(2)
  35. try:
  36. # pylint: disable=undefined-variable
  37. WinErr = WindowsError
  38. except NameError:
  39. class WinErr(Exception):
  40. pass
  41. class ClobberNeeded(Exception):
  42. pass
  43. def exponential_backoff_retry(fn, excs=(Exception,), name=None, count=10,
  44. sleep_time=0.25, printerr=None):
  45. """Executes |fn| up to |count| times, backing off exponentially.
  46. Args:
  47. fn (callable): The function to execute. If this raises a handled
  48. exception, the function will retry with exponential backoff.
  49. excs (tuple): A tuple of Exception types to handle. If one of these is
  50. raised by |fn|, a retry will be attempted. If |fn| raises an Exception
  51. that is not in this list, it will immediately pass through. If |excs|
  52. is empty, the Exception base class will be used.
  53. name (str): Optional operation name to print in the retry string.
  54. count (int): The number of times to try before allowing the exception to
  55. pass through.
  56. sleep_time (float): The initial number of seconds to sleep in between
  57. retries. This will be doubled each retry.
  58. printerr (callable): Function that will be called with the error string upon
  59. failures. If None, |logging.warning| will be used.
  60. Returns: The return value of the successful fn.
  61. """
  62. printerr = printerr or logging.warning
  63. for i in range(count):
  64. try:
  65. return fn()
  66. except excs as e:
  67. if (i+1) >= count:
  68. raise
  69. printerr('Retrying %s in %.2f second(s) (%d / %d attempts): %s' % (
  70. (name or 'operation'), sleep_time, (i+1), count, e))
  71. time.sleep(sleep_time)
  72. sleep_time *= 2
  73. class Mirror(object):
  74. git_exe = 'git.bat' if sys.platform.startswith('win') else 'git'
  75. gsutil_exe = os.path.join(
  76. os.path.dirname(os.path.abspath(__file__)), 'gsutil.py')
  77. cachepath_lock = threading.Lock()
  78. UNSET_CACHEPATH = object()
  79. # Used for tests
  80. _GIT_CONFIG_LOCATION = []
  81. @staticmethod
  82. def parse_fetch_spec(spec):
  83. """Parses and canonicalizes a fetch spec.
  84. Returns (fetchspec, value_regex), where value_regex can be used
  85. with 'git config --replace-all'.
  86. """
  87. parts = spec.split(':', 1)
  88. src = parts[0].lstrip('+').rstrip('/')
  89. if not src.startswith('refs/'):
  90. src = 'refs/heads/%s' % src
  91. dest = parts[1].rstrip('/') if len(parts) > 1 else src
  92. regex = r'\+%s:.*' % src.replace('*', r'\*')
  93. return ('+%s:%s' % (src, dest), regex)
  94. def __init__(self, url, refs=None, commits=None, print_func=None):
  95. self.url = url
  96. self.fetch_specs = {self.parse_fetch_spec(ref) for ref in (refs or [])}
  97. self.fetch_commits = set(commits or [])
  98. self.basedir = self.UrlToCacheDir(url)
  99. self.mirror_path = os.path.join(self.GetCachePath(), self.basedir)
  100. if print_func:
  101. self.print = self.print_without_file
  102. self.print_func = print_func
  103. else:
  104. self.print = print
  105. def print_without_file(self, message, **_kwargs):
  106. self.print_func(message)
  107. @contextlib.contextmanager
  108. def print_duration_of(self, what):
  109. start = time.time()
  110. try:
  111. yield
  112. finally:
  113. self.print('%s took %.1f minutes' % (what, (time.time() - start) / 60.0))
  114. @property
  115. def bootstrap_bucket(self):
  116. b = os.getenv('OVERRIDE_BOOTSTRAP_BUCKET')
  117. if b:
  118. return b
  119. u = urlparse.urlparse(self.url)
  120. if u.netloc == 'chromium.googlesource.com':
  121. return 'chromium-git-cache'
  122. # Not recognized.
  123. return None
  124. @property
  125. def _gs_path(self):
  126. return 'gs://%s/v2/%s' % (self.bootstrap_bucket, self.basedir)
  127. @classmethod
  128. def FromPath(cls, path):
  129. return cls(cls.CacheDirToUrl(path))
  130. @staticmethod
  131. def UrlToCacheDir(url):
  132. """Convert a git url to a normalized form for the cache dir path."""
  133. if os.path.isdir(url):
  134. # Ignore the drive letter in Windows
  135. url = os.path.splitdrive(url)[1]
  136. return url.replace('-', '--').replace(os.sep, '-')
  137. parsed = urlparse.urlparse(url)
  138. norm_url = parsed.netloc + parsed.path
  139. if norm_url.endswith('.git'):
  140. norm_url = norm_url[:-len('.git')]
  141. # Use the same dir for authenticated URLs and unauthenticated URLs.
  142. norm_url = norm_url.replace('googlesource.com/a/', 'googlesource.com/')
  143. return norm_url.replace('-', '--').replace('/', '-').lower()
  144. @staticmethod
  145. def CacheDirToUrl(path):
  146. """Convert a cache dir path to its corresponding url."""
  147. netpath = re.sub(r'\b-\b', '/', os.path.basename(path)).replace('--', '-')
  148. return 'https://%s' % netpath
  149. @classmethod
  150. def SetCachePath(cls, cachepath):
  151. with cls.cachepath_lock:
  152. setattr(cls, 'cachepath', cachepath)
  153. @classmethod
  154. def GetCachePath(cls):
  155. with cls.cachepath_lock:
  156. if not hasattr(cls, 'cachepath'):
  157. try:
  158. cachepath = subprocess.check_output(
  159. [cls.git_exe, 'config'] +
  160. cls._GIT_CONFIG_LOCATION +
  161. ['cache.cachepath']).decode('utf-8', 'ignore').strip()
  162. except subprocess.CalledProcessError:
  163. cachepath = os.environ.get('GIT_CACHE_PATH', cls.UNSET_CACHEPATH)
  164. setattr(cls, 'cachepath', cachepath)
  165. ret = getattr(cls, 'cachepath')
  166. if ret is cls.UNSET_CACHEPATH:
  167. raise RuntimeError('No cache.cachepath git configuration or '
  168. '$GIT_CACHE_PATH is set.')
  169. return ret
  170. @staticmethod
  171. def _GetMostRecentCacheDirectory(ls_out_set):
  172. ready_file_pattern = re.compile(r'.*/(\d+).ready$')
  173. ready_dirs = []
  174. for name in ls_out_set:
  175. m = ready_file_pattern.match(name)
  176. # Given <path>/<number>.ready,
  177. # we are interested in <path>/<number> directory
  178. if m and (name[:-len('.ready')] + '/') in ls_out_set:
  179. ready_dirs.append((int(m.group(1)), name[:-len('.ready')]))
  180. if not ready_dirs:
  181. return None
  182. return max(ready_dirs)[1]
  183. def Rename(self, src, dst):
  184. # This is somehow racy on Windows.
  185. # Catching OSError because WindowsError isn't portable and
  186. # pylint complains.
  187. exponential_backoff_retry(
  188. lambda: os.rename(src, dst),
  189. excs=(OSError,),
  190. name='rename [%s] => [%s]' % (src, dst),
  191. printerr=self.print)
  192. def RunGit(self, cmd, print_stdout=True, **kwargs):
  193. """Run git in a subprocess."""
  194. cwd = kwargs.setdefault('cwd', self.mirror_path)
  195. kwargs.setdefault('print_stdout', False)
  196. if print_stdout:
  197. kwargs.setdefault('filter_fn', self.print)
  198. env = kwargs.get('env') or kwargs.setdefault('env', os.environ.copy())
  199. env.setdefault('GIT_ASKPASS', 'true')
  200. env.setdefault('SSH_ASKPASS', 'true')
  201. self.print('running "git %s" in "%s"' % (' '.join(cmd), cwd))
  202. gclient_utils.CheckCallAndFilter([self.git_exe] + cmd, **kwargs)
  203. def config(self, cwd=None, reset_fetch_config=False):
  204. if cwd is None:
  205. cwd = self.mirror_path
  206. if reset_fetch_config:
  207. try:
  208. self.RunGit(['config', '--unset-all', 'remote.origin.fetch'], cwd=cwd)
  209. except subprocess.CalledProcessError as e:
  210. # If exit code was 5, it means we attempted to unset a config that
  211. # didn't exist. Ignore it.
  212. if e.returncode != 5:
  213. raise
  214. # Don't run git-gc in a daemon. Bad things can happen if it gets killed.
  215. try:
  216. self.RunGit(['config', 'gc.autodetach', '0'], cwd=cwd)
  217. except subprocess.CalledProcessError:
  218. # Hard error, need to clobber.
  219. raise ClobberNeeded()
  220. # Don't combine pack files into one big pack file. It's really slow for
  221. # repositories, and there's no way to track progress and make sure it's
  222. # not stuck.
  223. if self.supported_project():
  224. self.RunGit(['config', 'gc.autopacklimit', '0'], cwd=cwd)
  225. # Allocate more RAM for cache-ing delta chains, for better performance
  226. # of "Resolving deltas".
  227. self.RunGit(['config', 'core.deltaBaseCacheLimit',
  228. gclient_utils.DefaultDeltaBaseCacheLimit()], cwd=cwd)
  229. self.RunGit(['config', 'remote.origin.url', self.url], cwd=cwd)
  230. self.RunGit(['config', '--replace-all', 'remote.origin.fetch',
  231. '+refs/heads/*:refs/heads/*', r'\+refs/heads/\*:.*'], cwd=cwd)
  232. for spec, value_regex in self.fetch_specs:
  233. self.RunGit(
  234. ['config', '--replace-all', 'remote.origin.fetch', spec, value_regex],
  235. cwd=cwd)
  236. def bootstrap_repo(self, directory):
  237. """Bootstrap the repo from Google Storage if possible.
  238. More apt-ly named bootstrap_repo_from_cloud_if_possible_else_do_nothing().
  239. """
  240. if not self.bootstrap_bucket:
  241. return False
  242. gsutil = Gsutil(self.gsutil_exe, boto_path=None)
  243. # Get the most recent version of the directory.
  244. # This is determined from the most recent version of a .ready file.
  245. # The .ready file is only uploaded when an entire directory has been
  246. # uploaded to GS.
  247. _, ls_out, ls_err = gsutil.check_call('ls', self._gs_path)
  248. ls_out_set = set(ls_out.strip().splitlines())
  249. latest_dir = self._GetMostRecentCacheDirectory(ls_out_set)
  250. if not latest_dir:
  251. self.print('No bootstrap file for %s found in %s, stderr:\n %s' %
  252. (self.mirror_path, self.bootstrap_bucket,
  253. ' '.join((ls_err or '').splitlines(True))))
  254. return False
  255. try:
  256. # create new temporary directory locally
  257. tempdir = tempfile.mkdtemp(prefix='_cache_tmp', dir=self.GetCachePath())
  258. self.RunGit(['init', '--bare'], cwd=tempdir)
  259. self.print('Downloading files in %s/* into %s.' %
  260. (latest_dir, tempdir))
  261. with self.print_duration_of('download'):
  262. with GSUTIL_CP_SEMAPHORE:
  263. code = gsutil.call('-m', 'cp', '-r', latest_dir + "/*",
  264. tempdir)
  265. if code:
  266. return False
  267. # Set HEAD to main.
  268. self.RunGit(['symbolic-ref', 'HEAD', 'refs/heads/main'], cwd=tempdir)
  269. # A quick validation that all references are valid.
  270. self.RunGit(['for-each-ref'], print_stdout=False, cwd=tempdir)
  271. except Exception as e:
  272. self.print('Encountered error: %s' % str(e), file=sys.stderr)
  273. gclient_utils.rmtree(tempdir)
  274. return False
  275. # delete the old directory
  276. if os.path.exists(directory):
  277. gclient_utils.rmtree(directory)
  278. self.Rename(tempdir, directory)
  279. return True
  280. def contains_revision(self, revision):
  281. if not self.exists():
  282. return False
  283. if sys.platform.startswith('win'):
  284. # Windows .bat scripts use ^ as escape sequence, which means we have to
  285. # escape it with itself for every .bat invocation.
  286. needle = '%s^^^^{commit}' % revision
  287. else:
  288. needle = '%s^{commit}' % revision
  289. try:
  290. # cat-file exits with 0 on success, that is git object of given hash was
  291. # found.
  292. self.RunGit(['cat-file', '-e', needle])
  293. return True
  294. except subprocess.CalledProcessError:
  295. self.print('Commit with hash "%s" not found' % revision, file=sys.stderr)
  296. return False
  297. def exists(self):
  298. return os.path.isfile(os.path.join(self.mirror_path, 'config'))
  299. def supported_project(self):
  300. """Returns true if this repo is known to have a bootstrap zip file."""
  301. u = urlparse.urlparse(self.url)
  302. return u.netloc in [
  303. 'chromium.googlesource.com',
  304. 'chrome-internal.googlesource.com']
  305. def _preserve_fetchspec(self):
  306. """Read and preserve remote.origin.fetch from an existing mirror.
  307. This modifies self.fetch_specs.
  308. """
  309. if not self.exists():
  310. return
  311. try:
  312. config_fetchspecs = subprocess.check_output(
  313. [self.git_exe, 'config', '--get-all', 'remote.origin.fetch'],
  314. cwd=self.mirror_path).decode('utf-8', 'ignore')
  315. for fetchspec in config_fetchspecs.splitlines():
  316. self.fetch_specs.add(self.parse_fetch_spec(fetchspec))
  317. except subprocess.CalledProcessError:
  318. logging.warning(
  319. 'Tried and failed to preserve remote.origin.fetch from the '
  320. 'existing cache directory. You may need to manually edit '
  321. '%s and "git cache fetch" again.' %
  322. os.path.join(self.mirror_path, 'config'))
  323. def _ensure_bootstrapped(
  324. self, depth, bootstrap, reset_fetch_config, force=False):
  325. pack_dir = os.path.join(self.mirror_path, 'objects', 'pack')
  326. pack_files = []
  327. if os.path.isdir(pack_dir):
  328. pack_files = [f for f in os.listdir(pack_dir) if f.endswith('.pack')]
  329. self.print('%s has %d .pack files, re-bootstrapping if >%d or ==0' %
  330. (self.mirror_path, len(pack_files), GC_AUTOPACKLIMIT))
  331. # master->main branch migration left the cache in some builders to have its
  332. # HEAD still pointing to refs/heads/master. This causes bot_update to fail.
  333. # If in this state, delete the cache and force bootstrap.
  334. try:
  335. with open(os.path.join(self.mirror_path, 'HEAD')) as f:
  336. head_ref = f.read()
  337. except FileNotFoundError:
  338. head_ref = ''
  339. # Check only when HEAD points to master.
  340. if 'master' in head_ref:
  341. # Some repos could still have master so verify if the ref exists first.
  342. show_ref_master_cmd = subprocess.run(
  343. [Mirror.git_exe, 'show-ref', '--verify', 'refs/heads/master'],
  344. cwd=self.mirror_path)
  345. if show_ref_master_cmd.returncode != 0:
  346. # Remove mirror
  347. gclient_utils.rmtree(self.mirror_path)
  348. # force bootstrap
  349. force = True
  350. should_bootstrap = (force or
  351. not self.exists() or
  352. len(pack_files) > GC_AUTOPACKLIMIT or
  353. len(pack_files) == 0)
  354. if not should_bootstrap:
  355. if depth and os.path.exists(os.path.join(self.mirror_path, 'shallow')):
  356. logging.warning(
  357. 'Shallow fetch requested, but repo cache already exists.')
  358. return
  359. if not self.exists():
  360. if os.path.exists(self.mirror_path):
  361. # If the mirror path exists but self.exists() returns false, we're
  362. # in an unexpected state. Nuke the previous mirror directory and
  363. # start fresh.
  364. gclient_utils.rmtree(self.mirror_path)
  365. os.mkdir(self.mirror_path)
  366. elif not reset_fetch_config:
  367. # Re-bootstrapping an existing mirror; preserve existing fetch spec.
  368. self._preserve_fetchspec()
  369. bootstrapped = (not depth and bootstrap and
  370. self.bootstrap_repo(self.mirror_path))
  371. if not bootstrapped:
  372. if not self.exists() or not self.supported_project():
  373. # Bootstrap failed due to:
  374. # 1. No previous cache.
  375. # 2. Project doesn't have a bootstrap folder.
  376. # Start with a bare git dir.
  377. self.RunGit(['init', '--bare'], cwd=self.mirror_path)
  378. # Set appropriate symbolic-ref
  379. remote_info = exponential_backoff_retry(
  380. lambda: subprocess.check_output(
  381. [self.git_exe, 'remote', 'show', self.url],
  382. cwd=self.mirror_path).decode('utf-8', 'ignore').strip()
  383. )
  384. default_branch_regexp = re.compile(r'HEAD branch: (.*)$')
  385. m = default_branch_regexp.search(remote_info, re.MULTILINE)
  386. if m:
  387. self.RunGit(['symbolic-ref', 'HEAD', 'refs/heads/' + m.groups()[0]],
  388. cwd=self.mirror_path)
  389. else:
  390. # Bootstrap failed, previous cache exists; warn and continue.
  391. logging.warning(
  392. 'Git cache has a lot of pack files (%d). Tried to re-bootstrap '
  393. 'but failed. Continuing with non-optimized repository.' %
  394. len(pack_files))
  395. def _fetch(self,
  396. rundir,
  397. verbose,
  398. depth,
  399. no_fetch_tags,
  400. reset_fetch_config,
  401. prune=True):
  402. self.config(rundir, reset_fetch_config)
  403. fetch_cmd = ['fetch']
  404. if verbose:
  405. fetch_cmd.extend(['-v', '--progress'])
  406. if depth:
  407. fetch_cmd.extend(['--depth', str(depth)])
  408. if no_fetch_tags:
  409. fetch_cmd.append('--no-tags')
  410. if prune:
  411. fetch_cmd.append('--prune')
  412. fetch_cmd.append('origin')
  413. fetch_specs = subprocess.check_output(
  414. [self.git_exe, 'config', '--get-all', 'remote.origin.fetch'],
  415. cwd=rundir).decode('utf-8', 'ignore').strip().splitlines()
  416. for spec in fetch_specs:
  417. try:
  418. self.print('Fetching %s' % spec)
  419. with self.print_duration_of('fetch %s' % spec):
  420. self.RunGit(fetch_cmd + [spec], cwd=rundir, retry=True)
  421. except subprocess.CalledProcessError:
  422. if spec == '+refs/heads/*:refs/heads/*':
  423. raise ClobberNeeded() # Corrupted cache.
  424. logging.warning('Fetch of %s failed' % spec)
  425. for commit in self.fetch_commits:
  426. self.print('Fetching %s' % commit)
  427. try:
  428. with self.print_duration_of('fetch %s' % commit):
  429. self.RunGit(['fetch', 'origin', commit], cwd=rundir, retry=True)
  430. except subprocess.CalledProcessError:
  431. logging.warning('Fetch of %s failed' % commit)
  432. def populate(self,
  433. depth=None,
  434. no_fetch_tags=False,
  435. shallow=False,
  436. bootstrap=False,
  437. verbose=False,
  438. lock_timeout=0,
  439. reset_fetch_config=False):
  440. assert self.GetCachePath()
  441. if shallow and not depth:
  442. depth = 10000
  443. gclient_utils.safe_makedirs(self.GetCachePath())
  444. with lockfile.lock(self.mirror_path, lock_timeout):
  445. try:
  446. self._ensure_bootstrapped(depth, bootstrap, reset_fetch_config)
  447. self._fetch(self.mirror_path, verbose, depth, no_fetch_tags,
  448. reset_fetch_config)
  449. except ClobberNeeded:
  450. # This is a major failure, we need to clean and force a bootstrap.
  451. gclient_utils.rmtree(self.mirror_path)
  452. self.print(GIT_CACHE_CORRUPT_MESSAGE)
  453. self._ensure_bootstrapped(depth,
  454. bootstrap,
  455. reset_fetch_config,
  456. force=True)
  457. self._fetch(self.mirror_path, verbose, depth, no_fetch_tags,
  458. reset_fetch_config)
  459. def update_bootstrap(self, prune=False, gc_aggressive=False):
  460. # NOTE: There have been cases where repos were being recursively uploaded
  461. # to google storage.
  462. # E.g. `<host_url>-<repo>/<gen_number>/<host_url>-<repo>/` in GS and
  463. # <host_url>-<repo>/<host_url>-<repo>/ on the bot.
  464. # Check for recursed files on the bot here and remove them if found
  465. # before we upload to GS.
  466. # See crbug.com/1370443; keep this check until root cause is found.
  467. recursed_dir = os.path.join(self.mirror_path,
  468. self.mirror_path.split(os.path.sep)[-1])
  469. if os.path.exists(recursed_dir):
  470. self.print('Deleting unexpected directory: %s' % recursed_dir)
  471. gclient_utils.rmtree(recursed_dir)
  472. # The folder is <git number>
  473. gen_number = subprocess.check_output([self.git_exe, 'number'],
  474. cwd=self.mirror_path).decode(
  475. 'utf-8', 'ignore').strip()
  476. gsutil = Gsutil(path=self.gsutil_exe, boto_path=None)
  477. dest_prefix = '%s/%s' % (self._gs_path, gen_number)
  478. # ls_out lists contents in the format: gs://blah/blah/123...
  479. self.print('running "gsutil ls %s":' % self._gs_path)
  480. ls_code, ls_out, ls_error = gsutil.check_call_with_retries(
  481. 'ls', self._gs_path)
  482. if ls_code != 0:
  483. self.print(ls_error)
  484. else:
  485. self.print(ls_out)
  486. # Check to see if folder already exists in gs
  487. ls_out_set = set(ls_out.strip().splitlines())
  488. if (dest_prefix + '/' in ls_out_set and
  489. dest_prefix + '.ready' in ls_out_set):
  490. print('Cache %s already exists.' % dest_prefix)
  491. return
  492. # Reduce the number of individual files to download & write on disk.
  493. self.RunGit(['pack-refs', '--all'])
  494. # Run Garbage Collect to compress packfile.
  495. gc_args = ['gc', '--prune=all']
  496. if gc_aggressive:
  497. # The default "gc --aggressive" is often too aggressive for some machines,
  498. # since it attempts to create as many threads as there are CPU cores,
  499. # while not limiting per-thread memory usage, which puts too much pressure
  500. # on RAM on high-core machines, causing them to thrash. Using lower-level
  501. # commands gives more control over those settings.
  502. # This might not be strictly necessary, but it's fast and is normally run
  503. # by 'gc --aggressive', so it shouldn't hurt.
  504. self.RunGit(['reflog', 'expire', '--all'])
  505. # These are the default repack settings for 'gc --aggressive'.
  506. gc_args = ['repack', '-d', '-l', '-f', '--depth=50', '--window=250', '-A',
  507. '--unpack-unreachable=all']
  508. # A 1G memory limit seems to provide comparable pack results as the
  509. # default, even for our largest repos, while preventing runaway memory (at
  510. # least on current Chromium builders which have about 4G RAM per core).
  511. gc_args.append('--window-memory=1g')
  512. # NOTE: It might also be possible to avoid thrashing with a larger window
  513. # (e.g. "--window-memory=2g") by limiting the number of threads created
  514. # (e.g. "--threads=[cores/2]"). Some limited testing didn't show much
  515. # difference in outcomes on our current repos, but it might be worth
  516. # trying if the repos grow much larger and the packs don't seem to be
  517. # getting compressed enough.
  518. self.RunGit(gc_args)
  519. self.print('running "gsutil -m rsync -r -d %s %s"' %
  520. (self.mirror_path, dest_prefix))
  521. gsutil.call('-m', 'rsync', '-r', '-d', self.mirror_path, dest_prefix)
  522. # Create .ready file and upload
  523. _, ready_file_name = tempfile.mkstemp(suffix='.ready')
  524. try:
  525. self.print('running "gsutil cp %s %s.ready"' %
  526. (ready_file_name, dest_prefix))
  527. gsutil.call('cp', ready_file_name, '%s.ready' % (dest_prefix))
  528. finally:
  529. os.remove(ready_file_name)
  530. # remove all other directory/.ready files in the same gs_path
  531. # except for the directory/.ready file previously created
  532. # which can be used for bootstrapping while the current one is
  533. # being uploaded
  534. if not prune:
  535. return
  536. prev_dest_prefix = self._GetMostRecentCacheDirectory(ls_out_set)
  537. if not prev_dest_prefix:
  538. return
  539. for path in ls_out_set:
  540. if path in (prev_dest_prefix + '/', prev_dest_prefix + '.ready'):
  541. continue
  542. if path.endswith('.ready'):
  543. gsutil.call('rm', path)
  544. continue
  545. gsutil.call('-m', 'rm', '-r', path)
  546. @staticmethod
  547. def DeleteTmpPackFiles(path):
  548. pack_dir = os.path.join(path, 'objects', 'pack')
  549. if not os.path.isdir(pack_dir):
  550. return
  551. pack_files = [f for f in os.listdir(pack_dir) if
  552. f.startswith('.tmp-') or f.startswith('tmp_pack_')]
  553. for f in pack_files:
  554. f = os.path.join(pack_dir, f)
  555. try:
  556. os.remove(f)
  557. logging.warning('Deleted stale temporary pack file %s' % f)
  558. except OSError:
  559. logging.warning('Unable to delete temporary pack file %s' % f)
  560. @subcommand.usage('[url of repo to check for caching]')
  561. @metrics.collector.collect_metrics('git cache exists')
  562. def CMDexists(parser, args):
  563. """Check to see if there already is a cache of the given repo."""
  564. _, args = parser.parse_args(args)
  565. if not len(args) == 1:
  566. parser.error('git cache exists only takes exactly one repo url.')
  567. url = args[0]
  568. mirror = Mirror(url)
  569. if mirror.exists():
  570. print(mirror.mirror_path)
  571. return 0
  572. return 1
  573. @subcommand.usage('[url of repo to create a bootstrap zip file]')
  574. @metrics.collector.collect_metrics('git cache update-bootstrap')
  575. def CMDupdate_bootstrap(parser, args):
  576. """Create and uploads a bootstrap tarball."""
  577. # Lets just assert we can't do this on Windows.
  578. if sys.platform.startswith('win'):
  579. print('Sorry, update bootstrap will not work on Windows.', file=sys.stderr)
  580. return 1
  581. parser.add_option('--skip-populate', action='store_true',
  582. help='Skips "populate" step if mirror already exists.')
  583. parser.add_option('--gc-aggressive', action='store_true',
  584. help='Run aggressive repacking of the repo.')
  585. parser.add_option('--prune', action='store_true',
  586. help='Prune all other cached bundles of the same repo.')
  587. populate_args = args[:]
  588. options, args = parser.parse_args(args)
  589. url = args[0]
  590. mirror = Mirror(url)
  591. if not options.skip_populate or not mirror.exists():
  592. CMDpopulate(parser, populate_args)
  593. else:
  594. print('Skipped populate step.')
  595. # Get the repo directory.
  596. _, args2 = parser.parse_args(args)
  597. url = args2[0]
  598. mirror = Mirror(url)
  599. mirror.update_bootstrap(options.prune, options.gc_aggressive)
  600. return 0
  601. @subcommand.usage('[url of repo to add to or update in cache]')
  602. @metrics.collector.collect_metrics('git cache populate')
  603. def CMDpopulate(parser, args):
  604. """Ensure that the cache has all up-to-date objects for the given repo."""
  605. parser.add_option('--depth', type='int',
  606. help='Only cache DEPTH commits of history')
  607. parser.add_option(
  608. '--no-fetch-tags',
  609. action='store_true',
  610. help=('Don\'t fetch tags from the server. This can speed up '
  611. 'fetch considerably when there are many tags.'))
  612. parser.add_option('--shallow', '-s', action='store_true',
  613. help='Only cache 10000 commits of history')
  614. parser.add_option('--ref', action='append',
  615. help='Specify additional refs to be fetched')
  616. parser.add_option('--commit', action='append',
  617. help='Specify additional commits to be fetched')
  618. parser.add_option('--no_bootstrap', '--no-bootstrap',
  619. action='store_true',
  620. help='Don\'t bootstrap from Google Storage')
  621. parser.add_option('--ignore_locks',
  622. '--ignore-locks',
  623. action='store_true',
  624. help='NOOP. This flag will be removed in the future.')
  625. parser.add_option('--break-locks',
  626. action='store_true',
  627. help='Break any existing lock instead of just ignoring it')
  628. parser.add_option('--reset-fetch-config', action='store_true', default=False,
  629. help='Reset the fetch config before populating the cache.')
  630. options, args = parser.parse_args(args)
  631. if not len(args) == 1:
  632. parser.error('git cache populate only takes exactly one repo url.')
  633. if options.ignore_locks:
  634. print('ignore_locks is no longer used. Please remove its usage.')
  635. if options.break_locks:
  636. print('break_locks is no longer used. Please remove its usage.')
  637. url = args[0]
  638. mirror = Mirror(url, refs=options.ref, commits=options.commit)
  639. kwargs = {
  640. 'no_fetch_tags': options.no_fetch_tags,
  641. 'verbose': options.verbose,
  642. 'shallow': options.shallow,
  643. 'bootstrap': not options.no_bootstrap,
  644. 'lock_timeout': options.timeout,
  645. 'reset_fetch_config': options.reset_fetch_config,
  646. }
  647. if options.depth:
  648. kwargs['depth'] = options.depth
  649. mirror.populate(**kwargs)
  650. @subcommand.usage('Fetch new commits into cache and current checkout')
  651. @metrics.collector.collect_metrics('git cache fetch')
  652. def CMDfetch(parser, args):
  653. """Update mirror, and fetch in cwd."""
  654. parser.add_option('--all', action='store_true', help='Fetch all remotes')
  655. parser.add_option('--no_bootstrap', '--no-bootstrap',
  656. action='store_true',
  657. help='Don\'t (re)bootstrap from Google Storage')
  658. parser.add_option(
  659. '--no-fetch-tags',
  660. action='store_true',
  661. help=('Don\'t fetch tags from the server. This can speed up '
  662. 'fetch considerably when there are many tags.'))
  663. options, args = parser.parse_args(args)
  664. # Figure out which remotes to fetch. This mimics the behavior of regular
  665. # 'git fetch'. Note that in the case of "stacked" or "pipelined" branches,
  666. # this will NOT try to traverse up the branching structure to find the
  667. # ultimate remote to update.
  668. remotes = []
  669. if options.all:
  670. assert not args, 'fatal: fetch --all does not take a repository argument'
  671. remotes = subprocess.check_output([Mirror.git_exe, 'remote'])
  672. remotes = remotes.decode('utf-8', 'ignore').splitlines()
  673. elif args:
  674. remotes = args
  675. else:
  676. current_branch = subprocess.check_output(
  677. [Mirror.git_exe, 'rev-parse', '--abbrev-ref', 'HEAD'])
  678. current_branch = current_branch.decode('utf-8', 'ignore').strip()
  679. if current_branch != 'HEAD':
  680. upstream = subprocess.check_output(
  681. [Mirror.git_exe, 'config', 'branch.%s.remote' % current_branch])
  682. upstream = upstream.decode('utf-8', 'ignore').strip()
  683. if upstream and upstream != '.':
  684. remotes = [upstream]
  685. if not remotes:
  686. remotes = ['origin']
  687. cachepath = Mirror.GetCachePath()
  688. git_dir = os.path.abspath(subprocess.check_output(
  689. [Mirror.git_exe, 'rev-parse', '--git-dir']).decode('utf-8', 'ignore'))
  690. git_dir = os.path.abspath(git_dir)
  691. if git_dir.startswith(cachepath):
  692. mirror = Mirror.FromPath(git_dir)
  693. mirror.populate(
  694. bootstrap=not options.no_bootstrap,
  695. no_fetch_tags=options.no_fetch_tags,
  696. lock_timeout=options.timeout)
  697. return 0
  698. for remote in remotes:
  699. remote_url = subprocess.check_output(
  700. [Mirror.git_exe, 'config', 'remote.%s.url' % remote])
  701. remote_url = remote_url.decode('utf-8', 'ignore').strip()
  702. if remote_url.startswith(cachepath):
  703. mirror = Mirror.FromPath(remote_url)
  704. mirror.print = lambda *args: None
  705. print('Updating git cache...')
  706. mirror.populate(
  707. bootstrap=not options.no_bootstrap,
  708. no_fetch_tags=options.no_fetch_tags,
  709. lock_timeout=options.timeout)
  710. subprocess.check_call([Mirror.git_exe, 'fetch', remote])
  711. return 0
  712. @subcommand.usage('do not use - it is a noop.')
  713. @metrics.collector.collect_metrics('git cache unlock')
  714. def CMDunlock(parser, args):
  715. """This command does nothing."""
  716. print('This command does nothing and will be removed in the future.')
  717. class OptionParser(optparse.OptionParser):
  718. """Wrapper class for OptionParser to handle global options."""
  719. def __init__(self, *args, **kwargs):
  720. optparse.OptionParser.__init__(self, *args, prog='git cache', **kwargs)
  721. self.add_option('-c', '--cache-dir',
  722. help=(
  723. 'Path to the directory containing the caches. Normally '
  724. 'deduced from git config cache.cachepath or '
  725. '$GIT_CACHE_PATH.'))
  726. self.add_option('-v', '--verbose', action='count', default=1,
  727. help='Increase verbosity (can be passed multiple times)')
  728. self.add_option('-q', '--quiet', action='store_true',
  729. help='Suppress all extraneous output')
  730. self.add_option('--timeout', type='int', default=0,
  731. help='Timeout for acquiring cache lock, in seconds')
  732. def parse_args(self, args=None, values=None):
  733. # Create an optparse.Values object that will store only the actual passed
  734. # options, without the defaults.
  735. actual_options = optparse.Values()
  736. _, args = optparse.OptionParser.parse_args(self, args, actual_options)
  737. # Create an optparse.Values object with the default options.
  738. options = optparse.Values(self.get_default_values().__dict__)
  739. # Update it with the options passed by the user.
  740. options._update_careful(actual_options.__dict__)
  741. # Store the options passed by the user in an _actual_options attribute.
  742. # We store only the keys, and not the values, since the values can contain
  743. # arbitrary information, which might be PII.
  744. metrics.collector.add('arguments', list(actual_options.__dict__.keys()))
  745. if options.quiet:
  746. options.verbose = 0
  747. levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
  748. logging.basicConfig(level=levels[min(options.verbose, len(levels) - 1)])
  749. try:
  750. global_cache_dir = Mirror.GetCachePath()
  751. except RuntimeError:
  752. global_cache_dir = None
  753. if options.cache_dir:
  754. if global_cache_dir and (
  755. os.path.abspath(options.cache_dir) !=
  756. os.path.abspath(global_cache_dir)):
  757. logging.warning('Overriding globally-configured cache directory.')
  758. Mirror.SetCachePath(options.cache_dir)
  759. return options, args
  760. def main(argv):
  761. dispatcher = subcommand.CommandDispatcher(__name__)
  762. return dispatcher.execute(OptionParser(), argv)
  763. if __name__ == '__main__':
  764. try:
  765. with metrics.collector.print_notice_and_exit():
  766. sys.exit(main(sys.argv[1:]))
  767. except KeyboardInterrupt:
  768. sys.stderr.write('interrupted\n')
  769. sys.exit(1)