git_cache.py 38 KB

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