blob: 6c4609c61889a65b0aff5a47f39a2998dd4e0371 [file] [log] [blame]
Josip Sokcevic4de5dea2022-03-23 21:15:14 +00001#!/usr/bin/env python3
agable@chromium.org5a306a22014-02-24 22:13:59 +00002# 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
6"""A git command for managing a local cache of git repositories."""
7
szager@chromium.org848fd492014-04-09 19:06:44 +00008from __future__ import print_function
Raul Tambreb946b232019-03-26 14:48:46 +00009
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -080010import contextlib
agable@chromium.org5a306a22014-02-24 22:13:59 +000011import errno
12import logging
13import optparse
14import os
szager@chromium.org174766f2014-05-13 21:27:46 +000015import re
John Budorick47ec0692019-05-01 15:04:28 +000016import subprocess
17import sys
agable@chromium.org5a306a22014-02-24 22:13:59 +000018import tempfile
szager@chromium.org1132f5f2014-08-23 01:57:59 +000019import threading
pgervais@chromium.orgf3726102014-04-17 17:24:15 +000020import time
Raul Tambreb946b232019-03-26 14:48:46 +000021
22try:
23 import urlparse
24except ImportError: # For Py3 compatibility
25 import urllib.parse as urlparse
26
hinoka@google.com563559c2014-04-02 00:36:24 +000027from download_from_google_storage import Gsutil
agable@chromium.org5a306a22014-02-24 22:13:59 +000028import gclient_utils
Josip Sokcevic14a83ae2020-05-21 01:36:34 +000029import lockfile
Edward Lesmescb047442021-05-06 20:18:49 +000030import metrics
agable@chromium.org5a306a22014-02-24 22:13:59 +000031import subcommand
32
szager@chromium.org301a7c32014-06-16 17:13:50 +000033# Analogous to gc.autopacklimit git config.
34GC_AUTOPACKLIMIT = 50
Takuto Ikuta9fce2132017-12-14 10:44:28 +090035
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +000036GIT_CACHE_CORRUPT_MESSAGE = 'WARNING: The Git cache is corrupt.'
37
Josip Sokcevic604f1602021-10-15 15:45:10 +000038# gsutil creates many processes and threads. Creating too many gsutil cp
39# processes may result in running out of resources, and may perform worse due to
40# contextr switching. This limits how many concurrent gsutil cp processes
41# git_cache runs.
42GSUTIL_CP_SEMAPHORE = threading.Semaphore(2)
43
szager@chromium.org848fd492014-04-09 19:06:44 +000044try:
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -080045 # pylint: disable=undefined-variable
szager@chromium.org848fd492014-04-09 19:06:44 +000046 WinErr = WindowsError
47except NameError:
48 class WinErr(Exception):
49 pass
agable@chromium.org5a306a22014-02-24 22:13:59 +000050
hinokadcd84042016-06-09 14:26:17 -070051class ClobberNeeded(Exception):
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +000052 pass
agable@chromium.org5a306a22014-02-24 22:13:59 +000053
dnj4625b5a2016-11-10 18:23:26 -080054
55def exponential_backoff_retry(fn, excs=(Exception,), name=None, count=10,
56 sleep_time=0.25, printerr=None):
57 """Executes |fn| up to |count| times, backing off exponentially.
58
59 Args:
60 fn (callable): The function to execute. If this raises a handled
61 exception, the function will retry with exponential backoff.
62 excs (tuple): A tuple of Exception types to handle. If one of these is
63 raised by |fn|, a retry will be attempted. If |fn| raises an Exception
64 that is not in this list, it will immediately pass through. If |excs|
65 is empty, the Exception base class will be used.
66 name (str): Optional operation name to print in the retry string.
67 count (int): The number of times to try before allowing the exception to
68 pass through.
69 sleep_time (float): The initial number of seconds to sleep in between
70 retries. This will be doubled each retry.
71 printerr (callable): Function that will be called with the error string upon
72 failures. If None, |logging.warning| will be used.
73
74 Returns: The return value of the successful fn.
75 """
76 printerr = printerr or logging.warning
Edward Lesmes451e8ba2019-10-01 22:15:33 +000077 for i in range(count):
dnj4625b5a2016-11-10 18:23:26 -080078 try:
79 return fn()
80 except excs as e:
81 if (i+1) >= count:
82 raise
83
84 printerr('Retrying %s in %.2f second(s) (%d / %d attempts): %s' % (
85 (name or 'operation'), sleep_time, (i+1), count, e))
86 time.sleep(sleep_time)
87 sleep_time *= 2
88
89
szager@chromium.org848fd492014-04-09 19:06:44 +000090class Mirror(object):
91
92 git_exe = 'git.bat' if sys.platform.startswith('win') else 'git'
93 gsutil_exe = os.path.join(
hinoka@chromium.orgb091aa52014-12-20 01:47:31 +000094 os.path.dirname(os.path.abspath(__file__)), 'gsutil.py')
Vadim Shtayura08049e22017-10-11 00:14:52 +000095 cachepath_lock = threading.Lock()
szager@chromium.org848fd492014-04-09 19:06:44 +000096
Robert Iannuccia19649b2018-06-29 16:31:45 +000097 UNSET_CACHEPATH = object()
98
99 # Used for tests
100 _GIT_CONFIG_LOCATION = []
101
szager@chromium.org66c8b852015-09-22 23:19:07 +0000102 @staticmethod
103 def parse_fetch_spec(spec):
104 """Parses and canonicalizes a fetch spec.
105
106 Returns (fetchspec, value_regex), where value_regex can be used
107 with 'git config --replace-all'.
108 """
109 parts = spec.split(':', 1)
110 src = parts[0].lstrip('+').rstrip('/')
111 if not src.startswith('refs/'):
112 src = 'refs/heads/%s' % src
113 dest = parts[1].rstrip('/') if len(parts) > 1 else src
114 regex = r'\+%s:.*' % src.replace('*', r'\*')
115 return ('+%s:%s' % (src, dest), regex)
116
Edward Lesmes07a68342021-04-20 23:39:30 +0000117 def __init__(self, url, refs=None, commits=None, print_func=None):
szager@chromium.org848fd492014-04-09 19:06:44 +0000118 self.url = url
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000119 self.fetch_specs = {self.parse_fetch_spec(ref) for ref in (refs or [])}
Edward Lesmes07a68342021-04-20 23:39:30 +0000120 self.fetch_commits = set(commits or [])
szager@chromium.org848fd492014-04-09 19:06:44 +0000121 self.basedir = self.UrlToCacheDir(url)
122 self.mirror_path = os.path.join(self.GetCachePath(), self.basedir)
loislo@chromium.org0fb693f2014-12-25 15:28:22 +0000123 if print_func:
124 self.print = self.print_without_file
125 self.print_func = print_func
126 else:
127 self.print = print
128
dnj4625b5a2016-11-10 18:23:26 -0800129 def print_without_file(self, message, **_kwargs):
loislo@chromium.org0fb693f2014-12-25 15:28:22 +0000130 self.print_func(message)
szager@chromium.org848fd492014-04-09 19:06:44 +0000131
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800132 @contextlib.contextmanager
133 def print_duration_of(self, what):
134 start = time.time()
135 try:
136 yield
137 finally:
138 self.print('%s took %.1f minutes' % (what, (time.time() - start) / 60.0))
139
hinoka@chromium.orgf8fa23d2014-06-05 01:00:04 +0000140 @property
141 def bootstrap_bucket(self):
Andrii Shyshkalov4b79c382019-04-15 23:48:35 +0000142 b = os.getenv('OVERRIDE_BOOTSTRAP_BUCKET')
143 if b:
144 return b
Ryan Tseng3beabd02017-03-15 13:57:58 -0700145 u = urlparse.urlparse(self.url)
146 if u.netloc == 'chromium.googlesource.com':
hinoka@chromium.orgf8fa23d2014-06-05 01:00:04 +0000147 return 'chromium-git-cache'
Ryan Tseng3beabd02017-03-15 13:57:58 -0700148 # Not recognized.
149 return None
hinoka@chromium.orgf8fa23d2014-06-05 01:00:04 +0000150
Karen Qiandcad7492019-04-26 03:11:16 +0000151 @property
152 def _gs_path(self):
153 return 'gs://%s/v2/%s' % (self.bootstrap_bucket, self.basedir)
154
szager@chromium.org174766f2014-05-13 21:27:46 +0000155 @classmethod
156 def FromPath(cls, path):
157 return cls(cls.CacheDirToUrl(path))
158
szager@chromium.org848fd492014-04-09 19:06:44 +0000159 @staticmethod
160 def UrlToCacheDir(url):
161 """Convert a git url to a normalized form for the cache dir path."""
Edward Lemure9024d02019-11-19 18:47:46 +0000162 if os.path.isdir(url):
163 # Ignore the drive letter in Windows
164 url = os.path.splitdrive(url)[1]
165 return url.replace('-', '--').replace(os.sep, '-')
166
szager@chromium.org848fd492014-04-09 19:06:44 +0000167 parsed = urlparse.urlparse(url)
Edward Lemure9024d02019-11-19 18:47:46 +0000168 norm_url = parsed.netloc + parsed.path
szager@chromium.org848fd492014-04-09 19:06:44 +0000169 if norm_url.endswith('.git'):
170 norm_url = norm_url[:-len('.git')]
Dirk Prankedb589542019-04-12 21:07:01 +0000171
172 # Use the same dir for authenticated URLs and unauthenticated URLs.
173 norm_url = norm_url.replace('googlesource.com/a/', 'googlesource.com/')
174
szager@chromium.org848fd492014-04-09 19:06:44 +0000175 return norm_url.replace('-', '--').replace('/', '-').lower()
176
177 @staticmethod
szager@chromium.org174766f2014-05-13 21:27:46 +0000178 def CacheDirToUrl(path):
179 """Convert a cache dir path to its corresponding url."""
180 netpath = re.sub(r'\b-\b', '/', os.path.basename(path)).replace('--', '-')
181 return 'https://%s' % netpath
182
szager@chromium.org848fd492014-04-09 19:06:44 +0000183 @classmethod
184 def SetCachePath(cls, cachepath):
Vadim Shtayura08049e22017-10-11 00:14:52 +0000185 with cls.cachepath_lock:
186 setattr(cls, 'cachepath', cachepath)
szager@chromium.org848fd492014-04-09 19:06:44 +0000187
188 @classmethod
189 def GetCachePath(cls):
Vadim Shtayura08049e22017-10-11 00:14:52 +0000190 with cls.cachepath_lock:
191 if not hasattr(cls, 'cachepath'):
192 try:
193 cachepath = subprocess.check_output(
Robert Iannuccia19649b2018-06-29 16:31:45 +0000194 [cls.git_exe, 'config'] +
195 cls._GIT_CONFIG_LOCATION +
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000196 ['cache.cachepath']).decode('utf-8', 'ignore').strip()
Vadim Shtayura08049e22017-10-11 00:14:52 +0000197 except subprocess.CalledProcessError:
Robert Iannuccia19649b2018-06-29 16:31:45 +0000198 cachepath = os.environ.get('GIT_CACHE_PATH', cls.UNSET_CACHEPATH)
Vadim Shtayura08049e22017-10-11 00:14:52 +0000199 setattr(cls, 'cachepath', cachepath)
Robert Iannuccia19649b2018-06-29 16:31:45 +0000200
201 ret = getattr(cls, 'cachepath')
202 if ret is cls.UNSET_CACHEPATH:
203 raise RuntimeError('No cache.cachepath git configuration or '
204 '$GIT_CACHE_PATH is set.')
205 return ret
szager@chromium.org848fd492014-04-09 19:06:44 +0000206
Karen Qianccd2b4d2019-05-03 22:25:59 +0000207 @staticmethod
208 def _GetMostRecentCacheDirectory(ls_out_set):
209 ready_file_pattern = re.compile(r'.*/(\d+).ready$')
210 ready_dirs = []
211
212 for name in ls_out_set:
213 m = ready_file_pattern.match(name)
214 # Given <path>/<number>.ready,
215 # we are interested in <path>/<number> directory
216 if m and (name[:-len('.ready')] + '/') in ls_out_set:
217 ready_dirs.append((int(m.group(1)), name[:-len('.ready')]))
218
219 if not ready_dirs:
220 return None
221
222 return max(ready_dirs)[1]
223
dnj4625b5a2016-11-10 18:23:26 -0800224 def Rename(self, src, dst):
225 # This is somehow racy on Windows.
226 # Catching OSError because WindowsError isn't portable and
227 # pylint complains.
228 exponential_backoff_retry(
229 lambda: os.rename(src, dst),
230 excs=(OSError,),
231 name='rename [%s] => [%s]' % (src, dst),
232 printerr=self.print)
233
Josip Sokcevic650f8532021-10-15 18:35:31 +0000234 def RunGit(self, cmd, print_stdout=True, **kwargs):
szager@chromium.org848fd492014-04-09 19:06:44 +0000235 """Run git in a subprocess."""
236 cwd = kwargs.setdefault('cwd', self.mirror_path)
Joanna Wangea99f9a2023-08-17 02:20:43 +0000237 if "--git-dir" not in cmd:
238 cmd = ['--git-dir', os.path.abspath(cwd)] + cmd
239
szager@chromium.org848fd492014-04-09 19:06:44 +0000240 kwargs.setdefault('print_stdout', False)
Josip Sokcevic650f8532021-10-15 18:35:31 +0000241 if print_stdout:
242 kwargs.setdefault('filter_fn', self.print)
szager@chromium.org848fd492014-04-09 19:06:44 +0000243 env = kwargs.get('env') or kwargs.setdefault('env', os.environ.copy())
244 env.setdefault('GIT_ASKPASS', 'true')
245 env.setdefault('SSH_ASKPASS', 'true')
246 self.print('running "git %s" in "%s"' % (' '.join(cmd), cwd))
247 gclient_utils.CheckCallAndFilter([self.git_exe] + cmd, **kwargs)
248
Joanna Wangea99f9a2023-08-17 02:20:43 +0000249 def config(self, reset_fetch_config=False):
Edward Lemur579c9862018-07-13 23:17:51 +0000250 if reset_fetch_config:
Edward Lemur2f38df62018-07-14 02:13:21 +0000251 try:
Joanna Wangea99f9a2023-08-17 02:20:43 +0000252 self.RunGit(['config', '--unset-all', 'remote.origin.fetch'])
Edward Lemur2f38df62018-07-14 02:13:21 +0000253 except subprocess.CalledProcessError as e:
254 # If exit code was 5, it means we attempted to unset a config that
255 # didn't exist. Ignore it.
256 if e.returncode != 5:
257 raise
Edward Lemur579c9862018-07-13 23:17:51 +0000258
szager@chromium.org301a7c32014-06-16 17:13:50 +0000259 # Don't run git-gc in a daemon. Bad things can happen if it gets killed.
hinokadcd84042016-06-09 14:26:17 -0700260 try:
Joanna Wangea99f9a2023-08-17 02:20:43 +0000261 self.RunGit(['config', 'gc.autodetach', '0'])
hinokadcd84042016-06-09 14:26:17 -0700262 except subprocess.CalledProcessError:
263 # Hard error, need to clobber.
264 raise ClobberNeeded()
szager@chromium.org301a7c32014-06-16 17:13:50 +0000265
266 # Don't combine pack files into one big pack file. It's really slow for
267 # repositories, and there's no way to track progress and make sure it's
268 # not stuck.
Ryan Tseng3beabd02017-03-15 13:57:58 -0700269 if self.supported_project():
Joanna Wangea99f9a2023-08-17 02:20:43 +0000270 self.RunGit(['config', 'gc.autopacklimit', '0'])
szager@chromium.org301a7c32014-06-16 17:13:50 +0000271
272 # Allocate more RAM for cache-ing delta chains, for better performance
273 # of "Resolving deltas".
Joanna Wangea99f9a2023-08-17 02:20:43 +0000274 self.RunGit([
275 'config', 'core.deltaBaseCacheLimit',
276 gclient_utils.DefaultDeltaBaseCacheLimit()
277 ])
szager@chromium.org301a7c32014-06-16 17:13:50 +0000278
Joanna Wangea99f9a2023-08-17 02:20:43 +0000279 self.RunGit(['config', 'remote.origin.url', self.url])
280 self.RunGit([
281 'config', '--replace-all', 'remote.origin.fetch',
282 '+refs/heads/*:refs/heads/*', r'\+refs/heads/\*:.*'
283 ])
szager@chromium.org66c8b852015-09-22 23:19:07 +0000284 for spec, value_regex in self.fetch_specs:
szager@chromium.org965c44f2014-08-19 21:19:19 +0000285 self.RunGit(
Joanna Wangea99f9a2023-08-17 02:20:43 +0000286 ['config', '--replace-all', 'remote.origin.fetch', spec, value_regex])
szager@chromium.org848fd492014-04-09 19:06:44 +0000287
288 def bootstrap_repo(self, directory):
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800289 """Bootstrap the repo from Google Storage if possible.
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000290
291 More apt-ly named bootstrap_repo_from_cloud_if_possible_else_do_nothing().
292 """
Ryan Tseng3beabd02017-03-15 13:57:58 -0700293 if not self.bootstrap_bucket:
294 return False
szager@chromium.org848fd492014-04-09 19:06:44 +0000295
hinoka@chromium.org199bc5f2014-12-17 02:17:14 +0000296 gsutil = Gsutil(self.gsutil_exe, boto_path=None)
Yuwei Huanga1fbdff2019-02-01 21:51:15 +0000297
Karen Qian0cbd5a52019-04-29 20:14:50 +0000298 # Get the most recent version of the directory.
299 # This is determined from the most recent version of a .ready file.
300 # The .ready file is only uploaded when an entire directory has been
301 # uploaded to GS.
302 _, ls_out, ls_err = gsutil.check_call('ls', self._gs_path)
Karen Qianccd2b4d2019-05-03 22:25:59 +0000303 ls_out_set = set(ls_out.strip().splitlines())
304 latest_dir = self._GetMostRecentCacheDirectory(ls_out_set)
Yuwei Huanga1fbdff2019-02-01 21:51:15 +0000305
Karen Qianccd2b4d2019-05-03 22:25:59 +0000306 if not latest_dir:
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800307 self.print('No bootstrap file for %s found in %s, stderr:\n %s' %
308 (self.mirror_path, self.bootstrap_bucket,
Karen Qian0cbd5a52019-04-29 20:14:50 +0000309 ' '.join((ls_err or '').splitlines(True))))
szager@chromium.org848fd492014-04-09 19:06:44 +0000310 return False
szager@chromium.org848fd492014-04-09 19:06:44 +0000311
szager@chromium.org848fd492014-04-09 19:06:44 +0000312 try:
Karen Qian0cbd5a52019-04-29 20:14:50 +0000313 # create new temporary directory locally
szager@chromium.org1cbf1042014-06-17 18:26:24 +0000314 tempdir = tempfile.mkdtemp(prefix='_cache_tmp', dir=self.GetCachePath())
Josip Sokcevica40c1e12021-08-18 20:38:32 +0000315 self.RunGit(['init', '--bare'], cwd=tempdir)
Karen Qian0cbd5a52019-04-29 20:14:50 +0000316 self.print('Downloading files in %s/* into %s.' %
317 (latest_dir, tempdir))
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800318 with self.print_duration_of('download'):
Josip Sokcevic604f1602021-10-15 15:45:10 +0000319 with GSUTIL_CP_SEMAPHORE:
320 code = gsutil.call('-m', 'cp', '-r', latest_dir + "/*",
321 tempdir)
szager@chromium.org848fd492014-04-09 19:06:44 +0000322 if code:
szager@chromium.org848fd492014-04-09 19:06:44 +0000323 return False
Josip Sokcevica40c1e12021-08-18 20:38:32 +0000324 # Set HEAD to main.
325 self.RunGit(['symbolic-ref', 'HEAD', 'refs/heads/main'], cwd=tempdir)
Josip Sokcevic67e12282020-12-16 17:12:45 +0000326 # A quick validation that all references are valid.
Josip Sokcevic650f8532021-10-15 18:35:31 +0000327 self.RunGit(['for-each-ref'], print_stdout=False, cwd=tempdir)
Karen Qian0cbd5a52019-04-29 20:14:50 +0000328 except Exception as e:
329 self.print('Encountered error: %s' % str(e), file=sys.stderr)
330 gclient_utils.rmtree(tempdir)
szager@chromium.org848fd492014-04-09 19:06:44 +0000331 return False
Karen Qian0cbd5a52019-04-29 20:14:50 +0000332 # delete the old directory
333 if os.path.exists(directory):
334 gclient_utils.rmtree(directory)
335 self.Rename(tempdir, directory)
szager@chromium.org848fd492014-04-09 19:06:44 +0000336 return True
337
Andrii Shyshkalov46a672b2017-11-24 18:04:43 -0800338 def contains_revision(self, revision):
339 if not self.exists():
340 return False
341
342 if sys.platform.startswith('win'):
343 # Windows .bat scripts use ^ as escape sequence, which means we have to
344 # escape it with itself for every .bat invocation.
345 needle = '%s^^^^{commit}' % revision
346 else:
347 needle = '%s^{commit}' % revision
348 try:
349 # cat-file exits with 0 on success, that is git object of given hash was
350 # found.
351 self.RunGit(['cat-file', '-e', needle])
352 return True
353 except subprocess.CalledProcessError:
Josip Sokcevic35061442022-01-12 00:32:54 +0000354 self.print('Commit with hash "%s" not found' % revision, file=sys.stderr)
Andrii Shyshkalov46a672b2017-11-24 18:04:43 -0800355 return False
356
szager@chromium.org848fd492014-04-09 19:06:44 +0000357 def exists(self):
358 return os.path.isfile(os.path.join(self.mirror_path, 'config'))
359
Ryan Tseng3beabd02017-03-15 13:57:58 -0700360 def supported_project(self):
361 """Returns true if this repo is known to have a bootstrap zip file."""
362 u = urlparse.urlparse(self.url)
363 return u.netloc in [
364 'chromium.googlesource.com',
365 'chrome-internal.googlesource.com']
366
szager@chromium.org66c8b852015-09-22 23:19:07 +0000367 def _preserve_fetchspec(self):
368 """Read and preserve remote.origin.fetch from an existing mirror.
369
370 This modifies self.fetch_specs.
371 """
372 if not self.exists():
373 return
374 try:
375 config_fetchspecs = subprocess.check_output(
376 [self.git_exe, 'config', '--get-all', 'remote.origin.fetch'],
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000377 cwd=self.mirror_path).decode('utf-8', 'ignore')
szager@chromium.org66c8b852015-09-22 23:19:07 +0000378 for fetchspec in config_fetchspecs.splitlines():
379 self.fetch_specs.add(self.parse_fetch_spec(fetchspec))
380 except subprocess.CalledProcessError:
Gavin Make6a62332020-12-04 21:57:10 +0000381 logging.warning(
382 'Tried and failed to preserve remote.origin.fetch from the '
383 'existing cache directory. You may need to manually edit '
384 '%s and "git cache fetch" again.' %
385 os.path.join(self.mirror_path, 'config'))
szager@chromium.org66c8b852015-09-22 23:19:07 +0000386
Edward Lesmes34f71ab2020-03-25 21:24:00 +0000387 def _ensure_bootstrapped(
388 self, depth, bootstrap, reset_fetch_config, force=False):
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000389 pack_dir = os.path.join(self.mirror_path, 'objects', 'pack')
390 pack_files = []
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000391 if os.path.isdir(pack_dir):
392 pack_files = [f for f in os.listdir(pack_dir) if f.endswith('.pack')]
Edward Lesmes34f71ab2020-03-25 21:24:00 +0000393 self.print('%s has %d .pack files, re-bootstrapping if >%d or ==0' %
Karen Qian0cbd5a52019-04-29 20:14:50 +0000394 (self.mirror_path, len(pack_files), GC_AUTOPACKLIMIT))
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000395
Aravind Vasudevan6eccb0e2023-03-06 17:28:15 +0000396 # master->main branch migration left the cache in some builders to have its
397 # HEAD still pointing to refs/heads/master. This causes bot_update to fail.
398 # If in this state, delete the cache and force bootstrap.
399 try:
400 with open(os.path.join(self.mirror_path, 'HEAD')) as f:
401 head_ref = f.read()
402 except FileNotFoundError:
403 head_ref = ''
404
405 # Check only when HEAD points to master.
406 if 'master' in head_ref:
407 # Some repos could still have master so verify if the ref exists first.
408 show_ref_master_cmd = subprocess.run(
409 [Mirror.git_exe, 'show-ref', '--verify', 'refs/heads/master'],
410 cwd=self.mirror_path)
411
412 if show_ref_master_cmd.returncode != 0:
413 # Remove mirror
414 gclient_utils.rmtree(self.mirror_path)
415
416 # force bootstrap
417 force = True
418
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000419 should_bootstrap = (force or
szager@chromium.org66c8b852015-09-22 23:19:07 +0000420 not self.exists() or
Edward Lesmes34f71ab2020-03-25 21:24:00 +0000421 len(pack_files) > GC_AUTOPACKLIMIT or
422 len(pack_files) == 0)
Karen Qian0cbd5a52019-04-29 20:14:50 +0000423
424 if not should_bootstrap:
425 if depth and os.path.exists(os.path.join(self.mirror_path, 'shallow')):
Gavin Make6a62332020-12-04 21:57:10 +0000426 logging.warning(
Karen Qian0cbd5a52019-04-29 20:14:50 +0000427 'Shallow fetch requested, but repo cache already exists.')
428 return
429
Edward Lesmes34f71ab2020-03-25 21:24:00 +0000430 if not self.exists():
John Budorick47ec0692019-05-01 15:04:28 +0000431 if os.path.exists(self.mirror_path):
432 # If the mirror path exists but self.exists() returns false, we're
433 # in an unexpected state. Nuke the previous mirror directory and
434 # start fresh.
435 gclient_utils.rmtree(self.mirror_path)
Karen Qian0cbd5a52019-04-29 20:14:50 +0000436 os.mkdir(self.mirror_path)
Edward Lesmes34f71ab2020-03-25 21:24:00 +0000437 elif not reset_fetch_config:
438 # Re-bootstrapping an existing mirror; preserve existing fetch spec.
439 self._preserve_fetchspec()
Karen Qian0cbd5a52019-04-29 20:14:50 +0000440
441 bootstrapped = (not depth and bootstrap and
442 self.bootstrap_repo(self.mirror_path))
443
444 if not bootstrapped:
445 if not self.exists() or not self.supported_project():
446 # Bootstrap failed due to:
447 # 1. No previous cache.
448 # 2. Project doesn't have a bootstrap folder.
Ryan Tseng3beabd02017-03-15 13:57:58 -0700449 # Start with a bare git dir.
Joanna Wangea99f9a2023-08-17 02:20:43 +0000450 self.RunGit(['init', '--bare'])
Josip Sokcevica4b36022022-06-09 19:59:33 +0000451 # Set appropriate symbolic-ref
Joanna Wangea99f9a2023-08-17 02:20:43 +0000452 remote_info = exponential_backoff_retry(lambda: subprocess.check_output(
453 [
454 self.git_exe, '--git-dir',
455 os.path.abspath(self.mirror_path), 'remote', 'show', self.url
456 ],
457 cwd=self.mirror_path).decode('utf-8', 'ignore').strip())
Josip Sokcevica4b36022022-06-09 19:59:33 +0000458 default_branch_regexp = re.compile(r'HEAD branch: (.*)$')
459 m = default_branch_regexp.search(remote_info, re.MULTILINE)
460 if m:
Joanna Wangea99f9a2023-08-17 02:20:43 +0000461 self.RunGit(['symbolic-ref', 'HEAD', 'refs/heads/' + m.groups()[0]])
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000462 else:
463 # Bootstrap failed, previous cache exists; warn and continue.
Gavin Make6a62332020-12-04 21:57:10 +0000464 logging.warning(
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800465 'Git cache has a lot of pack files (%d). Tried to re-bootstrap '
Gavin Make6a62332020-12-04 21:57:10 +0000466 'but failed. Continuing with non-optimized repository.' %
467 len(pack_files))
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000468
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000469 def _fetch(self,
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000470 verbose,
471 depth,
472 no_fetch_tags,
473 reset_fetch_config,
474 prune=True):
Joanna Wangea99f9a2023-08-17 02:20:43 +0000475 self.config(reset_fetch_config)
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000476
477 fetch_cmd = ['fetch']
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000478 if verbose:
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000479 fetch_cmd.extend(['-v', '--progress'])
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000480 if depth:
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000481 fetch_cmd.extend(['--depth', str(depth)])
danakjc41f72c2019-11-05 17:12:01 +0000482 if no_fetch_tags:
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000483 fetch_cmd.append('--no-tags')
484 if prune:
485 fetch_cmd.append('--prune')
486 fetch_cmd.append('origin')
487
Joanna Wangea99f9a2023-08-17 02:20:43 +0000488 fetch_specs = subprocess.check_output([
489 self.git_exe, '--git-dir',
490 os.path.abspath(self.mirror_path), 'config', '--get-all',
491 'remote.origin.fetch'
492 ],
493 cwd=self.mirror_path).decode(
494 'utf-8',
495 'ignore').strip().splitlines()
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000496 for spec in fetch_specs:
497 try:
498 self.print('Fetching %s' % spec)
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800499 with self.print_duration_of('fetch %s' % spec):
Joanna Wangea99f9a2023-08-17 02:20:43 +0000500 self.RunGit(fetch_cmd + [spec], retry=True)
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000501 except subprocess.CalledProcessError:
502 if spec == '+refs/heads/*:refs/heads/*':
hinokadcd84042016-06-09 14:26:17 -0700503 raise ClobberNeeded() # Corrupted cache.
Gavin Make6a62332020-12-04 21:57:10 +0000504 logging.warning('Fetch of %s failed' % spec)
Edward Lesmes07a68342021-04-20 23:39:30 +0000505 for commit in self.fetch_commits:
506 self.print('Fetching %s' % commit)
507 try:
508 with self.print_duration_of('fetch %s' % commit):
Joanna Wangea99f9a2023-08-17 02:20:43 +0000509 self.RunGit(['fetch', 'origin', commit], retry=True)
Edward Lesmes07a68342021-04-20 23:39:30 +0000510 except subprocess.CalledProcessError:
511 logging.warning('Fetch of %s failed' % commit)
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000512
danakjc41f72c2019-11-05 17:12:01 +0000513 def populate(self,
514 depth=None,
515 no_fetch_tags=False,
516 shallow=False,
517 bootstrap=False,
518 verbose=False,
danakjc41f72c2019-11-05 17:12:01 +0000519 lock_timeout=0,
Edward Lemur579c9862018-07-13 23:17:51 +0000520 reset_fetch_config=False):
szager@chromium.orgb0a13a22014-06-18 00:52:25 +0000521 assert self.GetCachePath()
szager@chromium.org848fd492014-04-09 19:06:44 +0000522 if shallow and not depth:
523 depth = 10000
524 gclient_utils.safe_makedirs(self.GetCachePath())
525
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000526 with lockfile.lock(self.mirror_path, lock_timeout):
527 try:
528 self._ensure_bootstrapped(depth, bootstrap, reset_fetch_config)
Joanna Wangea99f9a2023-08-17 02:20:43 +0000529 self._fetch(verbose, depth, no_fetch_tags, reset_fetch_config)
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000530 except ClobberNeeded:
531 # This is a major failure, we need to clean and force a bootstrap.
532 gclient_utils.rmtree(self.mirror_path)
533 self.print(GIT_CACHE_CORRUPT_MESSAGE)
534 self._ensure_bootstrapped(depth,
535 bootstrap,
536 reset_fetch_config,
537 force=True)
Joanna Wangea99f9a2023-08-17 02:20:43 +0000538 self._fetch(verbose, depth, no_fetch_tags, reset_fetch_config)
szager@chromium.org848fd492014-04-09 19:06:44 +0000539
Joanna Wang5175d182022-12-07 17:27:57 +0000540 def update_bootstrap(self, prune=False, gc_aggressive=False):
Joanna Wang38d16732022-10-10 17:12:47 +0000541 # NOTE: There have been cases where repos were being recursively uploaded
542 # to google storage.
543 # E.g. `<host_url>-<repo>/<gen_number>/<host_url>-<repo>/` in GS and
544 # <host_url>-<repo>/<host_url>-<repo>/ on the bot.
545 # Check for recursed files on the bot here and remove them if found
546 # before we upload to GS.
547 # See crbug.com/1370443; keep this check until root cause is found.
548 recursed_dir = os.path.join(self.mirror_path,
Joanna Wang17cf81d2022-10-12 03:41:24 +0000549 self.mirror_path.split(os.path.sep)[-1])
Joanna Wang38d16732022-10-10 17:12:47 +0000550 if os.path.exists(recursed_dir):
551 self.print('Deleting unexpected directory: %s' % recursed_dir)
Josip Sokcevicd540d8b2022-10-12 18:43:49 +0000552 gclient_utils.rmtree(recursed_dir)
Joanna Wang38d16732022-10-10 17:12:47 +0000553
Karen Qiandcad7492019-04-26 03:11:16 +0000554 # The folder is <git number>
Joanna Wang5175d182022-12-07 17:27:57 +0000555 gen_number = subprocess.check_output([self.git_exe, 'number'],
556 cwd=self.mirror_path).decode(
557 'utf-8', 'ignore').strip()
Karen Qiandcad7492019-04-26 03:11:16 +0000558 gsutil = Gsutil(path=self.gsutil_exe, boto_path=None)
559
Karen Qianccd2b4d2019-05-03 22:25:59 +0000560 dest_prefix = '%s/%s' % (self._gs_path, gen_number)
Karen Qiandcad7492019-04-26 03:11:16 +0000561
Karen Qianccd2b4d2019-05-03 22:25:59 +0000562 # ls_out lists contents in the format: gs://blah/blah/123...
Joanna Wang5b5ee2d2022-10-12 17:18:22 +0000563 self.print('running "gsutil ls %s":' % self._gs_path)
Joanna Wang38d16732022-10-10 17:12:47 +0000564 ls_code, ls_out, ls_error = gsutil.check_call_with_retries(
565 'ls', self._gs_path)
566 if ls_code != 0:
567 self.print(ls_error)
568 else:
569 self.print(ls_out)
Karen Qiandcad7492019-04-26 03:11:16 +0000570
Karen Qianccd2b4d2019-05-03 22:25:59 +0000571 # Check to see if folder already exists in gs
572 ls_out_set = set(ls_out.strip().splitlines())
573 if (dest_prefix + '/' in ls_out_set and
574 dest_prefix + '.ready' in ls_out_set):
575 print('Cache %s already exists.' % dest_prefix)
Karen Qiandcad7492019-04-26 03:11:16 +0000576 return
577
Andrii Shyshkalov46b91c02020-10-27 17:25:47 +0000578 # Reduce the number of individual files to download & write on disk.
579 self.RunGit(['pack-refs', '--all'])
580
Andrii Shyshkalov199182f2019-04-26 16:01:20 +0000581 # Run Garbage Collect to compress packfile.
Andrii Shyshkalovdcfe55f2019-09-21 03:35:39 +0000582 gc_args = ['gc', '--prune=all']
583 if gc_aggressive:
Michael Moss77480942020-06-22 18:32:37 +0000584 # The default "gc --aggressive" is often too aggressive for some machines,
585 # since it attempts to create as many threads as there are CPU cores,
586 # while not limiting per-thread memory usage, which puts too much pressure
587 # on RAM on high-core machines, causing them to thrash. Using lower-level
588 # commands gives more control over those settings.
589
590 # This might not be strictly necessary, but it's fast and is normally run
591 # by 'gc --aggressive', so it shouldn't hurt.
592 self.RunGit(['reflog', 'expire', '--all'])
593
594 # These are the default repack settings for 'gc --aggressive'.
595 gc_args = ['repack', '-d', '-l', '-f', '--depth=50', '--window=250', '-A',
596 '--unpack-unreachable=all']
597 # A 1G memory limit seems to provide comparable pack results as the
598 # default, even for our largest repos, while preventing runaway memory (at
599 # least on current Chromium builders which have about 4G RAM per core).
600 gc_args.append('--window-memory=1g')
601 # NOTE: It might also be possible to avoid thrashing with a larger window
602 # (e.g. "--window-memory=2g") by limiting the number of threads created
603 # (e.g. "--threads=[cores/2]"). Some limited testing didn't show much
604 # difference in outcomes on our current repos, but it might be worth
605 # trying if the repos grow much larger and the packs don't seem to be
606 # getting compressed enough.
Andrii Shyshkalovdcfe55f2019-09-21 03:35:39 +0000607 self.RunGit(gc_args)
Andrii Shyshkalov199182f2019-04-26 16:01:20 +0000608
Joanna Wang38d16732022-10-10 17:12:47 +0000609 self.print('running "gsutil -m rsync -r -d %s %s"' %
Joanna Wang2c54a192022-10-05 01:01:40 +0000610 (self.mirror_path, dest_prefix))
Joanna Wang38d16732022-10-10 17:12:47 +0000611 gsutil.call('-m', 'rsync', '-r', '-d', self.mirror_path, dest_prefix)
Karen Qiandcad7492019-04-26 03:11:16 +0000612
Karen Qianccd2b4d2019-05-03 22:25:59 +0000613 # Create .ready file and upload
Karen Qiandcad7492019-04-26 03:11:16 +0000614 _, ready_file_name = tempfile.mkstemp(suffix='.ready')
615 try:
Joanna Wang2c54a192022-10-05 01:01:40 +0000616 self.print('running "gsutil cp %s %s.ready"' %
617 (ready_file_name, dest_prefix))
Karen Qianccd2b4d2019-05-03 22:25:59 +0000618 gsutil.call('cp', ready_file_name, '%s.ready' % (dest_prefix))
Karen Qiandcad7492019-04-26 03:11:16 +0000619 finally:
620 os.remove(ready_file_name)
hinoka@chromium.orgc8444f32014-06-18 23:18:17 +0000621
Karen Qianccd2b4d2019-05-03 22:25:59 +0000622 # remove all other directory/.ready files in the same gs_path
623 # except for the directory/.ready file previously created
624 # which can be used for bootstrapping while the current one is
625 # being uploaded
626 if not prune:
627 return
628 prev_dest_prefix = self._GetMostRecentCacheDirectory(ls_out_set)
629 if not prev_dest_prefix:
630 return
631 for path in ls_out_set:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000632 if path in (prev_dest_prefix + '/', prev_dest_prefix + '.ready'):
Karen Qianccd2b4d2019-05-03 22:25:59 +0000633 continue
634 if path.endswith('.ready'):
635 gsutil.call('rm', path)
636 continue
637 gsutil.call('-m', 'rm', '-r', path)
638
639
szager@chromium.orgcdfcd7c2014-06-10 23:40:46 +0000640 @staticmethod
641 def DeleteTmpPackFiles(path):
642 pack_dir = os.path.join(path, 'objects', 'pack')
szager@chromium.org33418492014-06-18 19:03:39 +0000643 if not os.path.isdir(pack_dir):
644 return
szager@chromium.orgcdfcd7c2014-06-10 23:40:46 +0000645 pack_files = [f for f in os.listdir(pack_dir) if
646 f.startswith('.tmp-') or f.startswith('tmp_pack_')]
647 for f in pack_files:
648 f = os.path.join(pack_dir, f)
649 try:
650 os.remove(f)
Gavin Make6a62332020-12-04 21:57:10 +0000651 logging.warning('Deleted stale temporary pack file %s' % f)
szager@chromium.orgcdfcd7c2014-06-10 23:40:46 +0000652 except OSError:
Gavin Make6a62332020-12-04 21:57:10 +0000653 logging.warning('Unable to delete temporary pack file %s' % f)
szager@chromium.org174766f2014-05-13 21:27:46 +0000654
szager@chromium.org848fd492014-04-09 19:06:44 +0000655
agable@chromium.org5a306a22014-02-24 22:13:59 +0000656@subcommand.usage('[url of repo to check for caching]')
Edward Lesmescb047442021-05-06 20:18:49 +0000657@metrics.collector.collect_metrics('git cache exists')
agable@chromium.org5a306a22014-02-24 22:13:59 +0000658def CMDexists(parser, args):
659 """Check to see if there already is a cache of the given repo."""
szager@chromium.org848fd492014-04-09 19:06:44 +0000660 _, args = parser.parse_args(args)
agable@chromium.org5a306a22014-02-24 22:13:59 +0000661 if not len(args) == 1:
662 parser.error('git cache exists only takes exactly one repo url.')
663 url = args[0]
szager@chromium.org848fd492014-04-09 19:06:44 +0000664 mirror = Mirror(url)
665 if mirror.exists():
666 print(mirror.mirror_path)
agable@chromium.org5a306a22014-02-24 22:13:59 +0000667 return 0
668 return 1
669
670
hinoka@google.com563559c2014-04-02 00:36:24 +0000671@subcommand.usage('[url of repo to create a bootstrap zip file]')
Edward Lesmescb047442021-05-06 20:18:49 +0000672@metrics.collector.collect_metrics('git cache update-bootstrap')
hinoka@google.com563559c2014-04-02 00:36:24 +0000673def CMDupdate_bootstrap(parser, args):
674 """Create and uploads a bootstrap tarball."""
675 # Lets just assert we can't do this on Windows.
676 if sys.platform.startswith('win'):
szager@chromium.org848fd492014-04-09 19:06:44 +0000677 print('Sorry, update bootstrap will not work on Windows.', file=sys.stderr)
hinoka@google.com563559c2014-04-02 00:36:24 +0000678 return 1
679
Robert Iannucci0081c0f2019-09-29 08:30:54 +0000680 parser.add_option('--skip-populate', action='store_true',
681 help='Skips "populate" step if mirror already exists.')
Andrii Shyshkalovdcfe55f2019-09-21 03:35:39 +0000682 parser.add_option('--gc-aggressive', action='store_true',
683 help='Run aggressive repacking of the repo.')
hinoka@chromium.orgc8444f32014-06-18 23:18:17 +0000684 parser.add_option('--prune', action='store_true',
Andrii Shyshkalov7a2205c2019-04-26 05:14:36 +0000685 help='Prune all other cached bundles of the same repo.')
hinoka@chromium.orgc8444f32014-06-18 23:18:17 +0000686
hinoka@google.com563559c2014-04-02 00:36:24 +0000687 populate_args = args[:]
Robert Iannucci0081c0f2019-09-29 08:30:54 +0000688 options, args = parser.parse_args(args)
689 url = args[0]
690 mirror = Mirror(url)
691 if not options.skip_populate or not mirror.exists():
692 CMDpopulate(parser, populate_args)
693 else:
694 print('Skipped populate step.')
hinoka@google.com563559c2014-04-02 00:36:24 +0000695
696 # Get the repo directory.
Andrii Shyshkalovc50b0962019-11-21 23:03:18 +0000697 _, args2 = parser.parse_args(args)
698 url = args2[0]
szager@chromium.org848fd492014-04-09 19:06:44 +0000699 mirror = Mirror(url)
Joanna Wang5175d182022-12-07 17:27:57 +0000700 mirror.update_bootstrap(options.prune, options.gc_aggressive)
szager@chromium.org848fd492014-04-09 19:06:44 +0000701 return 0
hinoka@google.com563559c2014-04-02 00:36:24 +0000702
703
agable@chromium.org5a306a22014-02-24 22:13:59 +0000704@subcommand.usage('[url of repo to add to or update in cache]')
Edward Lesmescb047442021-05-06 20:18:49 +0000705@metrics.collector.collect_metrics('git cache populate')
agable@chromium.org5a306a22014-02-24 22:13:59 +0000706def CMDpopulate(parser, args):
707 """Ensure that the cache has all up-to-date objects for the given repo."""
708 parser.add_option('--depth', type='int',
709 help='Only cache DEPTH commits of history')
danakjc41f72c2019-11-05 17:12:01 +0000710 parser.add_option(
711 '--no-fetch-tags',
712 action='store_true',
713 help=('Don\'t fetch tags from the server. This can speed up '
714 'fetch considerably when there are many tags.'))
agable@chromium.org5a306a22014-02-24 22:13:59 +0000715 parser.add_option('--shallow', '-s', action='store_true',
716 help='Only cache 10000 commits of history')
717 parser.add_option('--ref', action='append',
718 help='Specify additional refs to be fetched')
Edward Lesmes07a68342021-04-20 23:39:30 +0000719 parser.add_option('--commit', action='append',
720 help='Specify additional commits to be fetched')
pgervais@chromium.orgb9f27512014-08-08 15:52:33 +0000721 parser.add_option('--no_bootstrap', '--no-bootstrap',
722 action='store_true',
hinoka@google.com563559c2014-04-02 00:36:24 +0000723 help='Don\'t bootstrap from Google Storage')
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000724 parser.add_option('--ignore_locks',
725 '--ignore-locks',
Vadim Shtayura08049e22017-10-11 00:14:52 +0000726 action='store_true',
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000727 help='NOOP. This flag will be removed in the future.')
Robert Iannucci09315982019-10-05 08:12:03 +0000728 parser.add_option('--break-locks',
729 action='store_true',
730 help='Break any existing lock instead of just ignoring it')
Edward Lemur579c9862018-07-13 23:17:51 +0000731 parser.add_option('--reset-fetch-config', action='store_true', default=False,
732 help='Reset the fetch config before populating the cache.')
hinoka@google.com563559c2014-04-02 00:36:24 +0000733
agable@chromium.org5a306a22014-02-24 22:13:59 +0000734 options, args = parser.parse_args(args)
agable@chromium.org5a306a22014-02-24 22:13:59 +0000735 if not len(args) == 1:
736 parser.error('git cache populate only takes exactly one repo url.')
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000737 if options.ignore_locks:
738 print('ignore_locks is no longer used. Please remove its usage.')
739 if options.break_locks:
740 print('break_locks is no longer used. Please remove its usage.')
agable@chromium.org5a306a22014-02-24 22:13:59 +0000741 url = args[0]
742
Edward Lesmes07a68342021-04-20 23:39:30 +0000743 mirror = Mirror(url, refs=options.ref, commits=options.commit)
szager@chromium.org848fd492014-04-09 19:06:44 +0000744 kwargs = {
danakjc41f72c2019-11-05 17:12:01 +0000745 'no_fetch_tags': options.no_fetch_tags,
szager@chromium.org848fd492014-04-09 19:06:44 +0000746 'verbose': options.verbose,
747 'shallow': options.shallow,
748 'bootstrap': not options.no_bootstrap,
Vadim Shtayura08049e22017-10-11 00:14:52 +0000749 'lock_timeout': options.timeout,
Edward Lemur579c9862018-07-13 23:17:51 +0000750 'reset_fetch_config': options.reset_fetch_config,
szager@chromium.org848fd492014-04-09 19:06:44 +0000751 }
agable@chromium.org5a306a22014-02-24 22:13:59 +0000752 if options.depth:
szager@chromium.org848fd492014-04-09 19:06:44 +0000753 kwargs['depth'] = options.depth
754 mirror.populate(**kwargs)
agable@chromium.org5a306a22014-02-24 22:13:59 +0000755
756
szager@chromium.orgf3145112014-08-07 21:02:36 +0000757@subcommand.usage('Fetch new commits into cache and current checkout')
Edward Lesmescb047442021-05-06 20:18:49 +0000758@metrics.collector.collect_metrics('git cache fetch')
szager@chromium.orgf3145112014-08-07 21:02:36 +0000759def CMDfetch(parser, args):
760 """Update mirror, and fetch in cwd."""
761 parser.add_option('--all', action='store_true', help='Fetch all remotes')
szager@chromium.org66c8b852015-09-22 23:19:07 +0000762 parser.add_option('--no_bootstrap', '--no-bootstrap',
763 action='store_true',
764 help='Don\'t (re)bootstrap from Google Storage')
danakjc41f72c2019-11-05 17:12:01 +0000765 parser.add_option(
766 '--no-fetch-tags',
767 action='store_true',
768 help=('Don\'t fetch tags from the server. This can speed up '
769 'fetch considerably when there are many tags.'))
szager@chromium.orgf3145112014-08-07 21:02:36 +0000770 options, args = parser.parse_args(args)
771
772 # Figure out which remotes to fetch. This mimics the behavior of regular
773 # 'git fetch'. Note that in the case of "stacked" or "pipelined" branches,
774 # this will NOT try to traverse up the branching structure to find the
775 # ultimate remote to update.
776 remotes = []
777 if options.all:
778 assert not args, 'fatal: fetch --all does not take a repository argument'
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000779 remotes = subprocess.check_output([Mirror.git_exe, 'remote'])
780 remotes = remotes.decode('utf-8', 'ignore').splitlines()
szager@chromium.orgf3145112014-08-07 21:02:36 +0000781 elif args:
782 remotes = args
783 else:
784 current_branch = subprocess.check_output(
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000785 [Mirror.git_exe, 'rev-parse', '--abbrev-ref', 'HEAD'])
786 current_branch = current_branch.decode('utf-8', 'ignore').strip()
szager@chromium.orgf3145112014-08-07 21:02:36 +0000787 if current_branch != 'HEAD':
788 upstream = subprocess.check_output(
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000789 [Mirror.git_exe, 'config', 'branch.%s.remote' % current_branch])
790 upstream = upstream.decode('utf-8', 'ignore').strip()
szager@chromium.orgf3145112014-08-07 21:02:36 +0000791 if upstream and upstream != '.':
792 remotes = [upstream]
793 if not remotes:
794 remotes = ['origin']
795
796 cachepath = Mirror.GetCachePath()
797 git_dir = os.path.abspath(subprocess.check_output(
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000798 [Mirror.git_exe, 'rev-parse', '--git-dir']).decode('utf-8', 'ignore'))
szager@chromium.orgf3145112014-08-07 21:02:36 +0000799 git_dir = os.path.abspath(git_dir)
800 if git_dir.startswith(cachepath):
801 mirror = Mirror.FromPath(git_dir)
szager@chromium.orgdbb6f822016-02-02 22:59:30 +0000802 mirror.populate(
danakjc41f72c2019-11-05 17:12:01 +0000803 bootstrap=not options.no_bootstrap,
804 no_fetch_tags=options.no_fetch_tags,
805 lock_timeout=options.timeout)
szager@chromium.orgf3145112014-08-07 21:02:36 +0000806 return 0
807 for remote in remotes:
808 remote_url = subprocess.check_output(
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000809 [Mirror.git_exe, 'config', 'remote.%s.url' % remote])
810 remote_url = remote_url.decode('utf-8', 'ignore').strip()
szager@chromium.orgf3145112014-08-07 21:02:36 +0000811 if remote_url.startswith(cachepath):
812 mirror = Mirror.FromPath(remote_url)
813 mirror.print = lambda *args: None
814 print('Updating git cache...')
szager@chromium.orgdbb6f822016-02-02 22:59:30 +0000815 mirror.populate(
danakjc41f72c2019-11-05 17:12:01 +0000816 bootstrap=not options.no_bootstrap,
817 no_fetch_tags=options.no_fetch_tags,
818 lock_timeout=options.timeout)
szager@chromium.orgf3145112014-08-07 21:02:36 +0000819 subprocess.check_call([Mirror.git_exe, 'fetch', remote])
820 return 0
821
822
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000823@subcommand.usage('do not use - it is a noop.')
Edward Lesmescb047442021-05-06 20:18:49 +0000824@metrics.collector.collect_metrics('git cache unlock')
Vadim Shtayura08049e22017-10-11 00:14:52 +0000825def CMDunlock(parser, args):
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000826 """This command does nothing."""
827 print('This command does nothing and will be removed in the future.')
Vadim Shtayura08049e22017-10-11 00:14:52 +0000828
829
agable@chromium.org5a306a22014-02-24 22:13:59 +0000830class OptionParser(optparse.OptionParser):
831 """Wrapper class for OptionParser to handle global options."""
832
833 def __init__(self, *args, **kwargs):
834 optparse.OptionParser.__init__(self, *args, prog='git cache', **kwargs)
835 self.add_option('-c', '--cache-dir',
Robert Iannuccia19649b2018-06-29 16:31:45 +0000836 help=(
837 'Path to the directory containing the caches. Normally '
838 'deduced from git config cache.cachepath or '
839 '$GIT_CACHE_PATH.'))
szager@chromium.org2c391af2014-05-23 09:07:15 +0000840 self.add_option('-v', '--verbose', action='count', default=1,
agable@chromium.org5a306a22014-02-24 22:13:59 +0000841 help='Increase verbosity (can be passed multiple times)')
szager@chromium.org2c391af2014-05-23 09:07:15 +0000842 self.add_option('-q', '--quiet', action='store_true',
843 help='Suppress all extraneous output')
Vadim Shtayura08049e22017-10-11 00:14:52 +0000844 self.add_option('--timeout', type='int', default=0,
845 help='Timeout for acquiring cache lock, in seconds')
agable@chromium.org5a306a22014-02-24 22:13:59 +0000846
847 def parse_args(self, args=None, values=None):
Edward Lesmescb047442021-05-06 20:18:49 +0000848 # Create an optparse.Values object that will store only the actual passed
849 # options, without the defaults.
850 actual_options = optparse.Values()
851 _, args = optparse.OptionParser.parse_args(self, args, actual_options)
852 # Create an optparse.Values object with the default options.
853 options = optparse.Values(self.get_default_values().__dict__)
854 # Update it with the options passed by the user.
855 options._update_careful(actual_options.__dict__)
856 # Store the options passed by the user in an _actual_options attribute.
857 # We store only the keys, and not the values, since the values can contain
858 # arbitrary information, which might be PII.
859 metrics.collector.add('arguments', list(actual_options.__dict__.keys()))
860
szager@chromium.org2c391af2014-05-23 09:07:15 +0000861 if options.quiet:
862 options.verbose = 0
863
864 levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
865 logging.basicConfig(level=levels[min(options.verbose, len(levels) - 1)])
agable@chromium.org5a306a22014-02-24 22:13:59 +0000866
867 try:
szager@chromium.org848fd492014-04-09 19:06:44 +0000868 global_cache_dir = Mirror.GetCachePath()
869 except RuntimeError:
870 global_cache_dir = None
871 if options.cache_dir:
872 if global_cache_dir and (
873 os.path.abspath(options.cache_dir) !=
874 os.path.abspath(global_cache_dir)):
Gavin Make6a62332020-12-04 21:57:10 +0000875 logging.warning('Overriding globally-configured cache directory.')
szager@chromium.org848fd492014-04-09 19:06:44 +0000876 Mirror.SetCachePath(options.cache_dir)
agable@chromium.org5a306a22014-02-24 22:13:59 +0000877
agable@chromium.org5a306a22014-02-24 22:13:59 +0000878 return options, args
879
880
881def main(argv):
882 dispatcher = subcommand.CommandDispatcher(__name__)
883 return dispatcher.execute(OptionParser(), argv)
884
885
886if __name__ == '__main__':
sbc@chromium.org013731e2015-02-26 18:28:43 +0000887 try:
Edward Lesmescb047442021-05-06 20:18:49 +0000888 with metrics.collector.print_notice_and_exit():
889 sys.exit(main(sys.argv[1:]))
sbc@chromium.org013731e2015-02-26 18:28:43 +0000890 except KeyboardInterrupt:
891 sys.stderr.write('interrupted\n')
Edward Lemurdf746d02019-07-27 00:42:46 +0000892 sys.exit(1)