Josip Sokcevic | 4de5dea | 2022-03-23 21:15:14 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 2 | # Copyright 2014 The Chromium Authors. All rights reserved. |
| 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | |
| 6 | """A git command for managing a local cache of git repositories.""" |
| 7 | |
Andrii Shyshkalov | 4f56f23 | 2017-11-23 02:19:25 -0800 | [diff] [blame] | 8 | import contextlib |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 9 | import logging |
| 10 | import optparse |
| 11 | import os |
szager@chromium.org | 174766f | 2014-05-13 21:27:46 +0000 | [diff] [blame] | 12 | import re |
John Budorick | 47ec069 | 2019-05-01 15:04:28 +0000 | [diff] [blame] | 13 | import subprocess |
| 14 | import sys |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 15 | import tempfile |
szager@chromium.org | 1132f5f | 2014-08-23 01:57:59 +0000 | [diff] [blame] | 16 | import threading |
pgervais@chromium.org | f372610 | 2014-04-17 17:24:15 +0000 | [diff] [blame] | 17 | import time |
Gavin Mak | cc97655 | 2023-08-28 17:01:52 +0000 | [diff] [blame] | 18 | import urllib.parse |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 19 | |
hinoka@google.com | 563559c | 2014-04-02 00:36:24 +0000 | [diff] [blame] | 20 | from download_from_google_storage import Gsutil |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 21 | import gclient_utils |
Josip Sokcevic | 14a83ae | 2020-05-21 01:36:34 +0000 | [diff] [blame] | 22 | import lockfile |
Edward Lesmes | cb04744 | 2021-05-06 20:18:49 +0000 | [diff] [blame] | 23 | import metrics |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 24 | import subcommand |
| 25 | |
szager@chromium.org | 301a7c3 | 2014-06-16 17:13:50 +0000 | [diff] [blame] | 26 | # Analogous to gc.autopacklimit git config. |
| 27 | GC_AUTOPACKLIMIT = 50 |
Takuto Ikuta | 9fce213 | 2017-12-14 10:44:28 +0900 | [diff] [blame] | 28 | |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 29 | GIT_CACHE_CORRUPT_MESSAGE = 'WARNING: The Git cache is corrupt.' |
| 30 | |
Josip Sokcevic | 604f160 | 2021-10-15 15:45:10 +0000 | [diff] [blame] | 31 | # 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. |
| 35 | GSUTIL_CP_SEMAPHORE = threading.Semaphore(2) |
| 36 | |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 37 | try: |
Quinten Yearsley | b2cc4a9 | 2016-12-15 13:53:26 -0800 | [diff] [blame] | 38 | # pylint: disable=undefined-variable |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 39 | WinErr = WindowsError |
| 40 | except NameError: |
| 41 | class WinErr(Exception): |
| 42 | pass |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 43 | |
hinoka | dcd8404 | 2016-06-09 14:26:17 -0700 | [diff] [blame] | 44 | class ClobberNeeded(Exception): |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 45 | pass |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 46 | |
dnj | 4625b5a | 2016-11-10 18:23:26 -0800 | [diff] [blame] | 47 | |
| 48 | def 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 Lesmes | 451e8ba | 2019-10-01 22:15:33 +0000 | [diff] [blame] | 70 | for i in range(count): |
dnj | 4625b5a | 2016-11-10 18:23:26 -0800 | [diff] [blame] | 71 | 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.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 83 | class Mirror(object): |
| 84 | |
| 85 | git_exe = 'git.bat' if sys.platform.startswith('win') else 'git' |
| 86 | gsutil_exe = os.path.join( |
hinoka@chromium.org | b091aa5 | 2014-12-20 01:47:31 +0000 | [diff] [blame] | 87 | os.path.dirname(os.path.abspath(__file__)), 'gsutil.py') |
Vadim Shtayura | 08049e2 | 2017-10-11 00:14:52 +0000 | [diff] [blame] | 88 | cachepath_lock = threading.Lock() |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 89 | |
Robert Iannucci | a19649b | 2018-06-29 16:31:45 +0000 | [diff] [blame] | 90 | UNSET_CACHEPATH = object() |
| 91 | |
| 92 | # Used for tests |
| 93 | _GIT_CONFIG_LOCATION = [] |
| 94 | |
szager@chromium.org | 66c8b85 | 2015-09-22 23:19:07 +0000 | [diff] [blame] | 95 | @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 Lesmes | 07a6834 | 2021-04-20 23:39:30 +0000 | [diff] [blame] | 110 | def __init__(self, url, refs=None, commits=None, print_func=None): |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 111 | self.url = url |
Aravind Vasudevan | c5f0cbb | 2022-01-24 23:56:57 +0000 | [diff] [blame] | 112 | self.fetch_specs = {self.parse_fetch_spec(ref) for ref in (refs or [])} |
Edward Lesmes | 07a6834 | 2021-04-20 23:39:30 +0000 | [diff] [blame] | 113 | self.fetch_commits = set(commits or []) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 114 | self.basedir = self.UrlToCacheDir(url) |
| 115 | self.mirror_path = os.path.join(self.GetCachePath(), self.basedir) |
loislo@chromium.org | 0fb693f | 2014-12-25 15:28:22 +0000 | [diff] [blame] | 116 | if print_func: |
| 117 | self.print = self.print_without_file |
| 118 | self.print_func = print_func |
| 119 | else: |
| 120 | self.print = print |
| 121 | |
dnj | 4625b5a | 2016-11-10 18:23:26 -0800 | [diff] [blame] | 122 | def print_without_file(self, message, **_kwargs): |
loislo@chromium.org | 0fb693f | 2014-12-25 15:28:22 +0000 | [diff] [blame] | 123 | self.print_func(message) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 124 | |
Andrii Shyshkalov | 4f56f23 | 2017-11-23 02:19:25 -0800 | [diff] [blame] | 125 | @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.org | f8fa23d | 2014-06-05 01:00:04 +0000 | [diff] [blame] | 133 | @property |
| 134 | def bootstrap_bucket(self): |
Andrii Shyshkalov | 4b79c38 | 2019-04-15 23:48:35 +0000 | [diff] [blame] | 135 | b = os.getenv('OVERRIDE_BOOTSTRAP_BUCKET') |
| 136 | if b: |
| 137 | return b |
Gavin Mak | cc97655 | 2023-08-28 17:01:52 +0000 | [diff] [blame] | 138 | u = urllib.parse.urlparse(self.url) |
Ryan Tseng | 3beabd0 | 2017-03-15 13:57:58 -0700 | [diff] [blame] | 139 | if u.netloc == 'chromium.googlesource.com': |
hinoka@chromium.org | f8fa23d | 2014-06-05 01:00:04 +0000 | [diff] [blame] | 140 | return 'chromium-git-cache' |
Ryan Tseng | 3beabd0 | 2017-03-15 13:57:58 -0700 | [diff] [blame] | 141 | # Not recognized. |
| 142 | return None |
hinoka@chromium.org | f8fa23d | 2014-06-05 01:00:04 +0000 | [diff] [blame] | 143 | |
Karen Qian | dcad749 | 2019-04-26 03:11:16 +0000 | [diff] [blame] | 144 | @property |
| 145 | def _gs_path(self): |
| 146 | return 'gs://%s/v2/%s' % (self.bootstrap_bucket, self.basedir) |
| 147 | |
szager@chromium.org | 174766f | 2014-05-13 21:27:46 +0000 | [diff] [blame] | 148 | @classmethod |
| 149 | def FromPath(cls, path): |
| 150 | return cls(cls.CacheDirToUrl(path)) |
| 151 | |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 152 | @staticmethod |
| 153 | def UrlToCacheDir(url): |
| 154 | """Convert a git url to a normalized form for the cache dir path.""" |
Edward Lemur | e9024d0 | 2019-11-19 18:47:46 +0000 | [diff] [blame] | 155 | 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 Mak | cc97655 | 2023-08-28 17:01:52 +0000 | [diff] [blame] | 160 | parsed = urllib.parse.urlparse(url) |
Edward Lemur | e9024d0 | 2019-11-19 18:47:46 +0000 | [diff] [blame] | 161 | norm_url = parsed.netloc + parsed.path |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 162 | if norm_url.endswith('.git'): |
| 163 | norm_url = norm_url[:-len('.git')] |
Dirk Pranke | db58954 | 2019-04-12 21:07:01 +0000 | [diff] [blame] | 164 | |
| 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.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 168 | return norm_url.replace('-', '--').replace('/', '-').lower() |
| 169 | |
| 170 | @staticmethod |
szager@chromium.org | 174766f | 2014-05-13 21:27:46 +0000 | [diff] [blame] | 171 | 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.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 176 | @classmethod |
| 177 | def SetCachePath(cls, cachepath): |
Vadim Shtayura | 08049e2 | 2017-10-11 00:14:52 +0000 | [diff] [blame] | 178 | with cls.cachepath_lock: |
| 179 | setattr(cls, 'cachepath', cachepath) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 180 | |
| 181 | @classmethod |
| 182 | def GetCachePath(cls): |
Vadim Shtayura | 08049e2 | 2017-10-11 00:14:52 +0000 | [diff] [blame] | 183 | with cls.cachepath_lock: |
| 184 | if not hasattr(cls, 'cachepath'): |
| 185 | try: |
| 186 | cachepath = subprocess.check_output( |
Robert Iannucci | a19649b | 2018-06-29 16:31:45 +0000 | [diff] [blame] | 187 | [cls.git_exe, 'config'] + |
| 188 | cls._GIT_CONFIG_LOCATION + |
Edward Lesmes | 4c3eb70 | 2020-03-25 21:09:30 +0000 | [diff] [blame] | 189 | ['cache.cachepath']).decode('utf-8', 'ignore').strip() |
Vadim Shtayura | 08049e2 | 2017-10-11 00:14:52 +0000 | [diff] [blame] | 190 | except subprocess.CalledProcessError: |
Robert Iannucci | a19649b | 2018-06-29 16:31:45 +0000 | [diff] [blame] | 191 | cachepath = os.environ.get('GIT_CACHE_PATH', cls.UNSET_CACHEPATH) |
Vadim Shtayura | 08049e2 | 2017-10-11 00:14:52 +0000 | [diff] [blame] | 192 | setattr(cls, 'cachepath', cachepath) |
Robert Iannucci | a19649b | 2018-06-29 16:31:45 +0000 | [diff] [blame] | 193 | |
| 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.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 199 | |
Karen Qian | ccd2b4d | 2019-05-03 22:25:59 +0000 | [diff] [blame] | 200 | @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 | |
dnj | 4625b5a | 2016-11-10 18:23:26 -0800 | [diff] [blame] | 217 | 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 Sokcevic | 650f853 | 2021-10-15 18:35:31 +0000 | [diff] [blame] | 227 | def RunGit(self, cmd, print_stdout=True, **kwargs): |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 228 | """Run git in a subprocess.""" |
| 229 | cwd = kwargs.setdefault('cwd', self.mirror_path) |
Joanna Wang | ea99f9a | 2023-08-17 02:20:43 +0000 | [diff] [blame] | 230 | if "--git-dir" not in cmd: |
| 231 | cmd = ['--git-dir', os.path.abspath(cwd)] + cmd |
| 232 | |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 233 | kwargs.setdefault('print_stdout', False) |
Josip Sokcevic | 650f853 | 2021-10-15 18:35:31 +0000 | [diff] [blame] | 234 | if print_stdout: |
| 235 | kwargs.setdefault('filter_fn', self.print) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 236 | 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 Wang | ea99f9a | 2023-08-17 02:20:43 +0000 | [diff] [blame] | 242 | def config(self, reset_fetch_config=False): |
Edward Lemur | 579c986 | 2018-07-13 23:17:51 +0000 | [diff] [blame] | 243 | if reset_fetch_config: |
Edward Lemur | 2f38df6 | 2018-07-14 02:13:21 +0000 | [diff] [blame] | 244 | try: |
Joanna Wang | ea99f9a | 2023-08-17 02:20:43 +0000 | [diff] [blame] | 245 | self.RunGit(['config', '--unset-all', 'remote.origin.fetch']) |
Edward Lemur | 2f38df6 | 2018-07-14 02:13:21 +0000 | [diff] [blame] | 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 Lemur | 579c986 | 2018-07-13 23:17:51 +0000 | [diff] [blame] | 251 | |
szager@chromium.org | 301a7c3 | 2014-06-16 17:13:50 +0000 | [diff] [blame] | 252 | # Don't run git-gc in a daemon. Bad things can happen if it gets killed. |
hinoka | dcd8404 | 2016-06-09 14:26:17 -0700 | [diff] [blame] | 253 | try: |
Joanna Wang | ea99f9a | 2023-08-17 02:20:43 +0000 | [diff] [blame] | 254 | self.RunGit(['config', 'gc.autodetach', '0']) |
hinoka | dcd8404 | 2016-06-09 14:26:17 -0700 | [diff] [blame] | 255 | except subprocess.CalledProcessError: |
| 256 | # Hard error, need to clobber. |
| 257 | raise ClobberNeeded() |
szager@chromium.org | 301a7c3 | 2014-06-16 17:13:50 +0000 | [diff] [blame] | 258 | |
| 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 Tseng | 3beabd0 | 2017-03-15 13:57:58 -0700 | [diff] [blame] | 262 | if self.supported_project(): |
Joanna Wang | ea99f9a | 2023-08-17 02:20:43 +0000 | [diff] [blame] | 263 | self.RunGit(['config', 'gc.autopacklimit', '0']) |
szager@chromium.org | 301a7c3 | 2014-06-16 17:13:50 +0000 | [diff] [blame] | 264 | |
| 265 | # Allocate more RAM for cache-ing delta chains, for better performance |
| 266 | # of "Resolving deltas". |
Joanna Wang | ea99f9a | 2023-08-17 02:20:43 +0000 | [diff] [blame] | 267 | self.RunGit([ |
| 268 | 'config', 'core.deltaBaseCacheLimit', |
| 269 | gclient_utils.DefaultDeltaBaseCacheLimit() |
| 270 | ]) |
szager@chromium.org | 301a7c3 | 2014-06-16 17:13:50 +0000 | [diff] [blame] | 271 | |
Joanna Wang | ea99f9a | 2023-08-17 02:20:43 +0000 | [diff] [blame] | 272 | 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.org | 66c8b85 | 2015-09-22 23:19:07 +0000 | [diff] [blame] | 277 | for spec, value_regex in self.fetch_specs: |
szager@chromium.org | 965c44f | 2014-08-19 21:19:19 +0000 | [diff] [blame] | 278 | self.RunGit( |
Joanna Wang | ea99f9a | 2023-08-17 02:20:43 +0000 | [diff] [blame] | 279 | ['config', '--replace-all', 'remote.origin.fetch', spec, value_regex]) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 280 | |
| 281 | def bootstrap_repo(self, directory): |
Andrii Shyshkalov | 4f56f23 | 2017-11-23 02:19:25 -0800 | [diff] [blame] | 282 | """Bootstrap the repo from Google Storage if possible. |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 283 | |
| 284 | More apt-ly named bootstrap_repo_from_cloud_if_possible_else_do_nothing(). |
| 285 | """ |
Ryan Tseng | 3beabd0 | 2017-03-15 13:57:58 -0700 | [diff] [blame] | 286 | if not self.bootstrap_bucket: |
| 287 | return False |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 288 | |
hinoka@chromium.org | 199bc5f | 2014-12-17 02:17:14 +0000 | [diff] [blame] | 289 | gsutil = Gsutil(self.gsutil_exe, boto_path=None) |
Yuwei Huang | a1fbdff | 2019-02-01 21:51:15 +0000 | [diff] [blame] | 290 | |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 291 | # 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 Qian | ccd2b4d | 2019-05-03 22:25:59 +0000 | [diff] [blame] | 296 | ls_out_set = set(ls_out.strip().splitlines()) |
| 297 | latest_dir = self._GetMostRecentCacheDirectory(ls_out_set) |
Yuwei Huang | a1fbdff | 2019-02-01 21:51:15 +0000 | [diff] [blame] | 298 | |
Karen Qian | ccd2b4d | 2019-05-03 22:25:59 +0000 | [diff] [blame] | 299 | if not latest_dir: |
Andrii Shyshkalov | 4f56f23 | 2017-11-23 02:19:25 -0800 | [diff] [blame] | 300 | self.print('No bootstrap file for %s found in %s, stderr:\n %s' % |
| 301 | (self.mirror_path, self.bootstrap_bucket, |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 302 | ' '.join((ls_err or '').splitlines(True)))) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 303 | return False |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 304 | |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 305 | try: |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 306 | # create new temporary directory locally |
szager@chromium.org | 1cbf104 | 2014-06-17 18:26:24 +0000 | [diff] [blame] | 307 | tempdir = tempfile.mkdtemp(prefix='_cache_tmp', dir=self.GetCachePath()) |
Josip Sokcevic | a40c1e1 | 2021-08-18 20:38:32 +0000 | [diff] [blame] | 308 | self.RunGit(['init', '--bare'], cwd=tempdir) |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 309 | self.print('Downloading files in %s/* into %s.' % |
| 310 | (latest_dir, tempdir)) |
Andrii Shyshkalov | 4f56f23 | 2017-11-23 02:19:25 -0800 | [diff] [blame] | 311 | with self.print_duration_of('download'): |
Josip Sokcevic | 604f160 | 2021-10-15 15:45:10 +0000 | [diff] [blame] | 312 | with GSUTIL_CP_SEMAPHORE: |
| 313 | code = gsutil.call('-m', 'cp', '-r', latest_dir + "/*", |
| 314 | tempdir) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 315 | if code: |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 316 | return False |
Josip Sokcevic | a40c1e1 | 2021-08-18 20:38:32 +0000 | [diff] [blame] | 317 | # Set HEAD to main. |
| 318 | self.RunGit(['symbolic-ref', 'HEAD', 'refs/heads/main'], cwd=tempdir) |
Josip Sokcevic | 67e1228 | 2020-12-16 17:12:45 +0000 | [diff] [blame] | 319 | # A quick validation that all references are valid. |
Josip Sokcevic | 650f853 | 2021-10-15 18:35:31 +0000 | [diff] [blame] | 320 | self.RunGit(['for-each-ref'], print_stdout=False, cwd=tempdir) |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 321 | except Exception as e: |
| 322 | self.print('Encountered error: %s' % str(e), file=sys.stderr) |
| 323 | gclient_utils.rmtree(tempdir) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 324 | return False |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 325 | # delete the old directory |
| 326 | if os.path.exists(directory): |
| 327 | gclient_utils.rmtree(directory) |
| 328 | self.Rename(tempdir, directory) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 329 | return True |
| 330 | |
Andrii Shyshkalov | 46a672b | 2017-11-24 18:04:43 -0800 | [diff] [blame] | 331 | def contains_revision(self, revision): |
| 332 | if not self.exists(): |
| 333 | return False |
| 334 | |
| 335 | if sys.platform.startswith('win'): |
| 336 | # Windows .bat scripts use ^ as escape sequence, which means we have to |
| 337 | # escape it with itself for every .bat invocation. |
| 338 | needle = '%s^^^^{commit}' % revision |
| 339 | else: |
| 340 | needle = '%s^{commit}' % revision |
| 341 | try: |
| 342 | # cat-file exits with 0 on success, that is git object of given hash was |
| 343 | # found. |
| 344 | self.RunGit(['cat-file', '-e', needle]) |
| 345 | return True |
| 346 | except subprocess.CalledProcessError: |
Josip Sokcevic | 3506144 | 2022-01-12 00:32:54 +0000 | [diff] [blame] | 347 | self.print('Commit with hash "%s" not found' % revision, file=sys.stderr) |
Andrii Shyshkalov | 46a672b | 2017-11-24 18:04:43 -0800 | [diff] [blame] | 348 | return False |
| 349 | |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 350 | def exists(self): |
| 351 | return os.path.isfile(os.path.join(self.mirror_path, 'config')) |
| 352 | |
Ryan Tseng | 3beabd0 | 2017-03-15 13:57:58 -0700 | [diff] [blame] | 353 | def supported_project(self): |
| 354 | """Returns true if this repo is known to have a bootstrap zip file.""" |
Gavin Mak | cc97655 | 2023-08-28 17:01:52 +0000 | [diff] [blame] | 355 | u = urllib.parse.urlparse(self.url) |
Ryan Tseng | 3beabd0 | 2017-03-15 13:57:58 -0700 | [diff] [blame] | 356 | return u.netloc in [ |
| 357 | 'chromium.googlesource.com', |
| 358 | 'chrome-internal.googlesource.com'] |
| 359 | |
szager@chromium.org | 66c8b85 | 2015-09-22 23:19:07 +0000 | [diff] [blame] | 360 | def _preserve_fetchspec(self): |
| 361 | """Read and preserve remote.origin.fetch from an existing mirror. |
| 362 | |
| 363 | This modifies self.fetch_specs. |
| 364 | """ |
| 365 | if not self.exists(): |
| 366 | return |
| 367 | try: |
| 368 | config_fetchspecs = subprocess.check_output( |
| 369 | [self.git_exe, 'config', '--get-all', 'remote.origin.fetch'], |
Edward Lesmes | 4c3eb70 | 2020-03-25 21:09:30 +0000 | [diff] [blame] | 370 | cwd=self.mirror_path).decode('utf-8', 'ignore') |
szager@chromium.org | 66c8b85 | 2015-09-22 23:19:07 +0000 | [diff] [blame] | 371 | for fetchspec in config_fetchspecs.splitlines(): |
| 372 | self.fetch_specs.add(self.parse_fetch_spec(fetchspec)) |
| 373 | except subprocess.CalledProcessError: |
Gavin Mak | e6a6233 | 2020-12-04 21:57:10 +0000 | [diff] [blame] | 374 | logging.warning( |
| 375 | 'Tried and failed to preserve remote.origin.fetch from the ' |
| 376 | 'existing cache directory. You may need to manually edit ' |
| 377 | '%s and "git cache fetch" again.' % |
| 378 | os.path.join(self.mirror_path, 'config')) |
szager@chromium.org | 66c8b85 | 2015-09-22 23:19:07 +0000 | [diff] [blame] | 379 | |
Edward Lesmes | 34f71ab | 2020-03-25 21:24:00 +0000 | [diff] [blame] | 380 | def _ensure_bootstrapped( |
| 381 | self, depth, bootstrap, reset_fetch_config, force=False): |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 382 | pack_dir = os.path.join(self.mirror_path, 'objects', 'pack') |
| 383 | pack_files = [] |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 384 | if os.path.isdir(pack_dir): |
| 385 | pack_files = [f for f in os.listdir(pack_dir) if f.endswith('.pack')] |
Edward Lesmes | 34f71ab | 2020-03-25 21:24:00 +0000 | [diff] [blame] | 386 | self.print('%s has %d .pack files, re-bootstrapping if >%d or ==0' % |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 387 | (self.mirror_path, len(pack_files), GC_AUTOPACKLIMIT)) |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 388 | |
Aravind Vasudevan | 6eccb0e | 2023-03-06 17:28:15 +0000 | [diff] [blame] | 389 | # master->main branch migration left the cache in some builders to have its |
| 390 | # HEAD still pointing to refs/heads/master. This causes bot_update to fail. |
| 391 | # If in this state, delete the cache and force bootstrap. |
| 392 | try: |
| 393 | with open(os.path.join(self.mirror_path, 'HEAD')) as f: |
| 394 | head_ref = f.read() |
| 395 | except FileNotFoundError: |
| 396 | head_ref = '' |
| 397 | |
| 398 | # Check only when HEAD points to master. |
| 399 | if 'master' in head_ref: |
| 400 | # Some repos could still have master so verify if the ref exists first. |
| 401 | show_ref_master_cmd = subprocess.run( |
| 402 | [Mirror.git_exe, 'show-ref', '--verify', 'refs/heads/master'], |
| 403 | cwd=self.mirror_path) |
| 404 | |
| 405 | if show_ref_master_cmd.returncode != 0: |
| 406 | # Remove mirror |
| 407 | gclient_utils.rmtree(self.mirror_path) |
| 408 | |
| 409 | # force bootstrap |
| 410 | force = True |
| 411 | |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 412 | should_bootstrap = (force or |
szager@chromium.org | 66c8b85 | 2015-09-22 23:19:07 +0000 | [diff] [blame] | 413 | not self.exists() or |
Edward Lesmes | 34f71ab | 2020-03-25 21:24:00 +0000 | [diff] [blame] | 414 | len(pack_files) > GC_AUTOPACKLIMIT or |
| 415 | len(pack_files) == 0) |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 416 | |
| 417 | if not should_bootstrap: |
| 418 | if depth and os.path.exists(os.path.join(self.mirror_path, 'shallow')): |
Gavin Mak | e6a6233 | 2020-12-04 21:57:10 +0000 | [diff] [blame] | 419 | logging.warning( |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 420 | 'Shallow fetch requested, but repo cache already exists.') |
| 421 | return |
| 422 | |
Edward Lesmes | 34f71ab | 2020-03-25 21:24:00 +0000 | [diff] [blame] | 423 | if not self.exists(): |
John Budorick | 47ec069 | 2019-05-01 15:04:28 +0000 | [diff] [blame] | 424 | if os.path.exists(self.mirror_path): |
| 425 | # If the mirror path exists but self.exists() returns false, we're |
| 426 | # in an unexpected state. Nuke the previous mirror directory and |
| 427 | # start fresh. |
| 428 | gclient_utils.rmtree(self.mirror_path) |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 429 | os.mkdir(self.mirror_path) |
Edward Lesmes | 34f71ab | 2020-03-25 21:24:00 +0000 | [diff] [blame] | 430 | elif not reset_fetch_config: |
| 431 | # Re-bootstrapping an existing mirror; preserve existing fetch spec. |
| 432 | self._preserve_fetchspec() |
Karen Qian | 0cbd5a5 | 2019-04-29 20:14:50 +0000 | [diff] [blame] | 433 | |
| 434 | bootstrapped = (not depth and bootstrap and |
| 435 | self.bootstrap_repo(self.mirror_path)) |
| 436 | |
| 437 | if not bootstrapped: |
| 438 | if not self.exists() or not self.supported_project(): |
| 439 | # Bootstrap failed due to: |
| 440 | # 1. No previous cache. |
| 441 | # 2. Project doesn't have a bootstrap folder. |
Ryan Tseng | 3beabd0 | 2017-03-15 13:57:58 -0700 | [diff] [blame] | 442 | # Start with a bare git dir. |
Joanna Wang | ea99f9a | 2023-08-17 02:20:43 +0000 | [diff] [blame] | 443 | self.RunGit(['init', '--bare']) |
Josip Sokcevic | a4b3602 | 2022-06-09 19:59:33 +0000 | [diff] [blame] | 444 | # Set appropriate symbolic-ref |
Joanna Wang | ea99f9a | 2023-08-17 02:20:43 +0000 | [diff] [blame] | 445 | remote_info = exponential_backoff_retry(lambda: subprocess.check_output( |
| 446 | [ |
| 447 | self.git_exe, '--git-dir', |
| 448 | os.path.abspath(self.mirror_path), 'remote', 'show', self.url |
| 449 | ], |
| 450 | cwd=self.mirror_path).decode('utf-8', 'ignore').strip()) |
Josip Sokcevic | a4b3602 | 2022-06-09 19:59:33 +0000 | [diff] [blame] | 451 | default_branch_regexp = re.compile(r'HEAD branch: (.*)$') |
| 452 | m = default_branch_regexp.search(remote_info, re.MULTILINE) |
| 453 | if m: |
Joanna Wang | ea99f9a | 2023-08-17 02:20:43 +0000 | [diff] [blame] | 454 | self.RunGit(['symbolic-ref', 'HEAD', 'refs/heads/' + m.groups()[0]]) |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 455 | else: |
| 456 | # Bootstrap failed, previous cache exists; warn and continue. |
Gavin Mak | e6a6233 | 2020-12-04 21:57:10 +0000 | [diff] [blame] | 457 | logging.warning( |
Andrii Shyshkalov | 4f56f23 | 2017-11-23 02:19:25 -0800 | [diff] [blame] | 458 | 'Git cache has a lot of pack files (%d). Tried to re-bootstrap ' |
Gavin Mak | e6a6233 | 2020-12-04 21:57:10 +0000 | [diff] [blame] | 459 | 'but failed. Continuing with non-optimized repository.' % |
| 460 | len(pack_files)) |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 461 | |
Josip Sokcevic | 6afaa6c | 2020-05-08 18:20:17 +0000 | [diff] [blame] | 462 | def _fetch(self, |
Josip Sokcevic | 6afaa6c | 2020-05-08 18:20:17 +0000 | [diff] [blame] | 463 | verbose, |
| 464 | depth, |
| 465 | no_fetch_tags, |
| 466 | reset_fetch_config, |
| 467 | prune=True): |
Joanna Wang | ea99f9a | 2023-08-17 02:20:43 +0000 | [diff] [blame] | 468 | self.config(reset_fetch_config) |
Josip Sokcevic | 6afaa6c | 2020-05-08 18:20:17 +0000 | [diff] [blame] | 469 | |
| 470 | fetch_cmd = ['fetch'] |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 471 | if verbose: |
Josip Sokcevic | 6afaa6c | 2020-05-08 18:20:17 +0000 | [diff] [blame] | 472 | fetch_cmd.extend(['-v', '--progress']) |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 473 | if depth: |
Josip Sokcevic | 6afaa6c | 2020-05-08 18:20:17 +0000 | [diff] [blame] | 474 | fetch_cmd.extend(['--depth', str(depth)]) |
danakj | c41f72c | 2019-11-05 17:12:01 +0000 | [diff] [blame] | 475 | if no_fetch_tags: |
Josip Sokcevic | 6afaa6c | 2020-05-08 18:20:17 +0000 | [diff] [blame] | 476 | fetch_cmd.append('--no-tags') |
| 477 | if prune: |
| 478 | fetch_cmd.append('--prune') |
| 479 | fetch_cmd.append('origin') |
| 480 | |
Joanna Wang | ea99f9a | 2023-08-17 02:20:43 +0000 | [diff] [blame] | 481 | fetch_specs = subprocess.check_output([ |
| 482 | self.git_exe, '--git-dir', |
| 483 | os.path.abspath(self.mirror_path), 'config', '--get-all', |
| 484 | 'remote.origin.fetch' |
| 485 | ], |
| 486 | cwd=self.mirror_path).decode( |
| 487 | 'utf-8', |
| 488 | 'ignore').strip().splitlines() |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 489 | for spec in fetch_specs: |
| 490 | try: |
| 491 | self.print('Fetching %s' % spec) |
Andrii Shyshkalov | 4f56f23 | 2017-11-23 02:19:25 -0800 | [diff] [blame] | 492 | with self.print_duration_of('fetch %s' % spec): |
Joanna Wang | ea99f9a | 2023-08-17 02:20:43 +0000 | [diff] [blame] | 493 | self.RunGit(fetch_cmd + [spec], retry=True) |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 494 | except subprocess.CalledProcessError: |
| 495 | if spec == '+refs/heads/*:refs/heads/*': |
hinoka | dcd8404 | 2016-06-09 14:26:17 -0700 | [diff] [blame] | 496 | raise ClobberNeeded() # Corrupted cache. |
Gavin Mak | e6a6233 | 2020-12-04 21:57:10 +0000 | [diff] [blame] | 497 | logging.warning('Fetch of %s failed' % spec) |
Edward Lesmes | 07a6834 | 2021-04-20 23:39:30 +0000 | [diff] [blame] | 498 | for commit in self.fetch_commits: |
| 499 | self.print('Fetching %s' % commit) |
| 500 | try: |
| 501 | with self.print_duration_of('fetch %s' % commit): |
Joanna Wang | ea99f9a | 2023-08-17 02:20:43 +0000 | [diff] [blame] | 502 | self.RunGit(['fetch', 'origin', commit], retry=True) |
Edward Lesmes | 07a6834 | 2021-04-20 23:39:30 +0000 | [diff] [blame] | 503 | except subprocess.CalledProcessError: |
| 504 | logging.warning('Fetch of %s failed' % commit) |
hinoka@chromium.org | aa1e1a4 | 2014-06-26 21:58:51 +0000 | [diff] [blame] | 505 | |
danakj | c41f72c | 2019-11-05 17:12:01 +0000 | [diff] [blame] | 506 | def populate(self, |
| 507 | depth=None, |
| 508 | no_fetch_tags=False, |
| 509 | shallow=False, |
| 510 | bootstrap=False, |
| 511 | verbose=False, |
danakj | c41f72c | 2019-11-05 17:12:01 +0000 | [diff] [blame] | 512 | lock_timeout=0, |
Edward Lemur | 579c986 | 2018-07-13 23:17:51 +0000 | [diff] [blame] | 513 | reset_fetch_config=False): |
szager@chromium.org | b0a13a2 | 2014-06-18 00:52:25 +0000 | [diff] [blame] | 514 | assert self.GetCachePath() |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 515 | if shallow and not depth: |
| 516 | depth = 10000 |
| 517 | gclient_utils.safe_makedirs(self.GetCachePath()) |
| 518 | |
Josip Sokcevic | 14a83ae | 2020-05-21 01:36:34 +0000 | [diff] [blame] | 519 | with lockfile.lock(self.mirror_path, lock_timeout): |
| 520 | try: |
| 521 | self._ensure_bootstrapped(depth, bootstrap, reset_fetch_config) |
Joanna Wang | ea99f9a | 2023-08-17 02:20:43 +0000 | [diff] [blame] | 522 | self._fetch(verbose, depth, no_fetch_tags, reset_fetch_config) |
Josip Sokcevic | 14a83ae | 2020-05-21 01:36:34 +0000 | [diff] [blame] | 523 | except ClobberNeeded: |
| 524 | # This is a major failure, we need to clean and force a bootstrap. |
| 525 | gclient_utils.rmtree(self.mirror_path) |
| 526 | self.print(GIT_CACHE_CORRUPT_MESSAGE) |
| 527 | self._ensure_bootstrapped(depth, |
| 528 | bootstrap, |
| 529 | reset_fetch_config, |
| 530 | force=True) |
Joanna Wang | ea99f9a | 2023-08-17 02:20:43 +0000 | [diff] [blame] | 531 | self._fetch(verbose, depth, no_fetch_tags, reset_fetch_config) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 532 | |
Joanna Wang | 5175d18 | 2022-12-07 17:27:57 +0000 | [diff] [blame] | 533 | def update_bootstrap(self, prune=False, gc_aggressive=False): |
Joanna Wang | 38d1673 | 2022-10-10 17:12:47 +0000 | [diff] [blame] | 534 | # NOTE: There have been cases where repos were being recursively uploaded |
| 535 | # to google storage. |
| 536 | # E.g. `<host_url>-<repo>/<gen_number>/<host_url>-<repo>/` in GS and |
| 537 | # <host_url>-<repo>/<host_url>-<repo>/ on the bot. |
| 538 | # Check for recursed files on the bot here and remove them if found |
| 539 | # before we upload to GS. |
| 540 | # See crbug.com/1370443; keep this check until root cause is found. |
| 541 | recursed_dir = os.path.join(self.mirror_path, |
Joanna Wang | 17cf81d | 2022-10-12 03:41:24 +0000 | [diff] [blame] | 542 | self.mirror_path.split(os.path.sep)[-1]) |
Joanna Wang | 38d1673 | 2022-10-10 17:12:47 +0000 | [diff] [blame] | 543 | if os.path.exists(recursed_dir): |
| 544 | self.print('Deleting unexpected directory: %s' % recursed_dir) |
Josip Sokcevic | d540d8b | 2022-10-12 18:43:49 +0000 | [diff] [blame] | 545 | gclient_utils.rmtree(recursed_dir) |
Joanna Wang | 38d1673 | 2022-10-10 17:12:47 +0000 | [diff] [blame] | 546 | |
Karen Qian | dcad749 | 2019-04-26 03:11:16 +0000 | [diff] [blame] | 547 | # The folder is <git number> |
Joanna Wang | 5175d18 | 2022-12-07 17:27:57 +0000 | [diff] [blame] | 548 | gen_number = subprocess.check_output([self.git_exe, 'number'], |
| 549 | cwd=self.mirror_path).decode( |
| 550 | 'utf-8', 'ignore').strip() |
Karen Qian | dcad749 | 2019-04-26 03:11:16 +0000 | [diff] [blame] | 551 | gsutil = Gsutil(path=self.gsutil_exe, boto_path=None) |
| 552 | |
Karen Qian | ccd2b4d | 2019-05-03 22:25:59 +0000 | [diff] [blame] | 553 | dest_prefix = '%s/%s' % (self._gs_path, gen_number) |
Karen Qian | dcad749 | 2019-04-26 03:11:16 +0000 | [diff] [blame] | 554 | |
Karen Qian | ccd2b4d | 2019-05-03 22:25:59 +0000 | [diff] [blame] | 555 | # ls_out lists contents in the format: gs://blah/blah/123... |
Joanna Wang | 5b5ee2d | 2022-10-12 17:18:22 +0000 | [diff] [blame] | 556 | self.print('running "gsutil ls %s":' % self._gs_path) |
Joanna Wang | 38d1673 | 2022-10-10 17:12:47 +0000 | [diff] [blame] | 557 | ls_code, ls_out, ls_error = gsutil.check_call_with_retries( |
| 558 | 'ls', self._gs_path) |
| 559 | if ls_code != 0: |
| 560 | self.print(ls_error) |
| 561 | else: |
| 562 | self.print(ls_out) |
Karen Qian | dcad749 | 2019-04-26 03:11:16 +0000 | [diff] [blame] | 563 | |
Karen Qian | ccd2b4d | 2019-05-03 22:25:59 +0000 | [diff] [blame] | 564 | # Check to see if folder already exists in gs |
| 565 | ls_out_set = set(ls_out.strip().splitlines()) |
| 566 | if (dest_prefix + '/' in ls_out_set and |
| 567 | dest_prefix + '.ready' in ls_out_set): |
| 568 | print('Cache %s already exists.' % dest_prefix) |
Karen Qian | dcad749 | 2019-04-26 03:11:16 +0000 | [diff] [blame] | 569 | return |
| 570 | |
Andrii Shyshkalov | 46b91c0 | 2020-10-27 17:25:47 +0000 | [diff] [blame] | 571 | # Reduce the number of individual files to download & write on disk. |
| 572 | self.RunGit(['pack-refs', '--all']) |
| 573 | |
Andrii Shyshkalov | 199182f | 2019-04-26 16:01:20 +0000 | [diff] [blame] | 574 | # Run Garbage Collect to compress packfile. |
Andrii Shyshkalov | dcfe55f | 2019-09-21 03:35:39 +0000 | [diff] [blame] | 575 | gc_args = ['gc', '--prune=all'] |
| 576 | if gc_aggressive: |
Michael Moss | 7748094 | 2020-06-22 18:32:37 +0000 | [diff] [blame] | 577 | # The default "gc --aggressive" is often too aggressive for some machines, |
| 578 | # since it attempts to create as many threads as there are CPU cores, |
| 579 | # while not limiting per-thread memory usage, which puts too much pressure |
| 580 | # on RAM on high-core machines, causing them to thrash. Using lower-level |
| 581 | # commands gives more control over those settings. |
| 582 | |
| 583 | # This might not be strictly necessary, but it's fast and is normally run |
| 584 | # by 'gc --aggressive', so it shouldn't hurt. |
| 585 | self.RunGit(['reflog', 'expire', '--all']) |
| 586 | |
| 587 | # These are the default repack settings for 'gc --aggressive'. |
| 588 | gc_args = ['repack', '-d', '-l', '-f', '--depth=50', '--window=250', '-A', |
| 589 | '--unpack-unreachable=all'] |
| 590 | # A 1G memory limit seems to provide comparable pack results as the |
| 591 | # default, even for our largest repos, while preventing runaway memory (at |
| 592 | # least on current Chromium builders which have about 4G RAM per core). |
| 593 | gc_args.append('--window-memory=1g') |
| 594 | # NOTE: It might also be possible to avoid thrashing with a larger window |
| 595 | # (e.g. "--window-memory=2g") by limiting the number of threads created |
| 596 | # (e.g. "--threads=[cores/2]"). Some limited testing didn't show much |
| 597 | # difference in outcomes on our current repos, but it might be worth |
| 598 | # trying if the repos grow much larger and the packs don't seem to be |
| 599 | # getting compressed enough. |
Andrii Shyshkalov | dcfe55f | 2019-09-21 03:35:39 +0000 | [diff] [blame] | 600 | self.RunGit(gc_args) |
Andrii Shyshkalov | 199182f | 2019-04-26 16:01:20 +0000 | [diff] [blame] | 601 | |
Joanna Wang | 38d1673 | 2022-10-10 17:12:47 +0000 | [diff] [blame] | 602 | self.print('running "gsutil -m rsync -r -d %s %s"' % |
Joanna Wang | 2c54a19 | 2022-10-05 01:01:40 +0000 | [diff] [blame] | 603 | (self.mirror_path, dest_prefix)) |
Joanna Wang | 38d1673 | 2022-10-10 17:12:47 +0000 | [diff] [blame] | 604 | gsutil.call('-m', 'rsync', '-r', '-d', self.mirror_path, dest_prefix) |
Karen Qian | dcad749 | 2019-04-26 03:11:16 +0000 | [diff] [blame] | 605 | |
Karen Qian | ccd2b4d | 2019-05-03 22:25:59 +0000 | [diff] [blame] | 606 | # Create .ready file and upload |
Karen Qian | dcad749 | 2019-04-26 03:11:16 +0000 | [diff] [blame] | 607 | _, ready_file_name = tempfile.mkstemp(suffix='.ready') |
| 608 | try: |
Joanna Wang | 2c54a19 | 2022-10-05 01:01:40 +0000 | [diff] [blame] | 609 | self.print('running "gsutil cp %s %s.ready"' % |
| 610 | (ready_file_name, dest_prefix)) |
Karen Qian | ccd2b4d | 2019-05-03 22:25:59 +0000 | [diff] [blame] | 611 | gsutil.call('cp', ready_file_name, '%s.ready' % (dest_prefix)) |
Karen Qian | dcad749 | 2019-04-26 03:11:16 +0000 | [diff] [blame] | 612 | finally: |
| 613 | os.remove(ready_file_name) |
hinoka@chromium.org | c8444f3 | 2014-06-18 23:18:17 +0000 | [diff] [blame] | 614 | |
Karen Qian | ccd2b4d | 2019-05-03 22:25:59 +0000 | [diff] [blame] | 615 | # remove all other directory/.ready files in the same gs_path |
| 616 | # except for the directory/.ready file previously created |
| 617 | # which can be used for bootstrapping while the current one is |
| 618 | # being uploaded |
| 619 | if not prune: |
| 620 | return |
| 621 | prev_dest_prefix = self._GetMostRecentCacheDirectory(ls_out_set) |
| 622 | if not prev_dest_prefix: |
| 623 | return |
| 624 | for path in ls_out_set: |
Aravind Vasudevan | c5f0cbb | 2022-01-24 23:56:57 +0000 | [diff] [blame] | 625 | if path in (prev_dest_prefix + '/', prev_dest_prefix + '.ready'): |
Karen Qian | ccd2b4d | 2019-05-03 22:25:59 +0000 | [diff] [blame] | 626 | continue |
| 627 | if path.endswith('.ready'): |
| 628 | gsutil.call('rm', path) |
| 629 | continue |
| 630 | gsutil.call('-m', 'rm', '-r', path) |
| 631 | |
| 632 | |
szager@chromium.org | cdfcd7c | 2014-06-10 23:40:46 +0000 | [diff] [blame] | 633 | @staticmethod |
| 634 | def DeleteTmpPackFiles(path): |
| 635 | pack_dir = os.path.join(path, 'objects', 'pack') |
szager@chromium.org | 3341849 | 2014-06-18 19:03:39 +0000 | [diff] [blame] | 636 | if not os.path.isdir(pack_dir): |
| 637 | return |
szager@chromium.org | cdfcd7c | 2014-06-10 23:40:46 +0000 | [diff] [blame] | 638 | pack_files = [f for f in os.listdir(pack_dir) if |
| 639 | f.startswith('.tmp-') or f.startswith('tmp_pack_')] |
| 640 | for f in pack_files: |
| 641 | f = os.path.join(pack_dir, f) |
| 642 | try: |
| 643 | os.remove(f) |
Gavin Mak | e6a6233 | 2020-12-04 21:57:10 +0000 | [diff] [blame] | 644 | logging.warning('Deleted stale temporary pack file %s' % f) |
szager@chromium.org | cdfcd7c | 2014-06-10 23:40:46 +0000 | [diff] [blame] | 645 | except OSError: |
Gavin Mak | e6a6233 | 2020-12-04 21:57:10 +0000 | [diff] [blame] | 646 | logging.warning('Unable to delete temporary pack file %s' % f) |
szager@chromium.org | 174766f | 2014-05-13 21:27:46 +0000 | [diff] [blame] | 647 | |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 648 | |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 649 | @subcommand.usage('[url of repo to check for caching]') |
Edward Lesmes | cb04744 | 2021-05-06 20:18:49 +0000 | [diff] [blame] | 650 | @metrics.collector.collect_metrics('git cache exists') |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 651 | def CMDexists(parser, args): |
| 652 | """Check to see if there already is a cache of the given repo.""" |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 653 | _, args = parser.parse_args(args) |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 654 | if not len(args) == 1: |
| 655 | parser.error('git cache exists only takes exactly one repo url.') |
| 656 | url = args[0] |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 657 | mirror = Mirror(url) |
| 658 | if mirror.exists(): |
| 659 | print(mirror.mirror_path) |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 660 | return 0 |
| 661 | return 1 |
| 662 | |
| 663 | |
hinoka@google.com | 563559c | 2014-04-02 00:36:24 +0000 | [diff] [blame] | 664 | @subcommand.usage('[url of repo to create a bootstrap zip file]') |
Edward Lesmes | cb04744 | 2021-05-06 20:18:49 +0000 | [diff] [blame] | 665 | @metrics.collector.collect_metrics('git cache update-bootstrap') |
hinoka@google.com | 563559c | 2014-04-02 00:36:24 +0000 | [diff] [blame] | 666 | def CMDupdate_bootstrap(parser, args): |
| 667 | """Create and uploads a bootstrap tarball.""" |
| 668 | # Lets just assert we can't do this on Windows. |
| 669 | if sys.platform.startswith('win'): |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 670 | print('Sorry, update bootstrap will not work on Windows.', file=sys.stderr) |
hinoka@google.com | 563559c | 2014-04-02 00:36:24 +0000 | [diff] [blame] | 671 | return 1 |
| 672 | |
Robert Iannucci | 0081c0f | 2019-09-29 08:30:54 +0000 | [diff] [blame] | 673 | parser.add_option('--skip-populate', action='store_true', |
| 674 | help='Skips "populate" step if mirror already exists.') |
Andrii Shyshkalov | dcfe55f | 2019-09-21 03:35:39 +0000 | [diff] [blame] | 675 | parser.add_option('--gc-aggressive', action='store_true', |
| 676 | help='Run aggressive repacking of the repo.') |
hinoka@chromium.org | c8444f3 | 2014-06-18 23:18:17 +0000 | [diff] [blame] | 677 | parser.add_option('--prune', action='store_true', |
Andrii Shyshkalov | 7a2205c | 2019-04-26 05:14:36 +0000 | [diff] [blame] | 678 | help='Prune all other cached bundles of the same repo.') |
hinoka@chromium.org | c8444f3 | 2014-06-18 23:18:17 +0000 | [diff] [blame] | 679 | |
hinoka@google.com | 563559c | 2014-04-02 00:36:24 +0000 | [diff] [blame] | 680 | populate_args = args[:] |
Robert Iannucci | 0081c0f | 2019-09-29 08:30:54 +0000 | [diff] [blame] | 681 | options, args = parser.parse_args(args) |
| 682 | url = args[0] |
| 683 | mirror = Mirror(url) |
| 684 | if not options.skip_populate or not mirror.exists(): |
| 685 | CMDpopulate(parser, populate_args) |
| 686 | else: |
| 687 | print('Skipped populate step.') |
hinoka@google.com | 563559c | 2014-04-02 00:36:24 +0000 | [diff] [blame] | 688 | |
| 689 | # Get the repo directory. |
Andrii Shyshkalov | c50b096 | 2019-11-21 23:03:18 +0000 | [diff] [blame] | 690 | _, args2 = parser.parse_args(args) |
| 691 | url = args2[0] |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 692 | mirror = Mirror(url) |
Joanna Wang | 5175d18 | 2022-12-07 17:27:57 +0000 | [diff] [blame] | 693 | mirror.update_bootstrap(options.prune, options.gc_aggressive) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 694 | return 0 |
hinoka@google.com | 563559c | 2014-04-02 00:36:24 +0000 | [diff] [blame] | 695 | |
| 696 | |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 697 | @subcommand.usage('[url of repo to add to or update in cache]') |
Edward Lesmes | cb04744 | 2021-05-06 20:18:49 +0000 | [diff] [blame] | 698 | @metrics.collector.collect_metrics('git cache populate') |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 699 | def CMDpopulate(parser, args): |
| 700 | """Ensure that the cache has all up-to-date objects for the given repo.""" |
| 701 | parser.add_option('--depth', type='int', |
| 702 | help='Only cache DEPTH commits of history') |
danakj | c41f72c | 2019-11-05 17:12:01 +0000 | [diff] [blame] | 703 | parser.add_option( |
| 704 | '--no-fetch-tags', |
| 705 | action='store_true', |
| 706 | help=('Don\'t fetch tags from the server. This can speed up ' |
| 707 | 'fetch considerably when there are many tags.')) |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 708 | parser.add_option('--shallow', '-s', action='store_true', |
| 709 | help='Only cache 10000 commits of history') |
| 710 | parser.add_option('--ref', action='append', |
| 711 | help='Specify additional refs to be fetched') |
Edward Lesmes | 07a6834 | 2021-04-20 23:39:30 +0000 | [diff] [blame] | 712 | parser.add_option('--commit', action='append', |
| 713 | help='Specify additional commits to be fetched') |
pgervais@chromium.org | b9f2751 | 2014-08-08 15:52:33 +0000 | [diff] [blame] | 714 | parser.add_option('--no_bootstrap', '--no-bootstrap', |
| 715 | action='store_true', |
hinoka@google.com | 563559c | 2014-04-02 00:36:24 +0000 | [diff] [blame] | 716 | help='Don\'t bootstrap from Google Storage') |
Josip Sokcevic | 14a83ae | 2020-05-21 01:36:34 +0000 | [diff] [blame] | 717 | parser.add_option('--ignore_locks', |
| 718 | '--ignore-locks', |
Vadim Shtayura | 08049e2 | 2017-10-11 00:14:52 +0000 | [diff] [blame] | 719 | action='store_true', |
Josip Sokcevic | 14a83ae | 2020-05-21 01:36:34 +0000 | [diff] [blame] | 720 | help='NOOP. This flag will be removed in the future.') |
Robert Iannucci | 0931598 | 2019-10-05 08:12:03 +0000 | [diff] [blame] | 721 | parser.add_option('--break-locks', |
| 722 | action='store_true', |
| 723 | help='Break any existing lock instead of just ignoring it') |
Edward Lemur | 579c986 | 2018-07-13 23:17:51 +0000 | [diff] [blame] | 724 | parser.add_option('--reset-fetch-config', action='store_true', default=False, |
| 725 | help='Reset the fetch config before populating the cache.') |
hinoka@google.com | 563559c | 2014-04-02 00:36:24 +0000 | [diff] [blame] | 726 | |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 727 | options, args = parser.parse_args(args) |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 728 | if not len(args) == 1: |
| 729 | parser.error('git cache populate only takes exactly one repo url.') |
Josip Sokcevic | 14a83ae | 2020-05-21 01:36:34 +0000 | [diff] [blame] | 730 | if options.ignore_locks: |
| 731 | print('ignore_locks is no longer used. Please remove its usage.') |
| 732 | if options.break_locks: |
| 733 | print('break_locks is no longer used. Please remove its usage.') |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 734 | url = args[0] |
| 735 | |
Edward Lesmes | 07a6834 | 2021-04-20 23:39:30 +0000 | [diff] [blame] | 736 | mirror = Mirror(url, refs=options.ref, commits=options.commit) |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 737 | kwargs = { |
danakj | c41f72c | 2019-11-05 17:12:01 +0000 | [diff] [blame] | 738 | 'no_fetch_tags': options.no_fetch_tags, |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 739 | 'verbose': options.verbose, |
| 740 | 'shallow': options.shallow, |
| 741 | 'bootstrap': not options.no_bootstrap, |
Vadim Shtayura | 08049e2 | 2017-10-11 00:14:52 +0000 | [diff] [blame] | 742 | 'lock_timeout': options.timeout, |
Edward Lemur | 579c986 | 2018-07-13 23:17:51 +0000 | [diff] [blame] | 743 | 'reset_fetch_config': options.reset_fetch_config, |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 744 | } |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 745 | if options.depth: |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 746 | kwargs['depth'] = options.depth |
| 747 | mirror.populate(**kwargs) |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 748 | |
| 749 | |
szager@chromium.org | f314511 | 2014-08-07 21:02:36 +0000 | [diff] [blame] | 750 | @subcommand.usage('Fetch new commits into cache and current checkout') |
Edward Lesmes | cb04744 | 2021-05-06 20:18:49 +0000 | [diff] [blame] | 751 | @metrics.collector.collect_metrics('git cache fetch') |
szager@chromium.org | f314511 | 2014-08-07 21:02:36 +0000 | [diff] [blame] | 752 | def CMDfetch(parser, args): |
| 753 | """Update mirror, and fetch in cwd.""" |
| 754 | parser.add_option('--all', action='store_true', help='Fetch all remotes') |
szager@chromium.org | 66c8b85 | 2015-09-22 23:19:07 +0000 | [diff] [blame] | 755 | parser.add_option('--no_bootstrap', '--no-bootstrap', |
| 756 | action='store_true', |
| 757 | help='Don\'t (re)bootstrap from Google Storage') |
danakj | c41f72c | 2019-11-05 17:12:01 +0000 | [diff] [blame] | 758 | parser.add_option( |
| 759 | '--no-fetch-tags', |
| 760 | action='store_true', |
| 761 | help=('Don\'t fetch tags from the server. This can speed up ' |
| 762 | 'fetch considerably when there are many tags.')) |
szager@chromium.org | f314511 | 2014-08-07 21:02:36 +0000 | [diff] [blame] | 763 | options, args = parser.parse_args(args) |
| 764 | |
| 765 | # Figure out which remotes to fetch. This mimics the behavior of regular |
| 766 | # 'git fetch'. Note that in the case of "stacked" or "pipelined" branches, |
| 767 | # this will NOT try to traverse up the branching structure to find the |
| 768 | # ultimate remote to update. |
| 769 | remotes = [] |
| 770 | if options.all: |
| 771 | assert not args, 'fatal: fetch --all does not take a repository argument' |
Edward Lesmes | 4c3eb70 | 2020-03-25 21:09:30 +0000 | [diff] [blame] | 772 | remotes = subprocess.check_output([Mirror.git_exe, 'remote']) |
| 773 | remotes = remotes.decode('utf-8', 'ignore').splitlines() |
szager@chromium.org | f314511 | 2014-08-07 21:02:36 +0000 | [diff] [blame] | 774 | elif args: |
| 775 | remotes = args |
| 776 | else: |
| 777 | current_branch = subprocess.check_output( |
Edward Lesmes | 4c3eb70 | 2020-03-25 21:09:30 +0000 | [diff] [blame] | 778 | [Mirror.git_exe, 'rev-parse', '--abbrev-ref', 'HEAD']) |
| 779 | current_branch = current_branch.decode('utf-8', 'ignore').strip() |
szager@chromium.org | f314511 | 2014-08-07 21:02:36 +0000 | [diff] [blame] | 780 | if current_branch != 'HEAD': |
| 781 | upstream = subprocess.check_output( |
Edward Lesmes | 4c3eb70 | 2020-03-25 21:09:30 +0000 | [diff] [blame] | 782 | [Mirror.git_exe, 'config', 'branch.%s.remote' % current_branch]) |
| 783 | upstream = upstream.decode('utf-8', 'ignore').strip() |
szager@chromium.org | f314511 | 2014-08-07 21:02:36 +0000 | [diff] [blame] | 784 | if upstream and upstream != '.': |
| 785 | remotes = [upstream] |
| 786 | if not remotes: |
| 787 | remotes = ['origin'] |
| 788 | |
| 789 | cachepath = Mirror.GetCachePath() |
| 790 | git_dir = os.path.abspath(subprocess.check_output( |
Edward Lesmes | 4c3eb70 | 2020-03-25 21:09:30 +0000 | [diff] [blame] | 791 | [Mirror.git_exe, 'rev-parse', '--git-dir']).decode('utf-8', 'ignore')) |
szager@chromium.org | f314511 | 2014-08-07 21:02:36 +0000 | [diff] [blame] | 792 | git_dir = os.path.abspath(git_dir) |
| 793 | if git_dir.startswith(cachepath): |
| 794 | mirror = Mirror.FromPath(git_dir) |
szager@chromium.org | dbb6f82 | 2016-02-02 22:59:30 +0000 | [diff] [blame] | 795 | mirror.populate( |
danakj | c41f72c | 2019-11-05 17:12:01 +0000 | [diff] [blame] | 796 | bootstrap=not options.no_bootstrap, |
| 797 | no_fetch_tags=options.no_fetch_tags, |
| 798 | lock_timeout=options.timeout) |
szager@chromium.org | f314511 | 2014-08-07 21:02:36 +0000 | [diff] [blame] | 799 | return 0 |
| 800 | for remote in remotes: |
| 801 | remote_url = subprocess.check_output( |
Edward Lesmes | 4c3eb70 | 2020-03-25 21:09:30 +0000 | [diff] [blame] | 802 | [Mirror.git_exe, 'config', 'remote.%s.url' % remote]) |
| 803 | remote_url = remote_url.decode('utf-8', 'ignore').strip() |
szager@chromium.org | f314511 | 2014-08-07 21:02:36 +0000 | [diff] [blame] | 804 | if remote_url.startswith(cachepath): |
| 805 | mirror = Mirror.FromPath(remote_url) |
| 806 | mirror.print = lambda *args: None |
| 807 | print('Updating git cache...') |
szager@chromium.org | dbb6f82 | 2016-02-02 22:59:30 +0000 | [diff] [blame] | 808 | mirror.populate( |
danakj | c41f72c | 2019-11-05 17:12:01 +0000 | [diff] [blame] | 809 | bootstrap=not options.no_bootstrap, |
| 810 | no_fetch_tags=options.no_fetch_tags, |
| 811 | lock_timeout=options.timeout) |
szager@chromium.org | f314511 | 2014-08-07 21:02:36 +0000 | [diff] [blame] | 812 | subprocess.check_call([Mirror.git_exe, 'fetch', remote]) |
| 813 | return 0 |
| 814 | |
| 815 | |
Josip Sokcevic | 14a83ae | 2020-05-21 01:36:34 +0000 | [diff] [blame] | 816 | @subcommand.usage('do not use - it is a noop.') |
Edward Lesmes | cb04744 | 2021-05-06 20:18:49 +0000 | [diff] [blame] | 817 | @metrics.collector.collect_metrics('git cache unlock') |
Vadim Shtayura | 08049e2 | 2017-10-11 00:14:52 +0000 | [diff] [blame] | 818 | def CMDunlock(parser, args): |
Josip Sokcevic | 14a83ae | 2020-05-21 01:36:34 +0000 | [diff] [blame] | 819 | """This command does nothing.""" |
| 820 | print('This command does nothing and will be removed in the future.') |
Vadim Shtayura | 08049e2 | 2017-10-11 00:14:52 +0000 | [diff] [blame] | 821 | |
| 822 | |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 823 | class OptionParser(optparse.OptionParser): |
| 824 | """Wrapper class for OptionParser to handle global options.""" |
| 825 | |
| 826 | def __init__(self, *args, **kwargs): |
| 827 | optparse.OptionParser.__init__(self, *args, prog='git cache', **kwargs) |
| 828 | self.add_option('-c', '--cache-dir', |
Robert Iannucci | a19649b | 2018-06-29 16:31:45 +0000 | [diff] [blame] | 829 | help=( |
| 830 | 'Path to the directory containing the caches. Normally ' |
| 831 | 'deduced from git config cache.cachepath or ' |
| 832 | '$GIT_CACHE_PATH.')) |
szager@chromium.org | 2c391af | 2014-05-23 09:07:15 +0000 | [diff] [blame] | 833 | self.add_option('-v', '--verbose', action='count', default=1, |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 834 | help='Increase verbosity (can be passed multiple times)') |
szager@chromium.org | 2c391af | 2014-05-23 09:07:15 +0000 | [diff] [blame] | 835 | self.add_option('-q', '--quiet', action='store_true', |
| 836 | help='Suppress all extraneous output') |
Vadim Shtayura | 08049e2 | 2017-10-11 00:14:52 +0000 | [diff] [blame] | 837 | self.add_option('--timeout', type='int', default=0, |
| 838 | help='Timeout for acquiring cache lock, in seconds') |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 839 | |
| 840 | def parse_args(self, args=None, values=None): |
Edward Lesmes | cb04744 | 2021-05-06 20:18:49 +0000 | [diff] [blame] | 841 | # Create an optparse.Values object that will store only the actual passed |
| 842 | # options, without the defaults. |
| 843 | actual_options = optparse.Values() |
| 844 | _, args = optparse.OptionParser.parse_args(self, args, actual_options) |
| 845 | # Create an optparse.Values object with the default options. |
| 846 | options = optparse.Values(self.get_default_values().__dict__) |
| 847 | # Update it with the options passed by the user. |
| 848 | options._update_careful(actual_options.__dict__) |
| 849 | # Store the options passed by the user in an _actual_options attribute. |
| 850 | # We store only the keys, and not the values, since the values can contain |
| 851 | # arbitrary information, which might be PII. |
| 852 | metrics.collector.add('arguments', list(actual_options.__dict__.keys())) |
| 853 | |
szager@chromium.org | 2c391af | 2014-05-23 09:07:15 +0000 | [diff] [blame] | 854 | if options.quiet: |
| 855 | options.verbose = 0 |
| 856 | |
| 857 | levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG] |
| 858 | logging.basicConfig(level=levels[min(options.verbose, len(levels) - 1)]) |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 859 | |
| 860 | try: |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 861 | global_cache_dir = Mirror.GetCachePath() |
| 862 | except RuntimeError: |
| 863 | global_cache_dir = None |
| 864 | if options.cache_dir: |
| 865 | if global_cache_dir and ( |
| 866 | os.path.abspath(options.cache_dir) != |
| 867 | os.path.abspath(global_cache_dir)): |
Gavin Mak | e6a6233 | 2020-12-04 21:57:10 +0000 | [diff] [blame] | 868 | logging.warning('Overriding globally-configured cache directory.') |
szager@chromium.org | 848fd49 | 2014-04-09 19:06:44 +0000 | [diff] [blame] | 869 | Mirror.SetCachePath(options.cache_dir) |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 870 | |
agable@chromium.org | 5a306a2 | 2014-02-24 22:13:59 +0000 | [diff] [blame] | 871 | return options, args |
| 872 | |
| 873 | |
| 874 | def main(argv): |
| 875 | dispatcher = subcommand.CommandDispatcher(__name__) |
| 876 | return dispatcher.execute(OptionParser(), argv) |
| 877 | |
| 878 | |
| 879 | if __name__ == '__main__': |
sbc@chromium.org | 013731e | 2015-02-26 18:28:43 +0000 | [diff] [blame] | 880 | try: |
Edward Lesmes | cb04744 | 2021-05-06 20:18:49 +0000 | [diff] [blame] | 881 | with metrics.collector.print_notice_and_exit(): |
| 882 | sys.exit(main(sys.argv[1:])) |
sbc@chromium.org | 013731e | 2015-02-26 18:28:43 +0000 | [diff] [blame] | 883 | except KeyboardInterrupt: |
| 884 | sys.stderr.write('interrupted\n') |
Edward Lemur | df746d0 | 2019-07-27 00:42:46 +0000 | [diff] [blame] | 885 | sys.exit(1) |