git_cache.py 37 KB

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