blob: a76816da63ee4d66a13c695cee7cec90c9faf1b3 [file] [log] [blame]
Edward Lesmes98eda3f2019-08-12 21:09:53 +00001#!/usr/bin/env python
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
szager@chromium.org848fd492014-04-09 19:06:44 +000038try:
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -080039 # pylint: disable=undefined-variable
szager@chromium.org848fd492014-04-09 19:06:44 +000040 WinErr = WindowsError
41except NameError:
42 class WinErr(Exception):
43 pass
agable@chromium.org5a306a22014-02-24 22:13:59 +000044
hinokadcd84042016-06-09 14:26:17 -070045class ClobberNeeded(Exception):
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +000046 pass
agable@chromium.org5a306a22014-02-24 22:13:59 +000047
dnj4625b5a2016-11-10 18:23:26 -080048
49def exponential_backoff_retry(fn, excs=(Exception,), name=None, count=10,
50 sleep_time=0.25, printerr=None):
51 """Executes |fn| up to |count| times, backing off exponentially.
52
53 Args:
54 fn (callable): The function to execute. If this raises a handled
55 exception, the function will retry with exponential backoff.
56 excs (tuple): A tuple of Exception types to handle. If one of these is
57 raised by |fn|, a retry will be attempted. If |fn| raises an Exception
58 that is not in this list, it will immediately pass through. If |excs|
59 is empty, the Exception base class will be used.
60 name (str): Optional operation name to print in the retry string.
61 count (int): The number of times to try before allowing the exception to
62 pass through.
63 sleep_time (float): The initial number of seconds to sleep in between
64 retries. This will be doubled each retry.
65 printerr (callable): Function that will be called with the error string upon
66 failures. If None, |logging.warning| will be used.
67
68 Returns: The return value of the successful fn.
69 """
70 printerr = printerr or logging.warning
Edward Lesmes451e8ba2019-10-01 22:15:33 +000071 for i in range(count):
dnj4625b5a2016-11-10 18:23:26 -080072 try:
73 return fn()
74 except excs as e:
75 if (i+1) >= count:
76 raise
77
78 printerr('Retrying %s in %.2f second(s) (%d / %d attempts): %s' % (
79 (name or 'operation'), sleep_time, (i+1), count, e))
80 time.sleep(sleep_time)
81 sleep_time *= 2
82
83
szager@chromium.org848fd492014-04-09 19:06:44 +000084class Mirror(object):
85
86 git_exe = 'git.bat' if sys.platform.startswith('win') else 'git'
87 gsutil_exe = os.path.join(
hinoka@chromium.orgb091aa52014-12-20 01:47:31 +000088 os.path.dirname(os.path.abspath(__file__)), 'gsutil.py')
Vadim Shtayura08049e22017-10-11 00:14:52 +000089 cachepath_lock = threading.Lock()
szager@chromium.org848fd492014-04-09 19:06:44 +000090
Robert Iannuccia19649b2018-06-29 16:31:45 +000091 UNSET_CACHEPATH = object()
92
93 # Used for tests
94 _GIT_CONFIG_LOCATION = []
95
szager@chromium.org66c8b852015-09-22 23:19:07 +000096 @staticmethod
97 def parse_fetch_spec(spec):
98 """Parses and canonicalizes a fetch spec.
99
100 Returns (fetchspec, value_regex), where value_regex can be used
101 with 'git config --replace-all'.
102 """
103 parts = spec.split(':', 1)
104 src = parts[0].lstrip('+').rstrip('/')
105 if not src.startswith('refs/'):
106 src = 'refs/heads/%s' % src
107 dest = parts[1].rstrip('/') if len(parts) > 1 else src
108 regex = r'\+%s:.*' % src.replace('*', r'\*')
109 return ('+%s:%s' % (src, dest), regex)
110
Edward Lesmes07a68342021-04-20 23:39:30 +0000111 def __init__(self, url, refs=None, commits=None, print_func=None):
szager@chromium.org848fd492014-04-09 19:06:44 +0000112 self.url = url
szager@chromium.org66c8b852015-09-22 23:19:07 +0000113 self.fetch_specs = set([self.parse_fetch_spec(ref) for ref in (refs or [])])
Edward Lesmes07a68342021-04-20 23:39:30 +0000114 self.fetch_commits = set(commits or [])
szager@chromium.org848fd492014-04-09 19:06:44 +0000115 self.basedir = self.UrlToCacheDir(url)
116 self.mirror_path = os.path.join(self.GetCachePath(), self.basedir)
loislo@chromium.org0fb693f2014-12-25 15:28:22 +0000117 if print_func:
118 self.print = self.print_without_file
119 self.print_func = print_func
120 else:
121 self.print = print
122
dnj4625b5a2016-11-10 18:23:26 -0800123 def print_without_file(self, message, **_kwargs):
loislo@chromium.org0fb693f2014-12-25 15:28:22 +0000124 self.print_func(message)
szager@chromium.org848fd492014-04-09 19:06:44 +0000125
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800126 @contextlib.contextmanager
127 def print_duration_of(self, what):
128 start = time.time()
129 try:
130 yield
131 finally:
132 self.print('%s took %.1f minutes' % (what, (time.time() - start) / 60.0))
133
hinoka@chromium.orgf8fa23d2014-06-05 01:00:04 +0000134 @property
135 def bootstrap_bucket(self):
Andrii Shyshkalov4b79c382019-04-15 23:48:35 +0000136 b = os.getenv('OVERRIDE_BOOTSTRAP_BUCKET')
137 if b:
138 return b
Ryan Tseng3beabd02017-03-15 13:57:58 -0700139 u = urlparse.urlparse(self.url)
140 if u.netloc == 'chromium.googlesource.com':
hinoka@chromium.orgf8fa23d2014-06-05 01:00:04 +0000141 return 'chromium-git-cache'
Ryan Tseng3beabd02017-03-15 13:57:58 -0700142 # Not recognized.
143 return None
hinoka@chromium.orgf8fa23d2014-06-05 01:00:04 +0000144
Karen Qiandcad7492019-04-26 03:11:16 +0000145 @property
146 def _gs_path(self):
147 return 'gs://%s/v2/%s' % (self.bootstrap_bucket, self.basedir)
148
szager@chromium.org174766f2014-05-13 21:27:46 +0000149 @classmethod
150 def FromPath(cls, path):
151 return cls(cls.CacheDirToUrl(path))
152
szager@chromium.org848fd492014-04-09 19:06:44 +0000153 @staticmethod
154 def UrlToCacheDir(url):
155 """Convert a git url to a normalized form for the cache dir path."""
Edward Lemure9024d02019-11-19 18:47:46 +0000156 if os.path.isdir(url):
157 # Ignore the drive letter in Windows
158 url = os.path.splitdrive(url)[1]
159 return url.replace('-', '--').replace(os.sep, '-')
160
szager@chromium.org848fd492014-04-09 19:06:44 +0000161 parsed = urlparse.urlparse(url)
Edward Lemure9024d02019-11-19 18:47:46 +0000162 norm_url = parsed.netloc + parsed.path
szager@chromium.org848fd492014-04-09 19:06:44 +0000163 if norm_url.endswith('.git'):
164 norm_url = norm_url[:-len('.git')]
Dirk Prankedb589542019-04-12 21:07:01 +0000165
166 # Use the same dir for authenticated URLs and unauthenticated URLs.
167 norm_url = norm_url.replace('googlesource.com/a/', 'googlesource.com/')
168
szager@chromium.org848fd492014-04-09 19:06:44 +0000169 return norm_url.replace('-', '--').replace('/', '-').lower()
170
171 @staticmethod
szager@chromium.org174766f2014-05-13 21:27:46 +0000172 def CacheDirToUrl(path):
173 """Convert a cache dir path to its corresponding url."""
174 netpath = re.sub(r'\b-\b', '/', os.path.basename(path)).replace('--', '-')
175 return 'https://%s' % netpath
176
szager@chromium.org848fd492014-04-09 19:06:44 +0000177 @classmethod
178 def SetCachePath(cls, cachepath):
Vadim Shtayura08049e22017-10-11 00:14:52 +0000179 with cls.cachepath_lock:
180 setattr(cls, 'cachepath', cachepath)
szager@chromium.org848fd492014-04-09 19:06:44 +0000181
182 @classmethod
183 def GetCachePath(cls):
Vadim Shtayura08049e22017-10-11 00:14:52 +0000184 with cls.cachepath_lock:
185 if not hasattr(cls, 'cachepath'):
186 try:
187 cachepath = subprocess.check_output(
Robert Iannuccia19649b2018-06-29 16:31:45 +0000188 [cls.git_exe, 'config'] +
189 cls._GIT_CONFIG_LOCATION +
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000190 ['cache.cachepath']).decode('utf-8', 'ignore').strip()
Vadim Shtayura08049e22017-10-11 00:14:52 +0000191 except subprocess.CalledProcessError:
Robert Iannuccia19649b2018-06-29 16:31:45 +0000192 cachepath = os.environ.get('GIT_CACHE_PATH', cls.UNSET_CACHEPATH)
Vadim Shtayura08049e22017-10-11 00:14:52 +0000193 setattr(cls, 'cachepath', cachepath)
Robert Iannuccia19649b2018-06-29 16:31:45 +0000194
195 ret = getattr(cls, 'cachepath')
196 if ret is cls.UNSET_CACHEPATH:
197 raise RuntimeError('No cache.cachepath git configuration or '
198 '$GIT_CACHE_PATH is set.')
199 return ret
szager@chromium.org848fd492014-04-09 19:06:44 +0000200
Karen Qianccd2b4d2019-05-03 22:25:59 +0000201 @staticmethod
202 def _GetMostRecentCacheDirectory(ls_out_set):
203 ready_file_pattern = re.compile(r'.*/(\d+).ready$')
204 ready_dirs = []
205
206 for name in ls_out_set:
207 m = ready_file_pattern.match(name)
208 # Given <path>/<number>.ready,
209 # we are interested in <path>/<number> directory
210 if m and (name[:-len('.ready')] + '/') in ls_out_set:
211 ready_dirs.append((int(m.group(1)), name[:-len('.ready')]))
212
213 if not ready_dirs:
214 return None
215
216 return max(ready_dirs)[1]
217
dnj4625b5a2016-11-10 18:23:26 -0800218 def Rename(self, src, dst):
219 # This is somehow racy on Windows.
220 # Catching OSError because WindowsError isn't portable and
221 # pylint complains.
222 exponential_backoff_retry(
223 lambda: os.rename(src, dst),
224 excs=(OSError,),
225 name='rename [%s] => [%s]' % (src, dst),
226 printerr=self.print)
227
szager@chromium.org848fd492014-04-09 19:06:44 +0000228 def RunGit(self, cmd, **kwargs):
229 """Run git in a subprocess."""
230 cwd = kwargs.setdefault('cwd', self.mirror_path)
231 kwargs.setdefault('print_stdout', False)
232 kwargs.setdefault('filter_fn', self.print)
233 env = kwargs.get('env') or kwargs.setdefault('env', os.environ.copy())
234 env.setdefault('GIT_ASKPASS', 'true')
235 env.setdefault('SSH_ASKPASS', 'true')
236 self.print('running "git %s" in "%s"' % (' '.join(cmd), cwd))
237 gclient_utils.CheckCallAndFilter([self.git_exe] + cmd, **kwargs)
238
Edward Lemur579c9862018-07-13 23:17:51 +0000239 def config(self, cwd=None, reset_fetch_config=False):
szager@chromium.org848fd492014-04-09 19:06:44 +0000240 if cwd is None:
241 cwd = self.mirror_path
szager@chromium.org301a7c32014-06-16 17:13:50 +0000242
Edward Lemur579c9862018-07-13 23:17:51 +0000243 if reset_fetch_config:
Edward Lemur2f38df62018-07-14 02:13:21 +0000244 try:
245 self.RunGit(['config', '--unset-all', 'remote.origin.fetch'], cwd=cwd)
246 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:
254 self.RunGit(['config', 'gc.autodetach', '0'], cwd=cwd)
255 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():
263 self.RunGit(['config', 'gc.autopacklimit', '0'], cwd=cwd)
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".
szager@chromium.org848fd492014-04-09 19:06:44 +0000267 self.RunGit(['config', 'core.deltaBaseCacheLimit',
hinoka@chromium.org8e095af2015-06-10 19:19:07 +0000268 gclient_utils.DefaultDeltaBaseCacheLimit()], cwd=cwd)
szager@chromium.org301a7c32014-06-16 17:13:50 +0000269
hinoka@chromium.org8e095af2015-06-10 19:19:07 +0000270 self.RunGit(['config', 'remote.origin.url', self.url], cwd=cwd)
szager@chromium.org848fd492014-04-09 19:06:44 +0000271 self.RunGit(['config', '--replace-all', 'remote.origin.fetch',
hinoka@chromium.org8e095af2015-06-10 19:19:07 +0000272 '+refs/heads/*:refs/heads/*', r'\+refs/heads/\*:.*'], cwd=cwd)
szager@chromium.org66c8b852015-09-22 23:19:07 +0000273 for spec, value_regex in self.fetch_specs:
szager@chromium.org965c44f2014-08-19 21:19:19 +0000274 self.RunGit(
szager@chromium.org66c8b852015-09-22 23:19:07 +0000275 ['config', '--replace-all', 'remote.origin.fetch', spec, value_regex],
hinoka@chromium.org8e095af2015-06-10 19:19:07 +0000276 cwd=cwd)
szager@chromium.org848fd492014-04-09 19:06:44 +0000277
278 def bootstrap_repo(self, directory):
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800279 """Bootstrap the repo from Google Storage if possible.
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000280
281 More apt-ly named bootstrap_repo_from_cloud_if_possible_else_do_nothing().
282 """
Ryan Tseng3beabd02017-03-15 13:57:58 -0700283 if not self.bootstrap_bucket:
284 return False
szager@chromium.org848fd492014-04-09 19:06:44 +0000285
hinoka@chromium.org199bc5f2014-12-17 02:17:14 +0000286 gsutil = Gsutil(self.gsutil_exe, boto_path=None)
Yuwei Huanga1fbdff2019-02-01 21:51:15 +0000287
Karen Qian0cbd5a52019-04-29 20:14:50 +0000288 # Get the most recent version of the directory.
289 # This is determined from the most recent version of a .ready file.
290 # The .ready file is only uploaded when an entire directory has been
291 # uploaded to GS.
292 _, ls_out, ls_err = gsutil.check_call('ls', self._gs_path)
Karen Qianccd2b4d2019-05-03 22:25:59 +0000293 ls_out_set = set(ls_out.strip().splitlines())
294 latest_dir = self._GetMostRecentCacheDirectory(ls_out_set)
Yuwei Huanga1fbdff2019-02-01 21:51:15 +0000295
Karen Qianccd2b4d2019-05-03 22:25:59 +0000296 if not latest_dir:
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800297 self.print('No bootstrap file for %s found in %s, stderr:\n %s' %
298 (self.mirror_path, self.bootstrap_bucket,
Karen Qian0cbd5a52019-04-29 20:14:50 +0000299 ' '.join((ls_err or '').splitlines(True))))
szager@chromium.org848fd492014-04-09 19:06:44 +0000300 return False
szager@chromium.org848fd492014-04-09 19:06:44 +0000301
szager@chromium.org848fd492014-04-09 19:06:44 +0000302 try:
Karen Qian0cbd5a52019-04-29 20:14:50 +0000303 # create new temporary directory locally
szager@chromium.org1cbf1042014-06-17 18:26:24 +0000304 tempdir = tempfile.mkdtemp(prefix='_cache_tmp', dir=self.GetCachePath())
Josip Sokcevica40c1e12021-08-18 20:38:32 +0000305 self.RunGit(['init', '--bare'], cwd=tempdir)
Karen Qian0cbd5a52019-04-29 20:14:50 +0000306 self.print('Downloading files in %s/* into %s.' %
307 (latest_dir, tempdir))
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800308 with self.print_duration_of('download'):
Karen Qian0cbd5a52019-04-29 20:14:50 +0000309 code = gsutil.call('-m', 'cp', '-r', latest_dir + "/*",
310 tempdir)
szager@chromium.org848fd492014-04-09 19:06:44 +0000311 if code:
szager@chromium.org848fd492014-04-09 19:06:44 +0000312 return False
Josip Sokcevica40c1e12021-08-18 20:38:32 +0000313 # Set HEAD to main.
314 self.RunGit(['symbolic-ref', 'HEAD', 'refs/heads/main'], cwd=tempdir)
Josip Sokcevic67e12282020-12-16 17:12:45 +0000315 # A quick validation that all references are valid.
316 self.RunGit(['for-each-ref'], cwd=tempdir)
Karen Qian0cbd5a52019-04-29 20:14:50 +0000317 except Exception as e:
318 self.print('Encountered error: %s' % str(e), file=sys.stderr)
319 gclient_utils.rmtree(tempdir)
szager@chromium.org848fd492014-04-09 19:06:44 +0000320 return False
Karen Qian0cbd5a52019-04-29 20:14:50 +0000321 # delete the old directory
322 if os.path.exists(directory):
323 gclient_utils.rmtree(directory)
324 self.Rename(tempdir, directory)
szager@chromium.org848fd492014-04-09 19:06:44 +0000325 return True
326
Andrii Shyshkalov46a672b2017-11-24 18:04:43 -0800327 def contains_revision(self, revision):
328 if not self.exists():
329 return False
330
331 if sys.platform.startswith('win'):
332 # Windows .bat scripts use ^ as escape sequence, which means we have to
333 # escape it with itself for every .bat invocation.
334 needle = '%s^^^^{commit}' % revision
335 else:
336 needle = '%s^{commit}' % revision
337 try:
338 # cat-file exits with 0 on success, that is git object of given hash was
339 # found.
340 self.RunGit(['cat-file', '-e', needle])
341 return True
342 except subprocess.CalledProcessError:
343 return False
344
szager@chromium.org848fd492014-04-09 19:06:44 +0000345 def exists(self):
346 return os.path.isfile(os.path.join(self.mirror_path, 'config'))
347
Ryan Tseng3beabd02017-03-15 13:57:58 -0700348 def supported_project(self):
349 """Returns true if this repo is known to have a bootstrap zip file."""
350 u = urlparse.urlparse(self.url)
351 return u.netloc in [
352 'chromium.googlesource.com',
353 'chrome-internal.googlesource.com']
354
szager@chromium.org66c8b852015-09-22 23:19:07 +0000355 def _preserve_fetchspec(self):
356 """Read and preserve remote.origin.fetch from an existing mirror.
357
358 This modifies self.fetch_specs.
359 """
360 if not self.exists():
361 return
362 try:
363 config_fetchspecs = subprocess.check_output(
364 [self.git_exe, 'config', '--get-all', 'remote.origin.fetch'],
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000365 cwd=self.mirror_path).decode('utf-8', 'ignore')
szager@chromium.org66c8b852015-09-22 23:19:07 +0000366 for fetchspec in config_fetchspecs.splitlines():
367 self.fetch_specs.add(self.parse_fetch_spec(fetchspec))
368 except subprocess.CalledProcessError:
Gavin Make6a62332020-12-04 21:57:10 +0000369 logging.warning(
370 'Tried and failed to preserve remote.origin.fetch from the '
371 'existing cache directory. You may need to manually edit '
372 '%s and "git cache fetch" again.' %
373 os.path.join(self.mirror_path, 'config'))
szager@chromium.org66c8b852015-09-22 23:19:07 +0000374
Edward Lesmes34f71ab2020-03-25 21:24:00 +0000375 def _ensure_bootstrapped(
376 self, depth, bootstrap, reset_fetch_config, force=False):
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000377 pack_dir = os.path.join(self.mirror_path, 'objects', 'pack')
378 pack_files = []
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000379 if os.path.isdir(pack_dir):
380 pack_files = [f for f in os.listdir(pack_dir) if f.endswith('.pack')]
Edward Lesmes34f71ab2020-03-25 21:24:00 +0000381 self.print('%s has %d .pack files, re-bootstrapping if >%d or ==0' %
Karen Qian0cbd5a52019-04-29 20:14:50 +0000382 (self.mirror_path, len(pack_files), GC_AUTOPACKLIMIT))
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000383
384 should_bootstrap = (force or
szager@chromium.org66c8b852015-09-22 23:19:07 +0000385 not self.exists() or
Edward Lesmes34f71ab2020-03-25 21:24:00 +0000386 len(pack_files) > GC_AUTOPACKLIMIT or
387 len(pack_files) == 0)
Karen Qian0cbd5a52019-04-29 20:14:50 +0000388
389 if not should_bootstrap:
390 if depth and os.path.exists(os.path.join(self.mirror_path, 'shallow')):
Gavin Make6a62332020-12-04 21:57:10 +0000391 logging.warning(
Karen Qian0cbd5a52019-04-29 20:14:50 +0000392 'Shallow fetch requested, but repo cache already exists.')
393 return
394
Edward Lesmes34f71ab2020-03-25 21:24:00 +0000395 if not self.exists():
John Budorick47ec0692019-05-01 15:04:28 +0000396 if os.path.exists(self.mirror_path):
397 # If the mirror path exists but self.exists() returns false, we're
398 # in an unexpected state. Nuke the previous mirror directory and
399 # start fresh.
400 gclient_utils.rmtree(self.mirror_path)
Karen Qian0cbd5a52019-04-29 20:14:50 +0000401 os.mkdir(self.mirror_path)
Edward Lesmes34f71ab2020-03-25 21:24:00 +0000402 elif not reset_fetch_config:
403 # Re-bootstrapping an existing mirror; preserve existing fetch spec.
404 self._preserve_fetchspec()
Karen Qian0cbd5a52019-04-29 20:14:50 +0000405
406 bootstrapped = (not depth and bootstrap and
407 self.bootstrap_repo(self.mirror_path))
408
409 if not bootstrapped:
410 if not self.exists() or not self.supported_project():
411 # Bootstrap failed due to:
412 # 1. No previous cache.
413 # 2. Project doesn't have a bootstrap folder.
Ryan Tseng3beabd02017-03-15 13:57:58 -0700414 # Start with a bare git dir.
Josip Sokcevica40c1e12021-08-18 20:38:32 +0000415 self.RunGit(['init', '--bare'], cwd=self.mirror_path)
416 # Set HEAD to main. -b is introduced in 2.28 and may not be available
417 # everywhere.
418 self.RunGit(['symbolic-ref', 'HEAD', 'refs/heads/main'],
419 cwd=self.mirror_path)
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000420 else:
421 # Bootstrap failed, previous cache exists; warn and continue.
Gavin Make6a62332020-12-04 21:57:10 +0000422 logging.warning(
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800423 'Git cache has a lot of pack files (%d). Tried to re-bootstrap '
Gavin Make6a62332020-12-04 21:57:10 +0000424 'but failed. Continuing with non-optimized repository.' %
425 len(pack_files))
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000426
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000427 def _fetch(self,
428 rundir,
429 verbose,
430 depth,
431 no_fetch_tags,
432 reset_fetch_config,
433 prune=True):
Edward Lemur579c9862018-07-13 23:17:51 +0000434 self.config(rundir, reset_fetch_config)
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000435
436 fetch_cmd = ['fetch']
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000437 if verbose:
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000438 fetch_cmd.extend(['-v', '--progress'])
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000439 if depth:
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000440 fetch_cmd.extend(['--depth', str(depth)])
danakjc41f72c2019-11-05 17:12:01 +0000441 if no_fetch_tags:
Josip Sokcevic6afaa6c2020-05-08 18:20:17 +0000442 fetch_cmd.append('--no-tags')
443 if prune:
444 fetch_cmd.append('--prune')
445 fetch_cmd.append('origin')
446
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000447 fetch_specs = subprocess.check_output(
448 [self.git_exe, 'config', '--get-all', 'remote.origin.fetch'],
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000449 cwd=rundir).decode('utf-8', 'ignore').strip().splitlines()
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000450 for spec in fetch_specs:
451 try:
452 self.print('Fetching %s' % spec)
Andrii Shyshkalov4f56f232017-11-23 02:19:25 -0800453 with self.print_duration_of('fetch %s' % spec):
John Budorick3da78c42019-11-14 20:06:30 +0000454 self.RunGit(fetch_cmd + [spec], cwd=rundir, retry=True)
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000455 except subprocess.CalledProcessError:
456 if spec == '+refs/heads/*:refs/heads/*':
hinokadcd84042016-06-09 14:26:17 -0700457 raise ClobberNeeded() # Corrupted cache.
Gavin Make6a62332020-12-04 21:57:10 +0000458 logging.warning('Fetch of %s failed' % spec)
Edward Lesmes07a68342021-04-20 23:39:30 +0000459 for commit in self.fetch_commits:
460 self.print('Fetching %s' % commit)
461 try:
462 with self.print_duration_of('fetch %s' % commit):
463 self.RunGit(['fetch', 'origin', commit], cwd=rundir, retry=True)
464 except subprocess.CalledProcessError:
465 logging.warning('Fetch of %s failed' % commit)
hinoka@chromium.orgaa1e1a42014-06-26 21:58:51 +0000466
danakjc41f72c2019-11-05 17:12:01 +0000467 def populate(self,
468 depth=None,
469 no_fetch_tags=False,
470 shallow=False,
471 bootstrap=False,
472 verbose=False,
danakjc41f72c2019-11-05 17:12:01 +0000473 lock_timeout=0,
Edward Lemur579c9862018-07-13 23:17:51 +0000474 reset_fetch_config=False):
szager@chromium.orgb0a13a22014-06-18 00:52:25 +0000475 assert self.GetCachePath()
szager@chromium.org848fd492014-04-09 19:06:44 +0000476 if shallow and not depth:
477 depth = 10000
478 gclient_utils.safe_makedirs(self.GetCachePath())
479
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000480 with lockfile.lock(self.mirror_path, lock_timeout):
481 try:
482 self._ensure_bootstrapped(depth, bootstrap, reset_fetch_config)
483 self._fetch(self.mirror_path, verbose, depth, no_fetch_tags,
484 reset_fetch_config)
485 except ClobberNeeded:
486 # This is a major failure, we need to clean and force a bootstrap.
487 gclient_utils.rmtree(self.mirror_path)
488 self.print(GIT_CACHE_CORRUPT_MESSAGE)
489 self._ensure_bootstrapped(depth,
490 bootstrap,
491 reset_fetch_config,
492 force=True)
493 self._fetch(self.mirror_path, verbose, depth, no_fetch_tags,
494 reset_fetch_config)
szager@chromium.org848fd492014-04-09 19:06:44 +0000495
Josip Sokcevicee1a2c72021-08-09 21:09:08 +0000496 def update_bootstrap(self, prune=False, gc_aggressive=False, branch='main'):
Karen Qiandcad7492019-04-26 03:11:16 +0000497 # The folder is <git number>
szager@chromium.org848fd492014-04-09 19:06:44 +0000498 gen_number = subprocess.check_output(
Anthony Polito90b4c0f2020-11-17 18:09:21 +0000499 [self.git_exe, 'number', branch],
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000500 cwd=self.mirror_path).decode('utf-8', 'ignore').strip()
Karen Qiandcad7492019-04-26 03:11:16 +0000501 gsutil = Gsutil(path=self.gsutil_exe, boto_path=None)
502
503 src_name = self.mirror_path
Karen Qianccd2b4d2019-05-03 22:25:59 +0000504 dest_prefix = '%s/%s' % (self._gs_path, gen_number)
Karen Qiandcad7492019-04-26 03:11:16 +0000505
Karen Qianccd2b4d2019-05-03 22:25:59 +0000506 # ls_out lists contents in the format: gs://blah/blah/123...
507 _, ls_out, _ = gsutil.check_call('ls', self._gs_path)
Karen Qiandcad7492019-04-26 03:11:16 +0000508
Karen Qianccd2b4d2019-05-03 22:25:59 +0000509 # Check to see if folder already exists in gs
510 ls_out_set = set(ls_out.strip().splitlines())
511 if (dest_prefix + '/' in ls_out_set and
512 dest_prefix + '.ready' in ls_out_set):
513 print('Cache %s already exists.' % dest_prefix)
Karen Qiandcad7492019-04-26 03:11:16 +0000514 return
515
Andrii Shyshkalov46b91c02020-10-27 17:25:47 +0000516 # Reduce the number of individual files to download & write on disk.
517 self.RunGit(['pack-refs', '--all'])
518
Andrii Shyshkalov199182f2019-04-26 16:01:20 +0000519 # Run Garbage Collect to compress packfile.
Andrii Shyshkalovdcfe55f2019-09-21 03:35:39 +0000520 gc_args = ['gc', '--prune=all']
521 if gc_aggressive:
Michael Moss77480942020-06-22 18:32:37 +0000522 # The default "gc --aggressive" is often too aggressive for some machines,
523 # since it attempts to create as many threads as there are CPU cores,
524 # while not limiting per-thread memory usage, which puts too much pressure
525 # on RAM on high-core machines, causing them to thrash. Using lower-level
526 # commands gives more control over those settings.
527
528 # This might not be strictly necessary, but it's fast and is normally run
529 # by 'gc --aggressive', so it shouldn't hurt.
530 self.RunGit(['reflog', 'expire', '--all'])
531
532 # These are the default repack settings for 'gc --aggressive'.
533 gc_args = ['repack', '-d', '-l', '-f', '--depth=50', '--window=250', '-A',
534 '--unpack-unreachable=all']
535 # A 1G memory limit seems to provide comparable pack results as the
536 # default, even for our largest repos, while preventing runaway memory (at
537 # least on current Chromium builders which have about 4G RAM per core).
538 gc_args.append('--window-memory=1g')
539 # NOTE: It might also be possible to avoid thrashing with a larger window
540 # (e.g. "--window-memory=2g") by limiting the number of threads created
541 # (e.g. "--threads=[cores/2]"). Some limited testing didn't show much
542 # difference in outcomes on our current repos, but it might be worth
543 # trying if the repos grow much larger and the packs don't seem to be
544 # getting compressed enough.
Andrii Shyshkalovdcfe55f2019-09-21 03:35:39 +0000545 self.RunGit(gc_args)
Andrii Shyshkalov199182f2019-04-26 16:01:20 +0000546
Karen Qianccd2b4d2019-05-03 22:25:59 +0000547 gsutil.call('-m', 'cp', '-r', src_name, dest_prefix)
Karen Qiandcad7492019-04-26 03:11:16 +0000548
Karen Qianccd2b4d2019-05-03 22:25:59 +0000549 # Create .ready file and upload
Karen Qiandcad7492019-04-26 03:11:16 +0000550 _, ready_file_name = tempfile.mkstemp(suffix='.ready')
551 try:
Karen Qianccd2b4d2019-05-03 22:25:59 +0000552 gsutil.call('cp', ready_file_name, '%s.ready' % (dest_prefix))
Karen Qiandcad7492019-04-26 03:11:16 +0000553 finally:
554 os.remove(ready_file_name)
hinoka@chromium.orgc8444f32014-06-18 23:18:17 +0000555
Karen Qianccd2b4d2019-05-03 22:25:59 +0000556 # remove all other directory/.ready files in the same gs_path
557 # except for the directory/.ready file previously created
558 # which can be used for bootstrapping while the current one is
559 # being uploaded
560 if not prune:
561 return
562 prev_dest_prefix = self._GetMostRecentCacheDirectory(ls_out_set)
563 if not prev_dest_prefix:
564 return
565 for path in ls_out_set:
566 if (path == prev_dest_prefix + '/' or
567 path == prev_dest_prefix + '.ready'):
568 continue
569 if path.endswith('.ready'):
570 gsutil.call('rm', path)
571 continue
572 gsutil.call('-m', 'rm', '-r', path)
573
574
szager@chromium.orgcdfcd7c2014-06-10 23:40:46 +0000575 @staticmethod
576 def DeleteTmpPackFiles(path):
577 pack_dir = os.path.join(path, 'objects', 'pack')
szager@chromium.org33418492014-06-18 19:03:39 +0000578 if not os.path.isdir(pack_dir):
579 return
szager@chromium.orgcdfcd7c2014-06-10 23:40:46 +0000580 pack_files = [f for f in os.listdir(pack_dir) if
581 f.startswith('.tmp-') or f.startswith('tmp_pack_')]
582 for f in pack_files:
583 f = os.path.join(pack_dir, f)
584 try:
585 os.remove(f)
Gavin Make6a62332020-12-04 21:57:10 +0000586 logging.warning('Deleted stale temporary pack file %s' % f)
szager@chromium.orgcdfcd7c2014-06-10 23:40:46 +0000587 except OSError:
Gavin Make6a62332020-12-04 21:57:10 +0000588 logging.warning('Unable to delete temporary pack file %s' % f)
szager@chromium.org174766f2014-05-13 21:27:46 +0000589
szager@chromium.org848fd492014-04-09 19:06:44 +0000590
agable@chromium.org5a306a22014-02-24 22:13:59 +0000591@subcommand.usage('[url of repo to check for caching]')
Edward Lesmescb047442021-05-06 20:18:49 +0000592@metrics.collector.collect_metrics('git cache exists')
agable@chromium.org5a306a22014-02-24 22:13:59 +0000593def CMDexists(parser, args):
594 """Check to see if there already is a cache of the given repo."""
szager@chromium.org848fd492014-04-09 19:06:44 +0000595 _, args = parser.parse_args(args)
agable@chromium.org5a306a22014-02-24 22:13:59 +0000596 if not len(args) == 1:
597 parser.error('git cache exists only takes exactly one repo url.')
598 url = args[0]
szager@chromium.org848fd492014-04-09 19:06:44 +0000599 mirror = Mirror(url)
600 if mirror.exists():
601 print(mirror.mirror_path)
agable@chromium.org5a306a22014-02-24 22:13:59 +0000602 return 0
603 return 1
604
605
hinoka@google.com563559c2014-04-02 00:36:24 +0000606@subcommand.usage('[url of repo to create a bootstrap zip file]')
Edward Lesmescb047442021-05-06 20:18:49 +0000607@metrics.collector.collect_metrics('git cache update-bootstrap')
hinoka@google.com563559c2014-04-02 00:36:24 +0000608def CMDupdate_bootstrap(parser, args):
609 """Create and uploads a bootstrap tarball."""
610 # Lets just assert we can't do this on Windows.
611 if sys.platform.startswith('win'):
szager@chromium.org848fd492014-04-09 19:06:44 +0000612 print('Sorry, update bootstrap will not work on Windows.', file=sys.stderr)
hinoka@google.com563559c2014-04-02 00:36:24 +0000613 return 1
614
Robert Iannucci0081c0f2019-09-29 08:30:54 +0000615 parser.add_option('--skip-populate', action='store_true',
616 help='Skips "populate" step if mirror already exists.')
Andrii Shyshkalovdcfe55f2019-09-21 03:35:39 +0000617 parser.add_option('--gc-aggressive', action='store_true',
618 help='Run aggressive repacking of the repo.')
hinoka@chromium.orgc8444f32014-06-18 23:18:17 +0000619 parser.add_option('--prune', action='store_true',
Andrii Shyshkalov7a2205c2019-04-26 05:14:36 +0000620 help='Prune all other cached bundles of the same repo.')
Josip Sokcevicee1a2c72021-08-09 21:09:08 +0000621 parser.add_option('--branch', default='main',
622 help='Branch to use for bootstrap. (Default \'main\')')
hinoka@chromium.orgc8444f32014-06-18 23:18:17 +0000623
hinoka@google.com563559c2014-04-02 00:36:24 +0000624 populate_args = args[:]
Robert Iannucci0081c0f2019-09-29 08:30:54 +0000625 options, args = parser.parse_args(args)
626 url = args[0]
627 mirror = Mirror(url)
628 if not options.skip_populate or not mirror.exists():
629 CMDpopulate(parser, populate_args)
630 else:
631 print('Skipped populate step.')
hinoka@google.com563559c2014-04-02 00:36:24 +0000632
633 # Get the repo directory.
Andrii Shyshkalovc50b0962019-11-21 23:03:18 +0000634 _, args2 = parser.parse_args(args)
635 url = args2[0]
szager@chromium.org848fd492014-04-09 19:06:44 +0000636 mirror = Mirror(url)
Anthony Polito90b4c0f2020-11-17 18:09:21 +0000637 mirror.update_bootstrap(options.prune, options.gc_aggressive, options.branch)
szager@chromium.org848fd492014-04-09 19:06:44 +0000638 return 0
hinoka@google.com563559c2014-04-02 00:36:24 +0000639
640
agable@chromium.org5a306a22014-02-24 22:13:59 +0000641@subcommand.usage('[url of repo to add to or update in cache]')
Edward Lesmescb047442021-05-06 20:18:49 +0000642@metrics.collector.collect_metrics('git cache populate')
agable@chromium.org5a306a22014-02-24 22:13:59 +0000643def CMDpopulate(parser, args):
644 """Ensure that the cache has all up-to-date objects for the given repo."""
645 parser.add_option('--depth', type='int',
646 help='Only cache DEPTH commits of history')
danakjc41f72c2019-11-05 17:12:01 +0000647 parser.add_option(
648 '--no-fetch-tags',
649 action='store_true',
650 help=('Don\'t fetch tags from the server. This can speed up '
651 'fetch considerably when there are many tags.'))
agable@chromium.org5a306a22014-02-24 22:13:59 +0000652 parser.add_option('--shallow', '-s', action='store_true',
653 help='Only cache 10000 commits of history')
654 parser.add_option('--ref', action='append',
655 help='Specify additional refs to be fetched')
Edward Lesmes07a68342021-04-20 23:39:30 +0000656 parser.add_option('--commit', action='append',
657 help='Specify additional commits to be fetched')
pgervais@chromium.orgb9f27512014-08-08 15:52:33 +0000658 parser.add_option('--no_bootstrap', '--no-bootstrap',
659 action='store_true',
hinoka@google.com563559c2014-04-02 00:36:24 +0000660 help='Don\'t bootstrap from Google Storage')
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000661 parser.add_option('--ignore_locks',
662 '--ignore-locks',
Vadim Shtayura08049e22017-10-11 00:14:52 +0000663 action='store_true',
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000664 help='NOOP. This flag will be removed in the future.')
Robert Iannucci09315982019-10-05 08:12:03 +0000665 parser.add_option('--break-locks',
666 action='store_true',
667 help='Break any existing lock instead of just ignoring it')
Edward Lemur579c9862018-07-13 23:17:51 +0000668 parser.add_option('--reset-fetch-config', action='store_true', default=False,
669 help='Reset the fetch config before populating the cache.')
hinoka@google.com563559c2014-04-02 00:36:24 +0000670
agable@chromium.org5a306a22014-02-24 22:13:59 +0000671 options, args = parser.parse_args(args)
agable@chromium.org5a306a22014-02-24 22:13:59 +0000672 if not len(args) == 1:
673 parser.error('git cache populate only takes exactly one repo url.')
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000674 if options.ignore_locks:
675 print('ignore_locks is no longer used. Please remove its usage.')
676 if options.break_locks:
677 print('break_locks is no longer used. Please remove its usage.')
agable@chromium.org5a306a22014-02-24 22:13:59 +0000678 url = args[0]
679
Edward Lesmes07a68342021-04-20 23:39:30 +0000680 mirror = Mirror(url, refs=options.ref, commits=options.commit)
szager@chromium.org848fd492014-04-09 19:06:44 +0000681 kwargs = {
danakjc41f72c2019-11-05 17:12:01 +0000682 'no_fetch_tags': options.no_fetch_tags,
szager@chromium.org848fd492014-04-09 19:06:44 +0000683 'verbose': options.verbose,
684 'shallow': options.shallow,
685 'bootstrap': not options.no_bootstrap,
Vadim Shtayura08049e22017-10-11 00:14:52 +0000686 'lock_timeout': options.timeout,
Edward Lemur579c9862018-07-13 23:17:51 +0000687 'reset_fetch_config': options.reset_fetch_config,
szager@chromium.org848fd492014-04-09 19:06:44 +0000688 }
agable@chromium.org5a306a22014-02-24 22:13:59 +0000689 if options.depth:
szager@chromium.org848fd492014-04-09 19:06:44 +0000690 kwargs['depth'] = options.depth
691 mirror.populate(**kwargs)
agable@chromium.org5a306a22014-02-24 22:13:59 +0000692
693
szager@chromium.orgf3145112014-08-07 21:02:36 +0000694@subcommand.usage('Fetch new commits into cache and current checkout')
Edward Lesmescb047442021-05-06 20:18:49 +0000695@metrics.collector.collect_metrics('git cache fetch')
szager@chromium.orgf3145112014-08-07 21:02:36 +0000696def CMDfetch(parser, args):
697 """Update mirror, and fetch in cwd."""
698 parser.add_option('--all', action='store_true', help='Fetch all remotes')
szager@chromium.org66c8b852015-09-22 23:19:07 +0000699 parser.add_option('--no_bootstrap', '--no-bootstrap',
700 action='store_true',
701 help='Don\'t (re)bootstrap from Google Storage')
danakjc41f72c2019-11-05 17:12:01 +0000702 parser.add_option(
703 '--no-fetch-tags',
704 action='store_true',
705 help=('Don\'t fetch tags from the server. This can speed up '
706 'fetch considerably when there are many tags.'))
szager@chromium.orgf3145112014-08-07 21:02:36 +0000707 options, args = parser.parse_args(args)
708
709 # Figure out which remotes to fetch. This mimics the behavior of regular
710 # 'git fetch'. Note that in the case of "stacked" or "pipelined" branches,
711 # this will NOT try to traverse up the branching structure to find the
712 # ultimate remote to update.
713 remotes = []
714 if options.all:
715 assert not args, 'fatal: fetch --all does not take a repository argument'
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000716 remotes = subprocess.check_output([Mirror.git_exe, 'remote'])
717 remotes = remotes.decode('utf-8', 'ignore').splitlines()
szager@chromium.orgf3145112014-08-07 21:02:36 +0000718 elif args:
719 remotes = args
720 else:
721 current_branch = subprocess.check_output(
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000722 [Mirror.git_exe, 'rev-parse', '--abbrev-ref', 'HEAD'])
723 current_branch = current_branch.decode('utf-8', 'ignore').strip()
szager@chromium.orgf3145112014-08-07 21:02:36 +0000724 if current_branch != 'HEAD':
725 upstream = subprocess.check_output(
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000726 [Mirror.git_exe, 'config', 'branch.%s.remote' % current_branch])
727 upstream = upstream.decode('utf-8', 'ignore').strip()
szager@chromium.orgf3145112014-08-07 21:02:36 +0000728 if upstream and upstream != '.':
729 remotes = [upstream]
730 if not remotes:
731 remotes = ['origin']
732
733 cachepath = Mirror.GetCachePath()
734 git_dir = os.path.abspath(subprocess.check_output(
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000735 [Mirror.git_exe, 'rev-parse', '--git-dir']).decode('utf-8', 'ignore'))
szager@chromium.orgf3145112014-08-07 21:02:36 +0000736 git_dir = os.path.abspath(git_dir)
737 if git_dir.startswith(cachepath):
738 mirror = Mirror.FromPath(git_dir)
szager@chromium.orgdbb6f822016-02-02 22:59:30 +0000739 mirror.populate(
danakjc41f72c2019-11-05 17:12:01 +0000740 bootstrap=not options.no_bootstrap,
741 no_fetch_tags=options.no_fetch_tags,
742 lock_timeout=options.timeout)
szager@chromium.orgf3145112014-08-07 21:02:36 +0000743 return 0
744 for remote in remotes:
745 remote_url = subprocess.check_output(
Edward Lesmes4c3eb702020-03-25 21:09:30 +0000746 [Mirror.git_exe, 'config', 'remote.%s.url' % remote])
747 remote_url = remote_url.decode('utf-8', 'ignore').strip()
szager@chromium.orgf3145112014-08-07 21:02:36 +0000748 if remote_url.startswith(cachepath):
749 mirror = Mirror.FromPath(remote_url)
750 mirror.print = lambda *args: None
751 print('Updating git cache...')
szager@chromium.orgdbb6f822016-02-02 22:59:30 +0000752 mirror.populate(
danakjc41f72c2019-11-05 17:12:01 +0000753 bootstrap=not options.no_bootstrap,
754 no_fetch_tags=options.no_fetch_tags,
755 lock_timeout=options.timeout)
szager@chromium.orgf3145112014-08-07 21:02:36 +0000756 subprocess.check_call([Mirror.git_exe, 'fetch', remote])
757 return 0
758
759
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000760@subcommand.usage('do not use - it is a noop.')
Edward Lesmescb047442021-05-06 20:18:49 +0000761@metrics.collector.collect_metrics('git cache unlock')
Vadim Shtayura08049e22017-10-11 00:14:52 +0000762def CMDunlock(parser, args):
Josip Sokcevic14a83ae2020-05-21 01:36:34 +0000763 """This command does nothing."""
764 print('This command does nothing and will be removed in the future.')
Vadim Shtayura08049e22017-10-11 00:14:52 +0000765
766
agable@chromium.org5a306a22014-02-24 22:13:59 +0000767class OptionParser(optparse.OptionParser):
768 """Wrapper class for OptionParser to handle global options."""
769
770 def __init__(self, *args, **kwargs):
771 optparse.OptionParser.__init__(self, *args, prog='git cache', **kwargs)
772 self.add_option('-c', '--cache-dir',
Robert Iannuccia19649b2018-06-29 16:31:45 +0000773 help=(
774 'Path to the directory containing the caches. Normally '
775 'deduced from git config cache.cachepath or '
776 '$GIT_CACHE_PATH.'))
szager@chromium.org2c391af2014-05-23 09:07:15 +0000777 self.add_option('-v', '--verbose', action='count', default=1,
agable@chromium.org5a306a22014-02-24 22:13:59 +0000778 help='Increase verbosity (can be passed multiple times)')
szager@chromium.org2c391af2014-05-23 09:07:15 +0000779 self.add_option('-q', '--quiet', action='store_true',
780 help='Suppress all extraneous output')
Vadim Shtayura08049e22017-10-11 00:14:52 +0000781 self.add_option('--timeout', type='int', default=0,
782 help='Timeout for acquiring cache lock, in seconds')
agable@chromium.org5a306a22014-02-24 22:13:59 +0000783
784 def parse_args(self, args=None, values=None):
Edward Lesmescb047442021-05-06 20:18:49 +0000785 # Create an optparse.Values object that will store only the actual passed
786 # options, without the defaults.
787 actual_options = optparse.Values()
788 _, args = optparse.OptionParser.parse_args(self, args, actual_options)
789 # Create an optparse.Values object with the default options.
790 options = optparse.Values(self.get_default_values().__dict__)
791 # Update it with the options passed by the user.
792 options._update_careful(actual_options.__dict__)
793 # Store the options passed by the user in an _actual_options attribute.
794 # We store only the keys, and not the values, since the values can contain
795 # arbitrary information, which might be PII.
796 metrics.collector.add('arguments', list(actual_options.__dict__.keys()))
797
szager@chromium.org2c391af2014-05-23 09:07:15 +0000798 if options.quiet:
799 options.verbose = 0
800
801 levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
802 logging.basicConfig(level=levels[min(options.verbose, len(levels) - 1)])
agable@chromium.org5a306a22014-02-24 22:13:59 +0000803
804 try:
szager@chromium.org848fd492014-04-09 19:06:44 +0000805 global_cache_dir = Mirror.GetCachePath()
806 except RuntimeError:
807 global_cache_dir = None
808 if options.cache_dir:
809 if global_cache_dir and (
810 os.path.abspath(options.cache_dir) !=
811 os.path.abspath(global_cache_dir)):
Gavin Make6a62332020-12-04 21:57:10 +0000812 logging.warning('Overriding globally-configured cache directory.')
szager@chromium.org848fd492014-04-09 19:06:44 +0000813 Mirror.SetCachePath(options.cache_dir)
agable@chromium.org5a306a22014-02-24 22:13:59 +0000814
agable@chromium.org5a306a22014-02-24 22:13:59 +0000815 return options, args
816
817
818def main(argv):
819 dispatcher = subcommand.CommandDispatcher(__name__)
820 return dispatcher.execute(OptionParser(), argv)
821
822
823if __name__ == '__main__':
sbc@chromium.org013731e2015-02-26 18:28:43 +0000824 try:
Edward Lesmescb047442021-05-06 20:18:49 +0000825 with metrics.collector.print_notice_and_exit():
826 sys.exit(main(sys.argv[1:]))
sbc@chromium.org013731e2015-02-26 18:28:43 +0000827 except KeyboardInterrupt:
828 sys.stderr.write('interrupted\n')
Edward Lemurdf746d02019-07-27 00:42:46 +0000829 sys.exit(1)