git_cache.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  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 Exception
  50. that is not in this list, it will immediately pass through. If |excs|
  51. 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 to
  54. 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 upon
  58. 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 bootstrap_repo_from_cloud_if_possible_else_do_nothing().
  245. """
  246. if not self.bootstrap_bucket:
  247. return False
  248. gsutil = Gsutil(self.gsutil_exe, boto_path=None)
  249. # Get the most recent version of the directory.
  250. # This is determined from the most recent version of a .ready file.
  251. # The .ready file is only uploaded when an entire directory has been
  252. # uploaded to GS.
  253. _, ls_out, ls_err = gsutil.check_call('ls', self._gs_path)
  254. ls_out_set = set(ls_out.strip().splitlines())
  255. latest_dir = self._GetMostRecentCacheDirectory(ls_out_set)
  256. if not latest_dir:
  257. self.print('No bootstrap file for %s found in %s, stderr:\n %s' %
  258. (self.mirror_path, self.bootstrap_bucket, ' '.join(
  259. (ls_err or '').splitlines(True))))
  260. return False
  261. try:
  262. # create new temporary directory locally
  263. tempdir = tempfile.mkdtemp(prefix='_cache_tmp',
  264. dir=self.GetCachePath())
  265. self.RunGit(['init', '-b', 'main', '--bare'], cwd=tempdir)
  266. self.print('Downloading files in %s/* into %s.' %
  267. (latest_dir, tempdir))
  268. with self.print_duration_of('download'):
  269. with GSUTIL_CP_SEMAPHORE:
  270. code = gsutil.call('-m', 'cp', '-r', latest_dir + "/*",
  271. tempdir)
  272. if code:
  273. return False
  274. # A quick validation that all references are valid.
  275. self.RunGit(['for-each-ref'], print_stdout=False, cwd=tempdir)
  276. except Exception as e:
  277. self.print('Encountered error: %s' % str(e), file=sys.stderr)
  278. gclient_utils.rmtree(tempdir)
  279. return False
  280. # delete the old directory
  281. if os.path.exists(directory):
  282. gclient_utils.rmtree(directory)
  283. self.Rename(tempdir, directory)
  284. return True
  285. def contains_revision(self, revision):
  286. if not self.exists():
  287. return False
  288. if sys.platform.startswith('win'):
  289. # Windows .bat scripts use ^ as escape sequence, which means we have
  290. # to escape it with itself for every .bat invocation.
  291. needle = '%s^^^^{commit}' % revision
  292. else:
  293. needle = '%s^{commit}' % revision
  294. try:
  295. # cat-file exits with 0 on success, that is git object of given hash
  296. # was found.
  297. self.RunGit(['cat-file', '-e', needle])
  298. return True
  299. except subprocess.CalledProcessError:
  300. self.print('Commit with hash "%s" not found' % revision,
  301. file=sys.stderr)
  302. return False
  303. def exists(self):
  304. return os.path.isfile(os.path.join(self.mirror_path, 'config'))
  305. def supported_project(self):
  306. """Returns true if this repo is known to have a bootstrap zip file."""
  307. u = urllib.parse.urlparse(self.url)
  308. return u.netloc in [
  309. 'chromium.googlesource.com', 'chrome-internal.googlesource.com'
  310. ]
  311. def _preserve_fetchspec(self):
  312. """Read and preserve remote.origin.fetch from an existing mirror.
  313. This modifies self.fetch_specs.
  314. """
  315. if not self.exists():
  316. return
  317. try:
  318. config_fetchspecs = subprocess.check_output(
  319. [self.git_exe, 'config', '--get-all', 'remote.origin.fetch'],
  320. cwd=self.mirror_path).decode('utf-8', 'ignore')
  321. for fetchspec in config_fetchspecs.splitlines():
  322. self.fetch_specs.add(self.parse_fetch_spec(fetchspec))
  323. except subprocess.CalledProcessError:
  324. logging.warning(
  325. 'Tried and failed to preserve remote.origin.fetch from the '
  326. 'existing cache directory. You may need to manually edit '
  327. '%s and "git cache fetch" again.' %
  328. os.path.join(self.mirror_path, 'config'))
  329. def _ensure_bootstrapped(self,
  330. depth,
  331. bootstrap,
  332. reset_fetch_config,
  333. force=False):
  334. pack_dir = os.path.join(self.mirror_path, 'objects', 'pack')
  335. pack_files = []
  336. if os.path.isdir(pack_dir):
  337. pack_files = [
  338. f for f in os.listdir(pack_dir) if f.endswith('.pack')
  339. ]
  340. self.print('%s has %d .pack files, re-bootstrapping if >%d or ==0' %
  341. (self.mirror_path, len(pack_files), GC_AUTOPACKLIMIT))
  342. # master->main branch migration left the cache in some builders to have
  343. # its HEAD still pointing to refs/heads/master. This causes bot_update
  344. # to fail. If in this state, delete the cache and force bootstrap.
  345. try:
  346. with open(os.path.join(self.mirror_path, 'HEAD')) as f:
  347. head_ref = f.read()
  348. except FileNotFoundError:
  349. head_ref = ''
  350. # Check only when HEAD points to master.
  351. if 'master' in head_ref:
  352. # Some repos could still have master so verify if the ref exists
  353. # first.
  354. show_ref_master_cmd = subprocess.run(
  355. [Mirror.git_exe, 'show-ref', '--verify', 'refs/heads/master'],
  356. cwd=self.mirror_path)
  357. if show_ref_master_cmd.returncode != 0:
  358. # Remove mirror
  359. gclient_utils.rmtree(self.mirror_path)
  360. # force bootstrap
  361. force = True
  362. should_bootstrap = (force or not self.exists()
  363. or len(pack_files) > GC_AUTOPACKLIMIT
  364. or len(pack_files) == 0)
  365. if not should_bootstrap:
  366. if depth and os.path.exists(
  367. os.path.join(self.mirror_path, 'shallow')):
  368. logging.warning(
  369. 'Shallow fetch requested, but repo cache already exists.')
  370. return
  371. if not self.exists():
  372. if os.path.exists(self.mirror_path):
  373. # If the mirror path exists but self.exists() returns false,
  374. # we're in an unexpected state. Nuke the previous mirror
  375. # directory and start fresh.
  376. gclient_utils.rmtree(self.mirror_path)
  377. os.mkdir(self.mirror_path)
  378. elif not reset_fetch_config:
  379. # Re-bootstrapping an existing mirror; preserve existing fetch spec.
  380. self._preserve_fetchspec()
  381. bootstrapped = (not depth and bootstrap
  382. and self.bootstrap_repo(self.mirror_path))
  383. if not bootstrapped:
  384. if not self.exists() or not self.supported_project():
  385. # Bootstrap failed due to:
  386. # 1. No previous cache.
  387. # 2. Project doesn't have a bootstrap folder.
  388. # Start with a bare git dir.
  389. self.RunGit(['init', '--bare'])
  390. # Set appropriate symbolic-ref
  391. remote_info = exponential_backoff_retry(
  392. lambda: subprocess.check_output(
  393. [
  394. self.git_exe, '--git-dir',
  395. os.path.abspath(self.mirror_path), 'remote', 'show',
  396. self.url
  397. ],
  398. cwd=self.mirror_path).decode('utf-8', 'ignore').strip())
  399. default_branch_regexp = re.compile(r'HEAD branch: (.*)$')
  400. m = default_branch_regexp.search(remote_info, re.MULTILINE)
  401. if m:
  402. self.RunGit(
  403. ['symbolic-ref', 'HEAD', 'refs/heads/' + m.groups()[0]])
  404. else:
  405. # Bootstrap failed, previous cache exists; warn and continue.
  406. logging.warning(
  407. 'Git cache has a lot of pack files (%d). Tried to '
  408. 're-bootstrap but failed. Continuing with non-optimized '
  409. 'repository.' % len(pack_files))
  410. def _fetch(self,
  411. verbose,
  412. depth,
  413. no_fetch_tags,
  414. reset_fetch_config,
  415. prune=True):
  416. self.config(reset_fetch_config)
  417. fetch_cmd = ['fetch']
  418. if verbose:
  419. fetch_cmd.extend(['-v', '--progress'])
  420. if depth:
  421. fetch_cmd.extend(['--depth', str(depth)])
  422. if no_fetch_tags:
  423. fetch_cmd.append('--no-tags')
  424. if prune:
  425. fetch_cmd.append('--prune')
  426. fetch_cmd.append('origin')
  427. fetch_specs = subprocess.check_output(
  428. [
  429. self.git_exe, '--git-dir',
  430. os.path.abspath(self.mirror_path), 'config', '--get-all',
  431. 'remote.origin.fetch'
  432. ],
  433. cwd=self.mirror_path).decode('utf-8',
  434. 'ignore').strip().splitlines()
  435. for spec in fetch_specs:
  436. try:
  437. self.print('Fetching %s' % spec)
  438. with self.print_duration_of('fetch %s' % spec):
  439. self.RunGit(fetch_cmd + [spec], retry=True)
  440. except subprocess.CalledProcessError:
  441. if spec == '+refs/heads/*:refs/heads/*':
  442. raise ClobberNeeded() # Corrupted cache.
  443. logging.warning('Fetch of %s failed' % spec)
  444. for commit in self.fetch_commits:
  445. self.print('Fetching %s' % commit)
  446. try:
  447. with self.print_duration_of('fetch %s' % commit):
  448. self.RunGit(['fetch', 'origin', commit], retry=True)
  449. except subprocess.CalledProcessError:
  450. logging.warning('Fetch of %s failed' % commit)
  451. def populate(self,
  452. depth=None,
  453. no_fetch_tags=False,
  454. shallow=False,
  455. bootstrap=False,
  456. verbose=False,
  457. lock_timeout=0,
  458. reset_fetch_config=False):
  459. assert self.GetCachePath()
  460. if shallow and not depth:
  461. depth = 10000
  462. gclient_utils.safe_makedirs(self.GetCachePath())
  463. with lockfile.lock(self.mirror_path, lock_timeout):
  464. try:
  465. self._ensure_bootstrapped(depth, bootstrap, reset_fetch_config)
  466. self._fetch(verbose, depth, no_fetch_tags, reset_fetch_config)
  467. except ClobberNeeded:
  468. # This is a major failure, we need to clean and force a
  469. # bootstrap.
  470. gclient_utils.rmtree(self.mirror_path)
  471. self.print(GIT_CACHE_CORRUPT_MESSAGE)
  472. self._ensure_bootstrapped(depth,
  473. bootstrap,
  474. reset_fetch_config,
  475. force=True)
  476. self._fetch(verbose, depth, no_fetch_tags, reset_fetch_config)
  477. def update_bootstrap(self, prune=False, gc_aggressive=False):
  478. # NOTE: There have been cases where repos were being recursively
  479. # uploaded to google storage. E.g.
  480. # `<host_url>-<repo>/<gen_number>/<host_url>-<repo>/` in GS and
  481. # <host_url>-<repo>/<host_url>-<repo>/ on the bot. Check for recursed
  482. # files on the bot here and remove them if found before we upload to GS.
  483. # See crbug.com/1370443; keep this check until root cause is found.
  484. recursed_dir = os.path.join(self.mirror_path,
  485. self.mirror_path.split(os.path.sep)[-1])
  486. if os.path.exists(recursed_dir):
  487. self.print('Deleting unexpected directory: %s' % recursed_dir)
  488. gclient_utils.rmtree(recursed_dir)
  489. # The folder is <git number>
  490. gen_number = subprocess.check_output([self.git_exe, 'number'],
  491. cwd=self.mirror_path).decode(
  492. 'utf-8', 'ignore').strip()
  493. gsutil = Gsutil(path=self.gsutil_exe, boto_path=None)
  494. dest_prefix = '%s/%s' % (self._gs_path, gen_number)
  495. # ls_out lists contents in the format: gs://blah/blah/123...
  496. self.print('running "gsutil ls %s":' % self._gs_path)
  497. ls_code, ls_out, ls_error = gsutil.check_call_with_retries(
  498. 'ls', self._gs_path)
  499. if ls_code != 0:
  500. self.print(ls_error)
  501. else:
  502. self.print(ls_out)
  503. # Check to see if folder already exists in gs
  504. ls_out_set = set(ls_out.strip().splitlines())
  505. if (dest_prefix + '/' in ls_out_set
  506. and dest_prefix + '.ready' in ls_out_set):
  507. print('Cache %s already exists.' % dest_prefix)
  508. return
  509. # Reduce the number of individual files to download & write on disk.
  510. self.RunGit(['pack-refs', '--all'])
  511. # Run Garbage Collect to compress packfile.
  512. gc_args = ['gc', '--prune=all']
  513. if gc_aggressive:
  514. # The default "gc --aggressive" is often too aggressive for some
  515. # machines, since it attempts to create as many threads as there are
  516. # CPU cores, while not limiting per-thread memory usage, which puts
  517. # too much pressure on RAM on high-core machines, causing them to
  518. # thrash. Using lower-level commands gives more control over those
  519. # settings.
  520. # This might not be strictly necessary, but it's fast and is
  521. # normally run by 'gc --aggressive', so it shouldn't hurt.
  522. self.RunGit(['reflog', 'expire', '--all'])
  523. # These are the default repack settings for 'gc --aggressive'.
  524. gc_args = [
  525. 'repack', '-d', '-l', '-f', '--depth=50', '--window=250', '-A',
  526. '--unpack-unreachable=all'
  527. ]
  528. # A 1G memory limit seems to provide comparable pack results as the
  529. # default, even for our largest repos, while preventing runaway
  530. # memory (at least on current Chromium builders which have about 4G
  531. # RAM per core).
  532. gc_args.append('--window-memory=1g')
  533. # NOTE: It might also be possible to avoid thrashing with a larger
  534. # window (e.g. "--window-memory=2g") by limiting the number of
  535. # threads created (e.g. "--threads=[cores/2]"). Some limited testing
  536. # didn't show much difference in outcomes on our current repos, but
  537. # it might be worth trying if the repos grow much larger and the
  538. # packs don't seem to be getting compressed enough.
  539. self.RunGit(gc_args)
  540. self.print('running "gsutil -m rsync -r -d %s %s"' %
  541. (self.mirror_path, dest_prefix))
  542. gsutil.call('-m', 'rsync', '-r', '-d', self.mirror_path, dest_prefix)
  543. # Create .ready file and upload
  544. _, ready_file_name = tempfile.mkstemp(suffix='.ready')
  545. try:
  546. self.print('running "gsutil cp %s %s.ready"' %
  547. (ready_file_name, dest_prefix))
  548. gsutil.call('cp', ready_file_name, '%s.ready' % (dest_prefix))
  549. finally:
  550. os.remove(ready_file_name)
  551. # remove all other directory/.ready files in the same gs_path
  552. # except for the directory/.ready file previously created
  553. # which can be used for bootstrapping while the current one is
  554. # being uploaded
  555. if not prune:
  556. return
  557. prev_dest_prefix = self._GetMostRecentCacheDirectory(ls_out_set)
  558. if not prev_dest_prefix:
  559. return
  560. for path in ls_out_set:
  561. if path in (prev_dest_prefix + '/', prev_dest_prefix + '.ready'):
  562. continue
  563. if path.endswith('.ready'):
  564. gsutil.call('rm', path)
  565. continue
  566. gsutil.call('-m', 'rm', '-r', path)
  567. @staticmethod
  568. def DeleteTmpPackFiles(path):
  569. pack_dir = os.path.join(path, 'objects', 'pack')
  570. if not os.path.isdir(pack_dir):
  571. return
  572. pack_files = [
  573. f for f in os.listdir(pack_dir)
  574. if f.startswith('.tmp-') or f.startswith('tmp_pack_')
  575. ]
  576. for f in pack_files:
  577. f = os.path.join(pack_dir, f)
  578. try:
  579. os.remove(f)
  580. logging.warning('Deleted stale temporary pack file %s' % f)
  581. except OSError:
  582. logging.warning('Unable to delete temporary pack file %s' % f)
  583. @subcommand.usage('[url of repo to check for caching]')
  584. @metrics.collector.collect_metrics('git cache exists')
  585. def CMDexists(parser, args):
  586. """Check to see if there already is a cache of the given repo."""
  587. _, args = parser.parse_args(args)
  588. if not len(args) == 1:
  589. parser.error('git cache exists only takes exactly one repo url.')
  590. url = args[0]
  591. mirror = Mirror(url)
  592. if mirror.exists():
  593. print(mirror.mirror_path)
  594. return 0
  595. return 1
  596. @subcommand.usage('[url of repo to create a bootstrap zip file]')
  597. @metrics.collector.collect_metrics('git cache update-bootstrap')
  598. def CMDupdate_bootstrap(parser, args):
  599. """Create and uploads a bootstrap tarball."""
  600. # Lets just assert we can't do this on Windows.
  601. if sys.platform.startswith('win'):
  602. print('Sorry, update bootstrap will not work on Windows.',
  603. file=sys.stderr)
  604. return 1
  605. parser.add_option('--skip-populate',
  606. action='store_true',
  607. help='Skips "populate" step if mirror already exists.')
  608. parser.add_option('--gc-aggressive',
  609. action='store_true',
  610. help='Run aggressive repacking of the repo.')
  611. parser.add_option('--prune',
  612. action='store_true',
  613. help='Prune all other cached bundles of the same repo.')
  614. populate_args = args[:]
  615. options, args = parser.parse_args(args)
  616. url = args[0]
  617. mirror = Mirror(url)
  618. if not options.skip_populate or not mirror.exists():
  619. CMDpopulate(parser, populate_args)
  620. else:
  621. print('Skipped populate step.')
  622. # Get the repo directory.
  623. _, args2 = parser.parse_args(args)
  624. url = args2[0]
  625. mirror = Mirror(url)
  626. mirror.update_bootstrap(options.prune, options.gc_aggressive)
  627. return 0
  628. @subcommand.usage('[url of repo to add to or update in cache]')
  629. @metrics.collector.collect_metrics('git cache populate')
  630. def CMDpopulate(parser, args):
  631. """Ensure that the cache has all up-to-date objects for the given repo."""
  632. parser.add_option('--depth',
  633. type='int',
  634. help='Only cache DEPTH commits of history')
  635. parser.add_option(
  636. '--no-fetch-tags',
  637. action='store_true',
  638. help=('Don\'t fetch tags from the server. This can speed up '
  639. 'fetch considerably when there are many tags.'))
  640. parser.add_option('--shallow',
  641. '-s',
  642. action='store_true',
  643. help='Only cache 10000 commits of history')
  644. parser.add_option('--ref',
  645. action='append',
  646. help='Specify additional refs to be fetched')
  647. parser.add_option('--commit',
  648. action='append',
  649. help='Specify additional commits to be fetched')
  650. parser.add_option('--no_bootstrap',
  651. '--no-bootstrap',
  652. action='store_true',
  653. help='Don\'t bootstrap from Google Storage')
  654. parser.add_option('--ignore_locks',
  655. '--ignore-locks',
  656. action='store_true',
  657. help='NOOP. This flag will be removed in the future.')
  658. parser.add_option(
  659. '--break-locks',
  660. action='store_true',
  661. help='Break any existing lock instead of just ignoring it')
  662. parser.add_option(
  663. '--reset-fetch-config',
  664. action='store_true',
  665. default=False,
  666. help='Reset the fetch config before populating the cache.')
  667. options, args = parser.parse_args(args)
  668. if not len(args) == 1:
  669. parser.error('git cache populate only takes exactly one repo url.')
  670. if options.ignore_locks:
  671. print('ignore_locks is no longer used. Please remove its usage.')
  672. if options.break_locks:
  673. print('break_locks is no longer used. Please remove its usage.')
  674. url = args[0]
  675. mirror = Mirror(url, refs=options.ref, commits=options.commit)
  676. kwargs = {
  677. 'no_fetch_tags': options.no_fetch_tags,
  678. 'verbose': options.verbose,
  679. 'shallow': options.shallow,
  680. 'bootstrap': not options.no_bootstrap,
  681. 'lock_timeout': options.timeout,
  682. 'reset_fetch_config': options.reset_fetch_config,
  683. }
  684. if options.depth:
  685. kwargs['depth'] = options.depth
  686. mirror.populate(**kwargs)
  687. @subcommand.usage('Fetch new commits into cache and current checkout')
  688. @metrics.collector.collect_metrics('git cache fetch')
  689. def CMDfetch(parser, args):
  690. """Update mirror, and fetch in cwd."""
  691. parser.add_option('--all', action='store_true', help='Fetch all remotes')
  692. parser.add_option('--no_bootstrap',
  693. '--no-bootstrap',
  694. action='store_true',
  695. help='Don\'t (re)bootstrap from Google Storage')
  696. parser.add_option(
  697. '--no-fetch-tags',
  698. action='store_true',
  699. help=('Don\'t fetch tags from the server. This can speed up '
  700. 'fetch considerably when there are many tags.'))
  701. options, args = parser.parse_args(args)
  702. # Figure out which remotes to fetch. This mimics the behavior of regular
  703. # 'git fetch'. Note that in the case of "stacked" or "pipelined" branches,
  704. # this will NOT try to traverse up the branching structure to find the
  705. # ultimate remote to update.
  706. remotes = []
  707. if options.all:
  708. assert not args, 'fatal: fetch --all does not take repository argument'
  709. remotes = subprocess.check_output([Mirror.git_exe, 'remote'])
  710. remotes = remotes.decode('utf-8', 'ignore').splitlines()
  711. elif args:
  712. remotes = args
  713. else:
  714. current_branch = subprocess.check_output(
  715. [Mirror.git_exe, 'rev-parse', '--abbrev-ref', 'HEAD'])
  716. current_branch = current_branch.decode('utf-8', 'ignore').strip()
  717. if current_branch != 'HEAD':
  718. upstream = subprocess.check_output(
  719. [Mirror.git_exe, 'config',
  720. 'branch.%s.remote' % current_branch])
  721. upstream = upstream.decode('utf-8', 'ignore').strip()
  722. if upstream and upstream != '.':
  723. remotes = [upstream]
  724. if not remotes:
  725. remotes = ['origin']
  726. cachepath = Mirror.GetCachePath()
  727. git_dir = os.path.abspath(
  728. subprocess.check_output([Mirror.git_exe, 'rev-parse',
  729. '--git-dir']).decode('utf-8', 'ignore'))
  730. git_dir = os.path.abspath(git_dir)
  731. if git_dir.startswith(cachepath):
  732. mirror = Mirror.FromPath(git_dir)
  733. mirror.populate(bootstrap=not options.no_bootstrap,
  734. no_fetch_tags=options.no_fetch_tags,
  735. lock_timeout=options.timeout)
  736. return 0
  737. for remote in remotes:
  738. remote_url = subprocess.check_output(
  739. [Mirror.git_exe, 'config',
  740. 'remote.%s.url' % remote])
  741. remote_url = remote_url.decode('utf-8', 'ignore').strip()
  742. if remote_url.startswith(cachepath):
  743. mirror = Mirror.FromPath(remote_url)
  744. mirror.print = lambda *args: None
  745. print('Updating git cache...')
  746. mirror.populate(bootstrap=not options.no_bootstrap,
  747. no_fetch_tags=options.no_fetch_tags,
  748. lock_timeout=options.timeout)
  749. subprocess.check_call([Mirror.git_exe, 'fetch', remote])
  750. return 0
  751. @subcommand.usage('do not use - it is a noop.')
  752. @metrics.collector.collect_metrics('git cache unlock')
  753. def CMDunlock(parser, args):
  754. """This command does nothing."""
  755. print('This command does nothing and will be removed in the future.')
  756. class OptionParser(optparse.OptionParser):
  757. """Wrapper class for OptionParser to handle global options."""
  758. def __init__(self, *args, **kwargs):
  759. optparse.OptionParser.__init__(self, *args, prog='git cache', **kwargs)
  760. self.add_option(
  761. '-c',
  762. '--cache-dir',
  763. help=('Path to the directory containing the caches. Normally '
  764. 'deduced from git config cache.cachepath or '
  765. '$GIT_CACHE_PATH.'))
  766. self.add_option(
  767. '-v',
  768. '--verbose',
  769. action='count',
  770. default=1,
  771. help='Increase verbosity (can be passed multiple times)')
  772. self.add_option('-q',
  773. '--quiet',
  774. action='store_true',
  775. help='Suppress all extraneous output')
  776. self.add_option('--timeout',
  777. type='int',
  778. default=0,
  779. help='Timeout for acquiring cache lock, in seconds')
  780. def parse_args(self, args=None, values=None):
  781. # Create an optparse.Values object that will store only the actual
  782. # passed options, without the defaults.
  783. actual_options = optparse.Values()
  784. _, args = optparse.OptionParser.parse_args(self, args, actual_options)
  785. # Create an optparse.Values object with the default options.
  786. options = optparse.Values(self.get_default_values().__dict__)
  787. # Update it with the options passed by the user.
  788. options._update_careful(actual_options.__dict__)
  789. # Store the options passed by the user in an _actual_options attribute.
  790. # We store only the keys, and not the values, since the values can
  791. # contain arbitrary information, which might be PII.
  792. metrics.collector.add('arguments', list(actual_options.__dict__.keys()))
  793. if options.quiet:
  794. options.verbose = 0
  795. levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
  796. logging.basicConfig(level=levels[min(options.verbose, len(levels) - 1)])
  797. try:
  798. global_cache_dir = Mirror.GetCachePath()
  799. except RuntimeError:
  800. global_cache_dir = None
  801. if options.cache_dir:
  802. if global_cache_dir and (os.path.abspath(options.cache_dir) !=
  803. os.path.abspath(global_cache_dir)):
  804. logging.warning(
  805. 'Overriding globally-configured cache directory.')
  806. Mirror.SetCachePath(options.cache_dir)
  807. return options, args
  808. def main(argv):
  809. dispatcher = subcommand.CommandDispatcher(__name__)
  810. return dispatcher.execute(OptionParser(), argv)
  811. if __name__ == '__main__':
  812. try:
  813. with metrics.collector.print_notice_and_exit():
  814. sys.exit(main(sys.argv[1:]))
  815. except KeyboardInterrupt:
  816. sys.stderr.write('interrupted\n')
  817. sys.exit(1)