blob: 816f415ac51290c61d526a1259b76c6fc25cbe41 [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
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -08008import contextlib
agable@chromium.org5a306a22014-02-24 22:13:59 +00009import logging
10import optparse
11import os
szager@chromium.org174766f2014-05-13 21:27:46 +000012import re
John Budorick47ec0692019-05-01 15:04:28 +000013import subprocess
14import sys
agable@chromium.org5a306a22014-02-24 22:13:59 +000015import tempfile
szager@chromium.org1132f5f2014-08-23 01:57:59 +000016import threading
pgervais@chromium.orgf3726102014-04-17 17:24:15 +000017import time
Gavin Makcc976552023-08-28 17:01:52 +000018import urllib.parse
Raul Tambreb946b232019-03-26 14:48:46 +000019
hinoka@google.com563559c2014-04-02 00:36:24 +000020from download_from_google_storage import Gsutil
agable@chromium.org5a306a22014-02-24 22:13:59 +000021import gclient_utils
Josip Sokcevic14a83ae2020-05-21 01:36:34 +000022import lockfile
Edward Lesmescb047442021-05-06 20:18:49 +000023import metrics
agable@chromium.org5a306a22014-02-24 22:13:59 +000024import subcommand
25
szager@chromium.org301a7c32014-06-16 17:13:50 +000026# Analogous to gc.autopacklimit git config.
27GC_AUTOPACKLIMIT = 50
Takuto Ikuta9fce2132017-12-14 10:44:28 +090028
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +000029GIT_CACHE_CORRUPT_MESSAGE = 'WARNING: The Git cache is corrupt.'
30
Josip Sokcevic604f1602021-10-15 15:45:10 +000031# gsutil creates many processes and threads. Creating too many gsutil cp
32# processes may result in running out of resources, and may perform worse due to
33# contextr switching. This limits how many concurrent gsutil cp processes
34# git_cache runs.
35GSUTIL_CP_SEMAPHORE = threading.Semaphore(2)
36
szager@chromium.org848fd492014-04-09 19:06:44 +000037try:
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -080038 # pylint: disable=undefined-variable
szager@chromium.org848fd492014-04-09 19:06:44 +000039 WinErr = WindowsError
40except NameError:
41 class WinErr(Exception):
42 pass
agable@chromium.org5a306a22014-02-24 22:13:59 +000043
hinokadcd84042016-06-09 14:26:17 -070044class ClobberNeeded(Exception):
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +000045 pass
agable@chromium.org5a306a22014-02-24 22:13:59 +000046
dnj4625b5a2016-11-10 18:23:26 -080047
48def exponential_backoff_retry(fn, excs=(Exception,), name=None, count=10,
49 sleep_time=0.25, printerr=None):
50 """Executes |fn| up to |count| times, backing off exponentially.
51
52 Args:
53 fn (callable): The function to execute. If this raises a handled
54 exception, the function will retry with exponential backoff.
55 excs (tuple): A tuple of Exception types to handle. If one of these is
56 raised by |fn|, a retry will be attempted. If |fn| raises an Exception
57 that is not in this list, it will immediately pass through. If |excs|
58 is empty, the Exception base class will be used.
59 name (str): Optional operation name to print in the retry string.
60 count (int): The number of times to try before allowing the exception to
61 pass through.
62 sleep_time (float): The initial number of seconds to sleep in between
63 retries. This will be doubled each retry.
64 printerr (callable): Function that will be called with the error string upon
65 failures. If None, |logging.warning| will be used.
66
67 Returns: The return value of the successful fn.
68 """
69 printerr = printerr or logging.warning
Edward Lesmes451e8ba2019-10-01 22:15:33 +000070 for i in range(count):
dnj4625b5a2016-11-10 18:23:26 -080071 try:
72 return fn()
73 except excs as e:
74 if (i+1) >= count:
75 raise
76
77 printerr('Retrying %s in %.2f second(s) (%d / %d attempts): %s' % (
78 (name or 'operation'), sleep_time, (i+1), count, e))
79 time.sleep(sleep_time)
80 sleep_time *= 2
81
82
szager@chromium.org848fd492014-04-09 19:06:44 +000083class Mirror(object):
84
85 git_exe = 'git.bat' if sys.platform.startswith('win') else 'git'
86 gsutil_exe = os.path.join(
hinoka@chromium.orgb091aa52014-12-20 01:47:31 +000087 os.path.dirname(os.path.abspath(__file__)), 'gsutil.py')
Vadim Shtayura08049e22017-10-11 00:14:52 +000088 cachepath_lock = threading.Lock()
szager@chromium.org848fd492014-04-09 19:06:44 +000089
Robert Iannuccia19649b2018-06-29 16:31:45 +000090 UNSET_CACHEPATH = object()
91
92 # Used for tests
93 _GIT_CONFIG_LOCATION = []
94
szager@chromium.org66c8b852015-09-22 23:19:07 +000095 @staticmethod
96 def parse_fetch_spec(spec):
97 """Parses and canonicalizes a fetch spec.
98
99 Returns (fetchspec, value_regex), where value_regex can be used
100 with 'git config --replace-all'.
101 """
102 parts = spec.split(':', 1)
103 src = parts[0].lstrip('+').rstrip('/')
104 if not src.startswith('refs/'):
105 src = 'refs/heads/%s' % src
106 dest = parts[1].rstrip('/') if len(parts) > 1 else src
107 regex = r'\+%s:.*' % src.replace('*', r'\*')
108 return ('+%s:%s' % (src, dest), regex)
109
Edward Lesmes07a68342021-04-20 23:39:30 +0000110 def __init__(self, url, refs=None, commits=None, print_func=None):
szager@chromium.org848fd492014-04-09 19:06:44 +0000111 self.url = url
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000112 self.fetch_specs = {self.parse_fetch_spec(ref) for ref in (refs or [])}
Edward Lesmes07a68342021-04-20 23:39:30 +0000113 self.fetch_commits = set(commits or [])
szager@chromium.org848fd492014-04-09 19:06:44 +0000114 self.basedir = self.UrlToCacheDir(url)
115 self.mirror_path = os.path.join(self.GetCachePath(), self.basedir)
loislo@chromium.org0fb693f2014-12-25 15:28:22 +0000116 if print_func:
117 self.print = self.print_without_file
118 self.print_func = print_func
119 else:
120 self.print = print
121
dnj4625b5a2016-11-10 18:23:26 -0800122 def print_without_file(self, message, **_kwargs):
loislo@chromium.org0fb693f2014-12-25 15:28:22 +0000123 self.print_func(message)
szager@chromium.org848fd492014-04-09 19:06:44 +0000124
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800125 @contextlib.contextmanager
126 def print_duration_of(self, what):
127 start = time.time()
128 try:
129 yield
130 finally:
131 self.print('%s took %.1f minutes' % (what, (time.time() - start) / 60.0))
132
hinoka@chromium.orgf8fa23d2014-06-05 01:00:04 +0000133 @property
134 def bootstrap_bucket(self):
Andrii Shyshkalov4b79c382019-04-15 23:48:35 +0000135 b = os.getenv('OVERRIDE_BOOTSTRAP_BUCKET')
136 if b:
137 return b
Gavin Makcc976552023-08-28 17:01:52 +0000138 u = urllib.parse.urlparse(self.url)
Ryan Tseng3beabd02017-03-15 13:57:58 -0700139 if u.netloc == 'chromium.googlesource.com':
hinoka@chromium.orgf8fa23d2014-06-05 01:00:04 +0000140 return 'chromium-git-cache'
Ryan Tseng3beabd02017-03-15 13:57:58 -0700141 # Not recognized.
142 return None
hinoka@chromium.orgf8fa23d2014-06-05 01:00:04 +0000143
Karen Qiandcad7492019-04-26 03:11:16 +0000144 @property
145 def _gs_path(self):
146 return 'gs://%s/v2/%s' % (self.bootstrap_bucket, self.basedir)
147
szager@chromium.org174766f2014-05-13 21:27:46 +0000148 @classmethod
149 def FromPath(cls, path):
150 return cls(cls.CacheDirToUrl(path))
151
szager@chromium.org848fd492014-04-09 19:06:44 +0000152 @staticmethod
153 def UrlToCacheDir(url):
154 """Convert a git url to a normalized form for the cache dir path."""
Edward Lemure9024d02019-11-19 18:47:46 +0000155 if os.path.isdir(url):
156 # Ignore the drive letter in Windows
157 url = os.path.splitdrive(url)[1]
158 return url.replace('-', '--').replace(os.sep, '-')
159
Gavin Makcc976552023-08-28 17:01:52 +0000160 parsed = urllib.parse.urlparse(url)
Edward Lemure9024d02019-11-19 18:47:46 +0000161 norm_url = parsed.netloc + parsed.path
szager@chromium.org848fd492014-04-09 19:06:44 +0000162 if norm_url.endswith('.git'):
163 norm_url = norm_url[:-len('.git')]
Dirk Prankedb589542019-04-12 21:07:01 +0000164
165 # Use the same dir for authenticated URLs and unauthenticated URLs.
166 norm_url = norm_url.replace('googlesource.com/a/', 'googlesource.com/')
167
szager@chromium.org848fd492014-04-09 19:06:44 +0000168 return norm_url.replace('-', '--').replace('/', '-').lower()
169
170 @staticmethod
szager@chromium.org174766f2014-05-13 21:27:46 +0000171 def CacheDirToUrl(path):
172 """Convert a cache dir path to its corresponding url."""
173 netpath = re.sub(r'\b-\b', '/', os.path.basename(path)).replace('--', '-')
174 return 'https://%s' % netpath
175
szager@chromium.org848fd492014-04-09 19:06:44 +0000176 @classmethod
177 def SetCachePath(cls, cachepath):
Vadim Shtayura08049e22017-10-11 00:14:52 +0000178 with cls.cachepath_lock:
179 setattr(cls, 'cachepath', cachepath)
szager@chromium.org848fd492014-04-09 19:06:44 +0000180
181 @classmethod
182 def GetCachePath(cls):
Vadim Shtayura08049e22017-10-11 00:14:52 +0000183 with cls.cachepath_lock:
184 if not hasattr(cls, 'cachepath'):
185 try:
186 cachepath = subprocess.check_output(
Robert Iannuccia19649b2018-06-29 16:31:45 +0000187 [cls.git_exe, 'config'] +
188 cls._GIT_CONFIG_LOCATION +
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000189 ['cache.cachepath']).decode('utf-8', 'ignore').strip()
Vadim Shtayura08049e22017-10-11 00:14:52 +0000190 except subprocess.CalledProcessError:
Robert Iannuccia19649b2018-06-29 16:31:45 +0000191 cachepath = os.environ.get('GIT_CACHE_PATH', cls.UNSET_CACHEPATH)
Vadim Shtayura08049e22017-10-11 00:14:52 +0000192 setattr(cls, 'cachepath', cachepath)
Robert Iannuccia19649b2018-06-29 16:31:45 +0000193
194 ret = getattr(cls, 'cachepath')
195 if ret is cls.UNSET_CACHEPATH:
196 raise RuntimeError('No cache.cachepath git configuration or '
197 '$GIT_CACHE_PATH is set.')
198 return ret
szager@chromium.org848fd492014-04-09 19:06:44 +0000199
Karen Qianccd2b4d2019-05-03 22:25:59 +0000200 @staticmethod
201 def _GetMostRecentCacheDirectory(ls_out_set):
202 ready_file_pattern = re.compile(r'.*/(\d+).ready$')
203 ready_dirs = []
204
205 for name in ls_out_set:
206 m = ready_file_pattern.match(name)
207 # Given <path>/<number>.ready,
208 # we are interested in <path>/<number> directory
209 if m and (name[:-len('.ready')] + '/') in ls_out_set:
210 ready_dirs.append((int(m.group(1)), name[:-len('.ready')]))
211
212 if not ready_dirs:
213 return None
214
215 return max(ready_dirs)[1]
216
dnj4625b5a2016-11-10 18:23:26 -0800217 def Rename(self, src, dst):
218 # This is somehow racy on Windows.
219 # Catching OSError because WindowsError isn't portable and
220 # pylint complains.
221 exponential_backoff_retry(
222 lambda: os.rename(src, dst),
223 excs=(OSError,),
224 name='rename [%s] => [%s]' % (src, dst),
225 printerr=self.print)
226
Josip Sokcevic650f8532021-10-15 18:35:31 +0000227 def RunGit(self, cmd, print_stdout=True, **kwargs):
szager@chromium.org848fd492014-04-09 19:06:44 +0000228 """Run git in a subprocess."""
229 cwd = kwargs.setdefault('cwd', self.mirror_path)
Joanna Wangea99f9a2023-08-17 02:20:43 +0000230 if "--git-dir" not in cmd:
231 cmd = ['--git-dir', os.path.abspath(cwd)] + cmd
232
szager@chromium.org848fd492014-04-09 19:06:44 +0000233 kwargs.setdefault('print_stdout', False)
Josip Sokcevic650f8532021-10-15 18:35:31 +0000234 if print_stdout:
235 kwargs.setdefault('filter_fn', self.print)
szager@chromium.org848fd492014-04-09 19:06:44 +0000236 env = kwargs.get('env') or kwargs.setdefault('env', os.environ.copy())
237 env.setdefault('GIT_ASKPASS', 'true')
238 env.setdefault('SSH_ASKPASS', 'true')
239 self.print('running "git %s" in "%s"' % (' '.join(cmd), cwd))
240 gclient_utils.CheckCallAndFilter([self.git_exe] + cmd, **kwargs)
241
Joanna Wangea99f9a2023-08-17 02:20:43 +0000242 def config(self, reset_fetch_config=False):
Edward Lemur579c9862018-07-13 23:17:51 +0000243 if reset_fetch_config:
Edward Lemur2f38df62018-07-14 02:13:21 +0000244 try:
Joanna Wangea99f9a2023-08-17 02:20:43 +0000245 self.RunGit(['config', '--unset-all', 'remote.origin.fetch'])
Edward Lemur2f38df62018-07-14 02:13:21 +0000246 except subprocess.CalledProcessError as e:
247 # If exit code was 5, it means we attempted to unset a config that
248 # didn't exist. Ignore it.
249 if e.returncode != 5:
250 raise
Edward Lemur579c9862018-07-13 23:17:51 +0000251
szager@chromium.org301a7c32014-06-16 17:13:50 +0000252 # Don't run git-gc in a daemon. Bad things can happen if it gets killed.
hinokadcd84042016-06-09 14:26:17 -0700253 try:
Joanna Wangea99f9a2023-08-17 02:20:43 +0000254 self.RunGit(['config', 'gc.autodetach', '0'])
hinokadcd84042016-06-09 14:26:17 -0700255 except subprocess.CalledProcessError:
256 # Hard error, need to clobber.
257 raise ClobberNeeded()
szager@chromium.org301a7c32014-06-16 17:13:50 +0000258
259 # Don't combine pack files into one big pack file. It's really slow for
260 # repositories, and there's no way to track progress and make sure it's
261 # not stuck.
Ryan Tseng3beabd02017-03-15 13:57:58 -0700262 if self.supported_project():
Joanna Wangea99f9a2023-08-17 02:20:43 +0000263 self.RunGit(['config', 'gc.autopacklimit', '0'])
szager@chromium.org301a7c32014-06-16 17:13:50 +0000264
265 # Allocate more RAM for cache-ing delta chains, for better performance
266 # of "Resolving deltas".
Joanna Wangea99f9a2023-08-17 02:20:43 +0000267 self.RunGit([
268 'config', 'core.deltaBaseCacheLimit',
269 gclient_utils.DefaultDeltaBaseCacheLimit()
270 ])
szager@chromium.org301a7c32014-06-16 17:13:50 +0000271
Joanna Wangea99f9a2023-08-17 02:20:43 +0000272 self.RunGit(['config', 'remote.origin.url', self.url])
273 self.RunGit([
274 'config', '--replace-all', 'remote.origin.fetch',
275 '+refs/heads/*:refs/heads/*', r'\+refs/heads/\*:.*'
276 ])
szager@chromium.org66c8b852015-09-22 23:19:07 +0000277 for spec, value_regex in self.fetch_specs:
szager@chromium.org965c44f2014-08-19 21:19:19 +0000278 self.RunGit(
Joanna Wangea99f9a2023-08-17 02:20:43 +0000279 ['config', '--replace-all', 'remote.origin.fetch', spec, value_regex])
szager@chromium.org848fd492014-04-09 19:06:44 +0000280
281 def bootstrap_repo(self, directory):
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800282 """Bootstrap the repo from Google Storage if possible.
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000283
284 More apt-ly named bootstrap_repo_from_cloud_if_possible_else_do_nothing().
285 """
Ryan Tseng3beabd02017-03-15 13:57:58 -0700286 if not self.bootstrap_bucket:
287 return False
szager@chromium.org848fd492014-04-09 19:06:44 +0000288
hinoka@chromium.org199bc5f2014-12-17 02:17:14 +0000289 gsutil = Gsutil(self.gsutil_exe, boto_path=None)
Yuwei Huanga1fbdff2019-02-01 21:51:15 +0000290
Karen Qian0cbd5a52019-04-29 20:14:50 +0000291 # Get the most recent version of the directory.
292 # This is determined from the most recent version of a .ready file.
293 # The .ready file is only uploaded when an entire directory has been
294 # uploaded to GS.
295 _, ls_out, ls_err = gsutil.check_call('ls', self._gs_path)
Karen Qianccd2b4d2019-05-03 22:25:59 +0000296 ls_out_set = set(ls_out.strip().splitlines())
297 latest_dir = self._GetMostRecentCacheDirectory(ls_out_set)
Yuwei Huanga1fbdff2019-02-01 21:51:15 +0000298
Karen Qianccd2b4d2019-05-03 22:25:59 +0000299 if not latest_dir:
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800300 self.print('No bootstrap file for %s found in %s, stderr:\n %s' %
301 (self.mirror_path, self.bootstrap_bucket,
Karen Qian0cbd5a52019-04-29 20:14:50 +0000302 ' '.join((ls_err or '').splitlines(True))))
szager@chromium.org848fd492014-04-09 19:06:44 +0000303 return False
szager@chromium.org848fd492014-04-09 19:06:44 +0000304
szager@chromium.org848fd492014-04-09 19:06:44 +0000305 try:
Karen Qian0cbd5a52019-04-29 20:14:50 +0000306 # create new temporary directory locally
szager@chromium.org1cbf1042014-06-17 18:26:24 +0000307 tempdir = tempfile.mkdtemp(prefix='_cache_tmp', dir=self.GetCachePath())
Josip Sokcevic5146d782023-08-29 18:06:01 +0000308 self.RunGit(['init', '-b', 'main', '--bare'], cwd=tempdir)
Karen Qian0cbd5a52019-04-29 20:14:50 +0000309 self.print('Downloading files in %s/* into %s.' %
310 (latest_dir, tempdir))
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800311 with self.print_duration_of('download'):
Josip Sokcevic604f1602021-10-15 15:45:10 +0000312 with GSUTIL_CP_SEMAPHORE:
313 code = gsutil.call('-m', 'cp', '-r', latest_dir + "/*",
314 tempdir)
szager@chromium.org848fd492014-04-09 19:06:44 +0000315 if code:
szager@chromium.org848fd492014-04-09 19:06:44 +0000316 return False
Josip Sokcevic67e12282020-12-16 17:12:45 +0000317 # A quick validation that all references are valid.
Josip Sokcevic650f8532021-10-15 18:35:31 +0000318 self.RunGit(['for-each-ref'], print_stdout=False, cwd=tempdir)
Karen Qian0cbd5a52019-04-29 20:14:50 +0000319 except Exception as e:
320 self.print('Encountered error: %s' % str(e), file=sys.stderr)
321 gclient_utils.rmtree(tempdir)
szager@chromium.org848fd492014-04-09 19:06:44 +0000322 return False
Karen Qian0cbd5a52019-04-29 20:14:50 +0000323 # delete the old directory
324 if os.path.exists(directory):
325 gclient_utils.rmtree(directory)
326 self.Rename(tempdir, directory)
szager@chromium.org848fd492014-04-09 19:06:44 +0000327 return True
328
Andrii Shyshkalov46a672b2017-11-24 18:04:43 -0800329 def contains_revision(self, revision):
330 if not self.exists():
331 return False
332
333 if sys.platform.startswith('win'):
334 # Windows .bat scripts use ^ as escape sequence, which means we have to
335 # escape it with itself for every .bat invocation.
336 needle = '%s^^^^{commit}' % revision
337 else:
338 needle = '%s^{commit}' % revision
339 try:
340 # cat-file exits with 0 on success, that is git object of given hash was
341 # found.
342 self.RunGit(['cat-file', '-e', needle])
343 return True
344 except subprocess.CalledProcessError:
Josip Sokcevic35061442022-01-12 00:32:54 +0000345 self.print('Commit with hash "%s" not found' % revision, file=sys.stderr)
Andrii Shyshkalov46a672b2017-11-24 18:04:43 -0800346 return False
347
szager@chromium.org848fd492014-04-09 19:06:44 +0000348 def exists(self):
349 return os.path.isfile(os.path.join(self.mirror_path, 'config'))
350
Ryan Tseng3beabd02017-03-15 13:57:58 -0700351 def supported_project(self):
352 """Returns true if this repo is known to have a bootstrap zip file."""
Gavin Makcc976552023-08-28 17:01:52 +0000353 u = urllib.parse.urlparse(self.url)
Ryan Tseng3beabd02017-03-15 13:57:58 -0700354 return u.netloc in [
355 'chromium.googlesource.com',
356 'chrome-internal.googlesource.com']
357
szager@chromium.org66c8b852015-09-22 23:19:07 +0000358 def _preserve_fetchspec(self):
359 """Read and preserve remote.origin.fetch from an existing mirror.
360
361 This modifies self.fetch_specs.
362 """
363 if not self.exists():
364 return
365 try:
366 config_fetchspecs = subprocess.check_output(
367 [self.git_exe, 'config', '--get-all', 'remote.origin.fetch'],
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000368 cwd=self.mirror_path).decode('utf-8', 'ignore')
szager@chromium.org66c8b852015-09-22 23:19:07 +0000369 for fetchspec in config_fetchspecs.splitlines():
370 self.fetch_specs.add(self.parse_fetch_spec(fetchspec))
371 except subprocess.CalledProcessError:
Gavin Make6a62332020-12-04 21:57:10 +0000372 logging.warning(
373 'Tried and failed to preserve remote.origin.fetch from the '
374 'existing cache directory. You may need to manually edit '
375 '%s and "git cache fetch" again.' %
376 os.path.join(self.mirror_path, 'config'))
szager@chromium.org66c8b852015-09-22 23:19:07 +0000377
Edward Lesmes34f71ab2020-03-25 21:24:00 +0000378 def _ensure_bootstrapped(
379 self, depth, bootstrap, reset_fetch_config, force=False):
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000380 pack_dir = os.path.join(self.mirror_path, 'objects', 'pack')
381 pack_files = []
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000382 if os.path.isdir(pack_dir):
383 pack_files = [f for f in os.listdir(pack_dir) if f.endswith('.pack')]
Edward Lesmes34f71ab2020-03-25 21:24:00 +0000384 self.print('%s has %d .pack files, re-bootstrapping if >%d or ==0' %
Karen Qian0cbd5a52019-04-29 20:14:50 +0000385 (self.mirror_path, len(pack_files), GC_AUTOPACKLIMIT))
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000386
Aravind Vasudevan6eccb0e2023-03-06 17:28:15 +0000387 # master->main branch migration left the cache in some builders to have its
388 # HEAD still pointing to refs/heads/master. This causes bot_update to fail.
389 # If in this state, delete the cache and force bootstrap.
390 try:
391 with open(os.path.join(self.mirror_path, 'HEAD')) as f:
392 head_ref = f.read()
393 except FileNotFoundError:
394 head_ref = ''
395
396 # Check only when HEAD points to master.
397 if 'master' in head_ref:
398 # Some repos could still have master so verify if the ref exists first.
399 show_ref_master_cmd = subprocess.run(
400 [Mirror.git_exe, 'show-ref', '--verify', 'refs/heads/master'],
401 cwd=self.mirror_path)
402
403 if show_ref_master_cmd.returncode != 0:
404 # Remove mirror
405 gclient_utils.rmtree(self.mirror_path)
406
407 # force bootstrap
408 force = True
409
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000410 should_bootstrap = (force or
szager@chromium.org66c8b852015-09-22 23:19:07 +0000411 not self.exists() or
Edward Lesmes34f71ab2020-03-25 21:24:00 +0000412 len(pack_files) > GC_AUTOPACKLIMIT or
413 len(pack_files) == 0)
Karen Qian0cbd5a52019-04-29 20:14:50 +0000414
415 if not should_bootstrap:
416 if depth and os.path.exists(os.path.join(self.mirror_path, 'shallow')):
Gavin Make6a62332020-12-04 21:57:10 +0000417 logging.warning(
Karen Qian0cbd5a52019-04-29 20:14:50 +0000418 'Shallow fetch requested, but repo cache already exists.')
419 return
420
Edward Lesmes34f71ab2020-03-25 21:24:00 +0000421 if not self.exists():
John Budorick47ec0692019-05-01 15:04:28 +0000422 if os.path.exists(self.mirror_path):
423 # If the mirror path exists but self.exists() returns false, we're
424 # in an unexpected state. Nuke the previous mirror directory and
425 # start fresh.
426 gclient_utils.rmtree(self.mirror_path)
Karen Qian0cbd5a52019-04-29 20:14:50 +0000427 os.mkdir(self.mirror_path)
Edward Lesmes34f71ab2020-03-25 21:24:00 +0000428 elif not reset_fetch_config:
429 # Re-bootstrapping an existing mirror; preserve existing fetch spec.
430 self._preserve_fetchspec()
Karen Qian0cbd5a52019-04-29 20:14:50 +0000431
432 bootstrapped = (not depth and bootstrap and
433 self.bootstrap_repo(self.mirror_path))
434
435 if not bootstrapped:
436 if not self.exists() or not self.supported_project():
437 # Bootstrap failed due to:
438 # 1. No previous cache.
439 # 2. Project doesn't have a bootstrap folder.
Ryan Tseng3beabd02017-03-15 13:57:58 -0700440 # Start with a bare git dir.
Joanna Wangea99f9a2023-08-17 02:20:43 +0000441 self.RunGit(['init', '--bare'])
Josip Sokcevica4b36022022-06-09 19:59:33 +0000442 # Set appropriate symbolic-ref
Joanna Wangea99f9a2023-08-17 02:20:43 +0000443 remote_info = exponential_backoff_retry(lambda: subprocess.check_output(
444 [
445 self.git_exe, '--git-dir',
446 os.path.abspath(self.mirror_path), 'remote', 'show', self.url
447 ],
448 cwd=self.mirror_path).decode('utf-8', 'ignore').strip())
Josip Sokcevica4b36022022-06-09 19:59:33 +0000449 default_branch_regexp = re.compile(r'HEAD branch: (.*)$')
450 m = default_branch_regexp.search(remote_info, re.MULTILINE)
451 if m:
Joanna Wangea99f9a2023-08-17 02:20:43 +0000452 self.RunGit(['symbolic-ref', 'HEAD', 'refs/heads/' + m.groups()[0]])
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000453 else:
454 # Bootstrap failed, previous cache exists; warn and continue.
Gavin Make6a62332020-12-04 21:57:10 +0000455 logging.warning(
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800456 'Git cache has a lot of pack files (%d). Tried to re-bootstrap '
Gavin Make6a62332020-12-04 21:57:10 +0000457 'but failed. Continuing with non-optimized repository.' %
458 len(pack_files))
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000459
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000460 def _fetch(self,
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000461 verbose,
462 depth,
463 no_fetch_tags,
464 reset_fetch_config,
465 prune=True):
Joanna Wangea99f9a2023-08-17 02:20:43 +0000466 self.config(reset_fetch_config)
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000467
468 fetch_cmd = ['fetch']
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000469 if verbose:
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000470 fetch_cmd.extend(['-v', '--progress'])
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000471 if depth:
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000472 fetch_cmd.extend(['--depth', str(depth)])
danakjc41f72c2019-11-05 17:12:01 +0000473 if no_fetch_tags:
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000474 fetch_cmd.append('--no-tags')
475 if prune:
476 fetch_cmd.append('--prune')
477 fetch_cmd.append('origin')
478
Joanna Wangea99f9a2023-08-17 02:20:43 +0000479 fetch_specs = subprocess.check_output([
480 self.git_exe, '--git-dir',
481 os.path.abspath(self.mirror_path), 'config', '--get-all',
482 'remote.origin.fetch'
483 ],
484 cwd=self.mirror_path).decode(
485 'utf-8',
486 'ignore').strip().splitlines()
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000487 for spec in fetch_specs:
488 try:
489 self.print('Fetching %s' % spec)
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800490 with self.print_duration_of('fetch %s' % spec):
Joanna Wangea99f9a2023-08-17 02:20:43 +0000491 self.RunGit(fetch_cmd + [spec], retry=True)
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000492 except subprocess.CalledProcessError:
493 if spec == '+refs/heads/*:refs/heads/*':
hinokadcd84042016-06-09 14:26:17 -0700494 raise ClobberNeeded() # Corrupted cache.
Gavin Make6a62332020-12-04 21:57:10 +0000495 logging.warning('Fetch of %s failed' % spec)
Edward Lesmes07a68342021-04-20 23:39:30 +0000496 for commit in self.fetch_commits:
497 self.print('Fetching %s' % commit)
498 try:
499 with self.print_duration_of('fetch %s' % commit):
Joanna Wangea99f9a2023-08-17 02:20:43 +0000500 self.RunGit(['fetch', 'origin', commit], retry=True)
Edward Lesmes07a68342021-04-20 23:39:30 +0000501 except subprocess.CalledProcessError:
502 logging.warning('Fetch of %s failed' % commit)
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000503
danakjc41f72c2019-11-05 17:12:01 +0000504 def populate(self,
505 depth=None,
506 no_fetch_tags=False,
507 shallow=False,
508 bootstrap=False,
509 verbose=False,
danakjc41f72c2019-11-05 17:12:01 +0000510 lock_timeout=0,
Edward Lemur579c9862018-07-13 23:17:51 +0000511 reset_fetch_config=False):
szager@chromium.orgb0a13a22014-06-18 00:52:25 +0000512 assert self.GetCachePath()
szager@chromium.org848fd492014-04-09 19:06:44 +0000513 if shallow and not depth:
514 depth = 10000
515 gclient_utils.safe_makedirs(self.GetCachePath())
516
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000517 with lockfile.lock(self.mirror_path, lock_timeout):
518 try:
519 self._ensure_bootstrapped(depth, bootstrap, reset_fetch_config)
Joanna Wangea99f9a2023-08-17 02:20:43 +0000520 self._fetch(verbose, depth, no_fetch_tags, reset_fetch_config)
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000521 except ClobberNeeded:
522 # This is a major failure, we need to clean and force a bootstrap.
523 gclient_utils.rmtree(self.mirror_path)
524 self.print(GIT_CACHE_CORRUPT_MESSAGE)
525 self._ensure_bootstrapped(depth,
526 bootstrap,
527 reset_fetch_config,
528 force=True)
Joanna Wangea99f9a2023-08-17 02:20:43 +0000529 self._fetch(verbose, depth, no_fetch_tags, reset_fetch_config)
szager@chromium.org848fd492014-04-09 19:06:44 +0000530
Joanna Wang5175d182022-12-07 17:27:57 +0000531 def update_bootstrap(self, prune=False, gc_aggressive=False):
Joanna Wang38d16732022-10-10 17:12:47 +0000532 # NOTE: There have been cases where repos were being recursively uploaded
533 # to google storage.
534 # E.g. `<host_url>-<repo>/<gen_number>/<host_url>-<repo>/` in GS and
535 # <host_url>-<repo>/<host_url>-<repo>/ on the bot.
536 # Check for recursed files on the bot here and remove them if found
537 # before we upload to GS.
538 # See crbug.com/1370443; keep this check until root cause is found.
539 recursed_dir = os.path.join(self.mirror_path,
Joanna Wang17cf81d2022-10-12 03:41:24 +0000540 self.mirror_path.split(os.path.sep)[-1])
Joanna Wang38d16732022-10-10 17:12:47 +0000541 if os.path.exists(recursed_dir):
542 self.print('Deleting unexpected directory: %s' % recursed_dir)
Josip Sokcevicd540d8b2022-10-12 18:43:49 +0000543 gclient_utils.rmtree(recursed_dir)
Joanna Wang38d16732022-10-10 17:12:47 +0000544
Karen Qiandcad7492019-04-26 03:11:16 +0000545 # The folder is <git number>
Joanna Wang5175d182022-12-07 17:27:57 +0000546 gen_number = subprocess.check_output([self.git_exe, 'number'],
547 cwd=self.mirror_path).decode(
548 'utf-8', 'ignore').strip()
Karen Qiandcad7492019-04-26 03:11:16 +0000549 gsutil = Gsutil(path=self.gsutil_exe, boto_path=None)
550
Karen Qianccd2b4d2019-05-03 22:25:59 +0000551 dest_prefix = '%s/%s' % (self._gs_path, gen_number)
Karen Qiandcad7492019-04-26 03:11:16 +0000552
Karen Qianccd2b4d2019-05-03 22:25:59 +0000553 # ls_out lists contents in the format: gs://blah/blah/123...
Joanna Wang5b5ee2d2022-10-12 17:18:22 +0000554 self.print('running "gsutil ls %s":' % self._gs_path)
Joanna Wang38d16732022-10-10 17:12:47 +0000555 ls_code, ls_out, ls_error = gsutil.check_call_with_retries(
556 'ls', self._gs_path)
557 if ls_code != 0:
558 self.print(ls_error)
559 else:
560 self.print(ls_out)
Karen Qiandcad7492019-04-26 03:11:16 +0000561
Karen Qianccd2b4d2019-05-03 22:25:59 +0000562 # Check to see if folder already exists in gs
563 ls_out_set = set(ls_out.strip().splitlines())
564 if (dest_prefix + '/' in ls_out_set and
565 dest_prefix + '.ready' in ls_out_set):
566 print('Cache %s already exists.' % dest_prefix)
Karen Qiandcad7492019-04-26 03:11:16 +0000567 return
568
Andrii Shyshkalov46b91c02020-10-27 17:25:47 +0000569 # Reduce the number of individual files to download & write on disk.
570 self.RunGit(['pack-refs', '--all'])
571
Andrii Shyshkalov199182f2019-04-26 16:01:20 +0000572 # Run Garbage Collect to compress packfile.
Andrii Shyshkalovdcfe55f2019-09-21 03:35:39 +0000573 gc_args = ['gc', '--prune=all']
574 if gc_aggressive:
Michael Moss77480942020-06-22 18:32:37 +0000575 # The default "gc --aggressive" is often too aggressive for some machines,
576 # since it attempts to create as many threads as there are CPU cores,
577 # while not limiting per-thread memory usage, which puts too much pressure
578 # on RAM on high-core machines, causing them to thrash. Using lower-level
579 # commands gives more control over those settings.
580
581 # This might not be strictly necessary, but it's fast and is normally run
582 # by 'gc --aggressive', so it shouldn't hurt.
583 self.RunGit(['reflog', 'expire', '--all'])
584
585 # These are the default repack settings for 'gc --aggressive'.
586 gc_args = ['repack', '-d', '-l', '-f', '--depth=50', '--window=250', '-A',
587 '--unpack-unreachable=all']
588 # A 1G memory limit seems to provide comparable pack results as the
589 # default, even for our largest repos, while preventing runaway memory (at
590 # least on current Chromium builders which have about 4G RAM per core).
591 gc_args.append('--window-memory=1g')
592 # NOTE: It might also be possible to avoid thrashing with a larger window
593 # (e.g. "--window-memory=2g") by limiting the number of threads created
594 # (e.g. "--threads=[cores/2]"). Some limited testing didn't show much
595 # difference in outcomes on our current repos, but it might be worth
596 # trying if the repos grow much larger and the packs don't seem to be
597 # getting compressed enough.
Andrii Shyshkalovdcfe55f2019-09-21 03:35:39 +0000598 self.RunGit(gc_args)
Andrii Shyshkalov199182f2019-04-26 16:01:20 +0000599
Joanna Wang38d16732022-10-10 17:12:47 +0000600 self.print('running "gsutil -m rsync -r -d %s %s"' %
Joanna Wang2c54a192022-10-05 01:01:40 +0000601 (self.mirror_path, dest_prefix))
Joanna Wang38d16732022-10-10 17:12:47 +0000602 gsutil.call('-m', 'rsync', '-r', '-d', self.mirror_path, dest_prefix)
Karen Qiandcad7492019-04-26 03:11:16 +0000603
Karen Qianccd2b4d2019-05-03 22:25:59 +0000604 # Create .ready file and upload
Karen Qiandcad7492019-04-26 03:11:16 +0000605 _, ready_file_name = tempfile.mkstemp(suffix='.ready')
606 try:
Joanna Wang2c54a192022-10-05 01:01:40 +0000607 self.print('running "gsutil cp %s %s.ready"' %
608 (ready_file_name, dest_prefix))
Karen Qianccd2b4d2019-05-03 22:25:59 +0000609 gsutil.call('cp', ready_file_name, '%s.ready' % (dest_prefix))
Karen Qiandcad7492019-04-26 03:11:16 +0000610 finally:
611 os.remove(ready_file_name)
hinoka@chromium.orgc8444f32014-06-18 23:18:17 +0000612
Karen Qianccd2b4d2019-05-03 22:25:59 +0000613 # remove all other directory/.ready files in the same gs_path
614 # except for the directory/.ready file previously created
615 # which can be used for bootstrapping while the current one is
616 # being uploaded
617 if not prune:
618 return
619 prev_dest_prefix = self._GetMostRecentCacheDirectory(ls_out_set)
620 if not prev_dest_prefix:
621 return
622 for path in ls_out_set:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000623 if path in (prev_dest_prefix + '/', prev_dest_prefix + '.ready'):
Karen Qianccd2b4d2019-05-03 22:25:59 +0000624 continue
625 if path.endswith('.ready'):
626 gsutil.call('rm', path)
627 continue
628 gsutil.call('-m', 'rm', '-r', path)
629
630
szager@chromium.orgcdfcd7c2014-06-10 23:40:46 +0000631 @staticmethod
632 def DeleteTmpPackFiles(path):
633 pack_dir = os.path.join(path, 'objects', 'pack')
szager@chromium.org33418492014-06-18 19:03:39 +0000634 if not os.path.isdir(pack_dir):
635 return
szager@chromium.orgcdfcd7c2014-06-10 23:40:46 +0000636 pack_files = [f for f in os.listdir(pack_dir) if
637 f.startswith('.tmp-') or f.startswith('tmp_pack_')]
638 for f in pack_files:
639 f = os.path.join(pack_dir, f)
640 try:
641 os.remove(f)
Gavin Make6a62332020-12-04 21:57:10 +0000642 logging.warning('Deleted stale temporary pack file %s' % f)
szager@chromium.orgcdfcd7c2014-06-10 23:40:46 +0000643 except OSError:
Gavin Make6a62332020-12-04 21:57:10 +0000644 logging.warning('Unable to delete temporary pack file %s' % f)
szager@chromium.org174766f2014-05-13 21:27:46 +0000645
szager@chromium.org848fd492014-04-09 19:06:44 +0000646
agable@chromium.org5a306a22014-02-24 22:13:59 +0000647@subcommand.usage('[url of repo to check for caching]')
Edward Lesmescb047442021-05-06 20:18:49 +0000648@metrics.collector.collect_metrics('git cache exists')
agable@chromium.org5a306a22014-02-24 22:13:59 +0000649def CMDexists(parser, args):
650 """Check to see if there already is a cache of the given repo."""
szager@chromium.org848fd492014-04-09 19:06:44 +0000651 _, args = parser.parse_args(args)
agable@chromium.org5a306a22014-02-24 22:13:59 +0000652 if not len(args) == 1:
653 parser.error('git cache exists only takes exactly one repo url.')
654 url = args[0]
szager@chromium.org848fd492014-04-09 19:06:44 +0000655 mirror = Mirror(url)
656 if mirror.exists():
657 print(mirror.mirror_path)
agable@chromium.org5a306a22014-02-24 22:13:59 +0000658 return 0
659 return 1
660
661
hinoka@google.com563559c2014-04-02 00:36:24 +0000662@subcommand.usage('[url of repo to create a bootstrap zip file]')
Edward Lesmescb047442021-05-06 20:18:49 +0000663@metrics.collector.collect_metrics('git cache update-bootstrap')
hinoka@google.com563559c2014-04-02 00:36:24 +0000664def CMDupdate_bootstrap(parser, args):
665 """Create and uploads a bootstrap tarball."""
666 # Lets just assert we can't do this on Windows.
667 if sys.platform.startswith('win'):
szager@chromium.org848fd492014-04-09 19:06:44 +0000668 print('Sorry, update bootstrap will not work on Windows.', file=sys.stderr)
hinoka@google.com563559c2014-04-02 00:36:24 +0000669 return 1
670
Robert Iannucci0081c0f2019-09-29 08:30:54 +0000671 parser.add_option('--skip-populate', action='store_true',
672 help='Skips "populate" step if mirror already exists.')
Andrii Shyshkalovdcfe55f2019-09-21 03:35:39 +0000673 parser.add_option('--gc-aggressive', action='store_true',
674 help='Run aggressive repacking of the repo.')
hinoka@chromium.orgc8444f32014-06-18 23:18:17 +0000675 parser.add_option('--prune', action='store_true',
Andrii Shyshkalov7a2205c2019-04-26 05:14:36 +0000676 help='Prune all other cached bundles of the same repo.')
hinoka@chromium.orgc8444f32014-06-18 23:18:17 +0000677
hinoka@google.com563559c2014-04-02 00:36:24 +0000678 populate_args = args[:]
Robert Iannucci0081c0f2019-09-29 08:30:54 +0000679 options, args = parser.parse_args(args)
680 url = args[0]
681 mirror = Mirror(url)
682 if not options.skip_populate or not mirror.exists():
683 CMDpopulate(parser, populate_args)
684 else:
685 print('Skipped populate step.')
hinoka@google.com563559c2014-04-02 00:36:24 +0000686
687 # Get the repo directory.
Andrii Shyshkalovc50b0962019-11-21 23:03:18 +0000688 _, args2 = parser.parse_args(args)
689 url = args2[0]
szager@chromium.org848fd492014-04-09 19:06:44 +0000690 mirror = Mirror(url)
Joanna Wang5175d182022-12-07 17:27:57 +0000691 mirror.update_bootstrap(options.prune, options.gc_aggressive)
szager@chromium.org848fd492014-04-09 19:06:44 +0000692 return 0
hinoka@google.com563559c2014-04-02 00:36:24 +0000693
694
agable@chromium.org5a306a22014-02-24 22:13:59 +0000695@subcommand.usage('[url of repo to add to or update in cache]')
Edward Lesmescb047442021-05-06 20:18:49 +0000696@metrics.collector.collect_metrics('git cache populate')
agable@chromium.org5a306a22014-02-24 22:13:59 +0000697def CMDpopulate(parser, args):
698 """Ensure that the cache has all up-to-date objects for the given repo."""
699 parser.add_option('--depth', type='int',
700 help='Only cache DEPTH commits of history')
danakjc41f72c2019-11-05 17:12:01 +0000701 parser.add_option(
702 '--no-fetch-tags',
703 action='store_true',
704 help=('Don\'t fetch tags from the server. This can speed up '
705 'fetch considerably when there are many tags.'))
agable@chromium.org5a306a22014-02-24 22:13:59 +0000706 parser.add_option('--shallow', '-s', action='store_true',
707 help='Only cache 10000 commits of history')
708 parser.add_option('--ref', action='append',
709 help='Specify additional refs to be fetched')
Edward Lesmes07a68342021-04-20 23:39:30 +0000710 parser.add_option('--commit', action='append',
711 help='Specify additional commits to be fetched')
pgervais@chromium.orgb9f27512014-08-08 15:52:33 +0000712 parser.add_option('--no_bootstrap', '--no-bootstrap',
713 action='store_true',
hinoka@google.com563559c2014-04-02 00:36:24 +0000714 help='Don\'t bootstrap from Google Storage')
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000715 parser.add_option('--ignore_locks',
716 '--ignore-locks',
Vadim Shtayura08049e22017-10-11 00:14:52 +0000717 action='store_true',
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000718 help='NOOP. This flag will be removed in the future.')
Robert Iannucci09315982019-10-05 08:12:03 +0000719 parser.add_option('--break-locks',
720 action='store_true',
721 help='Break any existing lock instead of just ignoring it')
Edward Lemur579c9862018-07-13 23:17:51 +0000722 parser.add_option('--reset-fetch-config', action='store_true', default=False,
723 help='Reset the fetch config before populating the cache.')
hinoka@google.com563559c2014-04-02 00:36:24 +0000724
agable@chromium.org5a306a22014-02-24 22:13:59 +0000725 options, args = parser.parse_args(args)
agable@chromium.org5a306a22014-02-24 22:13:59 +0000726 if not len(args) == 1:
727 parser.error('git cache populate only takes exactly one repo url.')
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000728 if options.ignore_locks:
729 print('ignore_locks is no longer used. Please remove its usage.')
730 if options.break_locks:
731 print('break_locks is no longer used. Please remove its usage.')
agable@chromium.org5a306a22014-02-24 22:13:59 +0000732 url = args[0]
733
Edward Lesmes07a68342021-04-20 23:39:30 +0000734 mirror = Mirror(url, refs=options.ref, commits=options.commit)
szager@chromium.org848fd492014-04-09 19:06:44 +0000735 kwargs = {
danakjc41f72c2019-11-05 17:12:01 +0000736 'no_fetch_tags': options.no_fetch_tags,
szager@chromium.org848fd492014-04-09 19:06:44 +0000737 'verbose': options.verbose,
738 'shallow': options.shallow,
739 'bootstrap': not options.no_bootstrap,
Vadim Shtayura08049e22017-10-11 00:14:52 +0000740 'lock_timeout': options.timeout,
Edward Lemur579c9862018-07-13 23:17:51 +0000741 'reset_fetch_config': options.reset_fetch_config,
szager@chromium.org848fd492014-04-09 19:06:44 +0000742 }
agable@chromium.org5a306a22014-02-24 22:13:59 +0000743 if options.depth:
szager@chromium.org848fd492014-04-09 19:06:44 +0000744 kwargs['depth'] = options.depth
745 mirror.populate(**kwargs)
agable@chromium.org5a306a22014-02-24 22:13:59 +0000746
747
szager@chromium.orgf3145112014-08-07 21:02:36 +0000748@subcommand.usage('Fetch new commits into cache and current checkout')
Edward Lesmescb047442021-05-06 20:18:49 +0000749@metrics.collector.collect_metrics('git cache fetch')
szager@chromium.orgf3145112014-08-07 21:02:36 +0000750def CMDfetch(parser, args):
751 """Update mirror, and fetch in cwd."""
752 parser.add_option('--all', action='store_true', help='Fetch all remotes')
szager@chromium.org66c8b852015-09-22 23:19:07 +0000753 parser.add_option('--no_bootstrap', '--no-bootstrap',
754 action='store_true',
755 help='Don\'t (re)bootstrap from Google Storage')
danakjc41f72c2019-11-05 17:12:01 +0000756 parser.add_option(
757 '--no-fetch-tags',
758 action='store_true',
759 help=('Don\'t fetch tags from the server. This can speed up '
760 'fetch considerably when there are many tags.'))
szager@chromium.orgf3145112014-08-07 21:02:36 +0000761 options, args = parser.parse_args(args)
762
763 # Figure out which remotes to fetch. This mimics the behavior of regular
764 # 'git fetch'. Note that in the case of "stacked" or "pipelined" branches,
765 # this will NOT try to traverse up the branching structure to find the
766 # ultimate remote to update.
767 remotes = []
768 if options.all:
769 assert not args, 'fatal: fetch --all does not take a repository argument'
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000770 remotes = subprocess.check_output([Mirror.git_exe, 'remote'])
771 remotes = remotes.decode('utf-8', 'ignore').splitlines()
szager@chromium.orgf3145112014-08-07 21:02:36 +0000772 elif args:
773 remotes = args
774 else:
775 current_branch = subprocess.check_output(
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000776 [Mirror.git_exe, 'rev-parse', '--abbrev-ref', 'HEAD'])
777 current_branch = current_branch.decode('utf-8', 'ignore').strip()
szager@chromium.orgf3145112014-08-07 21:02:36 +0000778 if current_branch != 'HEAD':
779 upstream = subprocess.check_output(
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000780 [Mirror.git_exe, 'config', 'branch.%s.remote' % current_branch])
781 upstream = upstream.decode('utf-8', 'ignore').strip()
szager@chromium.orgf3145112014-08-07 21:02:36 +0000782 if upstream and upstream != '.':
783 remotes = [upstream]
784 if not remotes:
785 remotes = ['origin']
786
787 cachepath = Mirror.GetCachePath()
788 git_dir = os.path.abspath(subprocess.check_output(
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000789 [Mirror.git_exe, 'rev-parse', '--git-dir']).decode('utf-8', 'ignore'))
szager@chromium.orgf3145112014-08-07 21:02:36 +0000790 git_dir = os.path.abspath(git_dir)
791 if git_dir.startswith(cachepath):
792 mirror = Mirror.FromPath(git_dir)
szager@chromium.orgdbb6f822016-02-02 22:59:30 +0000793 mirror.populate(
danakjc41f72c2019-11-05 17:12:01 +0000794 bootstrap=not options.no_bootstrap,
795 no_fetch_tags=options.no_fetch_tags,
796 lock_timeout=options.timeout)
szager@chromium.orgf3145112014-08-07 21:02:36 +0000797 return 0
798 for remote in remotes:
799 remote_url = subprocess.check_output(
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000800 [Mirror.git_exe, 'config', 'remote.%s.url' % remote])
801 remote_url = remote_url.decode('utf-8', 'ignore').strip()
szager@chromium.orgf3145112014-08-07 21:02:36 +0000802 if remote_url.startswith(cachepath):
803 mirror = Mirror.FromPath(remote_url)
804 mirror.print = lambda *args: None
805 print('Updating git cache...')
szager@chromium.orgdbb6f822016-02-02 22:59:30 +0000806 mirror.populate(
danakjc41f72c2019-11-05 17:12:01 +0000807 bootstrap=not options.no_bootstrap,
808 no_fetch_tags=options.no_fetch_tags,
809 lock_timeout=options.timeout)
szager@chromium.orgf3145112014-08-07 21:02:36 +0000810 subprocess.check_call([Mirror.git_exe, 'fetch', remote])
811 return 0
812
813
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000814@subcommand.usage('do not use - it is a noop.')
Edward Lesmescb047442021-05-06 20:18:49 +0000815@metrics.collector.collect_metrics('git cache unlock')
Vadim Shtayura08049e22017-10-11 00:14:52 +0000816def CMDunlock(parser, args):
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000817 """This command does nothing."""
818 print('This command does nothing and will be removed in the future.')
Vadim Shtayura08049e22017-10-11 00:14:52 +0000819
820
agable@chromium.org5a306a22014-02-24 22:13:59 +0000821class OptionParser(optparse.OptionParser):
822 """Wrapper class for OptionParser to handle global options."""
823
824 def __init__(self, *args, **kwargs):
825 optparse.OptionParser.__init__(self, *args, prog='git cache', **kwargs)
826 self.add_option('-c', '--cache-dir',
Robert Iannuccia19649b2018-06-29 16:31:45 +0000827 help=(
828 'Path to the directory containing the caches. Normally '
829 'deduced from git config cache.cachepath or '
830 '$GIT_CACHE_PATH.'))
szager@chromium.org2c391af2014-05-23 09:07:15 +0000831 self.add_option('-v', '--verbose', action='count', default=1,
agable@chromium.org5a306a22014-02-24 22:13:59 +0000832 help='Increase verbosity (can be passed multiple times)')
szager@chromium.org2c391af2014-05-23 09:07:15 +0000833 self.add_option('-q', '--quiet', action='store_true',
834 help='Suppress all extraneous output')
Vadim Shtayura08049e22017-10-11 00:14:52 +0000835 self.add_option('--timeout', type='int', default=0,
836 help='Timeout for acquiring cache lock, in seconds')
agable@chromium.org5a306a22014-02-24 22:13:59 +0000837
838 def parse_args(self, args=None, values=None):
Edward Lesmescb047442021-05-06 20:18:49 +0000839 # Create an optparse.Values object that will store only the actual passed
840 # options, without the defaults.
841 actual_options = optparse.Values()
842 _, args = optparse.OptionParser.parse_args(self, args, actual_options)
843 # Create an optparse.Values object with the default options.
844 options = optparse.Values(self.get_default_values().__dict__)
845 # Update it with the options passed by the user.
846 options._update_careful(actual_options.__dict__)
847 # Store the options passed by the user in an _actual_options attribute.
848 # We store only the keys, and not the values, since the values can contain
849 # arbitrary information, which might be PII.
850 metrics.collector.add('arguments', list(actual_options.__dict__.keys()))
851
szager@chromium.org2c391af2014-05-23 09:07:15 +0000852 if options.quiet:
853 options.verbose = 0
854
855 levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
856 logging.basicConfig(level=levels[min(options.verbose, len(levels) - 1)])
agable@chromium.org5a306a22014-02-24 22:13:59 +0000857
858 try:
szager@chromium.org848fd492014-04-09 19:06:44 +0000859 global_cache_dir = Mirror.GetCachePath()
860 except RuntimeError:
861 global_cache_dir = None
862 if options.cache_dir:
863 if global_cache_dir and (
864 os.path.abspath(options.cache_dir) !=
865 os.path.abspath(global_cache_dir)):
Gavin Make6a62332020-12-04 21:57:10 +0000866 logging.warning('Overriding globally-configured cache directory.')
szager@chromium.org848fd492014-04-09 19:06:44 +0000867 Mirror.SetCachePath(options.cache_dir)
agable@chromium.org5a306a22014-02-24 22:13:59 +0000868
agable@chromium.org5a306a22014-02-24 22:13:59 +0000869 return options, args
870
871
872def main(argv):
873 dispatcher = subcommand.CommandDispatcher(__name__)
874 return dispatcher.execute(OptionParser(), argv)
875
876
877if __name__ == '__main__':
sbc@chromium.org013731e2015-02-26 18:28:43 +0000878 try:
Edward Lesmescb047442021-05-06 20:18:49 +0000879 with metrics.collector.print_notice_and_exit():
880 sys.exit(main(sys.argv[1:]))
sbc@chromium.org013731e2015-02-26 18:28:43 +0000881 except KeyboardInterrupt:
882 sys.stderr.write('interrupted\n')
Edward Lemurdf746d02019-07-27 00:42:46 +0000883 sys.exit(1)