Josip Sokcevic | fb12b3f | 2021-04-19 18:09:50 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
hinoka@chromium.org | 7a79054 | 2014-12-10 02:04:39 +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 | """Run a pinned gsutil.""" |
| 7 | |
Aravind Vasudevan | 7af6169 | 2023-01-09 23:15:15 +0000 | [diff] [blame] | 8 | from __future__ import print_function |
hinoka@chromium.org | 7a79054 | 2014-12-10 02:04:39 +0000 | [diff] [blame] | 9 | |
| 10 | import argparse |
hinoka@chromium.org | 7a79054 | 2014-12-10 02:04:39 +0000 | [diff] [blame] | 11 | import base64 |
dnj@chromium.org | 605d81d | 2015-09-18 22:33:53 +0000 | [diff] [blame] | 12 | import contextlib |
primiano@chromium.org | df35176 | 2014-12-18 11:12:34 +0000 | [diff] [blame] | 13 | import hashlib |
hinoka@chromium.org | 7a79054 | 2014-12-10 02:04:39 +0000 | [diff] [blame] | 14 | import json |
primiano@chromium.org | df35176 | 2014-12-18 11:12:34 +0000 | [diff] [blame] | 15 | import os |
| 16 | import shutil |
hinoka@chromium.org | 7a79054 | 2014-12-10 02:04:39 +0000 | [diff] [blame] | 17 | import subprocess |
primiano@chromium.org | df35176 | 2014-12-18 11:12:34 +0000 | [diff] [blame] | 18 | import sys |
dnj@chromium.org | 605d81d | 2015-09-18 22:33:53 +0000 | [diff] [blame] | 19 | import tempfile |
| 20 | import time |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 21 | |
| 22 | try: |
| 23 | import urllib2 as urllib |
| 24 | except ImportError: # For Py3 compatibility |
| 25 | import urllib.request as urllib |
| 26 | |
primiano@chromium.org | df35176 | 2014-12-18 11:12:34 +0000 | [diff] [blame] | 27 | import zipfile |
hinoka@chromium.org | 7a79054 | 2014-12-10 02:04:39 +0000 | [diff] [blame] | 28 | |
| 29 | |
| 30 | GSUTIL_URL = 'https://storage.googleapis.com/pub/' |
| 31 | API_URL = 'https://www.googleapis.com/storage/v1/b/pub/o/' |
| 32 | |
| 33 | THIS_DIR = os.path.dirname(os.path.abspath(__file__)) |
| 34 | DEFAULT_BIN_DIR = os.path.join(THIS_DIR, 'external_bin', 'gsutil') |
hinoka@chromium.org | 7a79054 | 2014-12-10 02:04:39 +0000 | [diff] [blame] | 35 | |
Dan Jacques | 509776e | 2017-09-07 18:01:08 -0700 | [diff] [blame] | 36 | IS_WINDOWS = os.name == 'nt' |
| 37 | |
Josip Sokcevic | 1909696 | 2022-03-10 17:56:09 +0000 | [diff] [blame] | 38 | VERSION = '4.68' |
Josip Sokcevic | fa474e8 | 2021-09-17 16:59:49 +0000 | [diff] [blame] | 39 | |
Aravind Vasudevan | 7af6169 | 2023-01-09 23:15:15 +0000 | [diff] [blame] | 40 | # Google OAuth Context required by gsutil. |
| 41 | LUCI_AUTH_SCOPES = [ |
| 42 | 'https://www.googleapis.com/auth/devstorage.full_control', |
| 43 | 'https://www.googleapis.com/auth/userinfo.email', |
| 44 | ] |
| 45 | |
Dan Jacques | 509776e | 2017-09-07 18:01:08 -0700 | [diff] [blame] | 46 | |
hinoka@chromium.org | 7a79054 | 2014-12-10 02:04:39 +0000 | [diff] [blame] | 47 | class InvalidGsutilError(Exception): |
| 48 | pass |
| 49 | |
| 50 | |
hinoka@chromium.org | 7a79054 | 2014-12-10 02:04:39 +0000 | [diff] [blame] | 51 | def download_gsutil(version, target_dir): |
| 52 | """Downloads gsutil into the target_dir.""" |
| 53 | filename = 'gsutil_%s.zip' % version |
| 54 | target_filename = os.path.join(target_dir, filename) |
| 55 | |
| 56 | # Check if the target exists already. |
| 57 | if os.path.exists(target_filename): |
| 58 | md5_calc = hashlib.md5() |
| 59 | with open(target_filename, 'rb') as f: |
| 60 | while True: |
| 61 | buf = f.read(4096) |
| 62 | if not buf: |
| 63 | break |
| 64 | md5_calc.update(buf) |
| 65 | local_md5 = md5_calc.hexdigest() |
| 66 | |
| 67 | metadata_url = '%s%s' % (API_URL, filename) |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 68 | metadata = json.load(urllib.urlopen(metadata_url)) |
Edward Lemur | 83aafc9 | 2019-11-25 23:25:05 +0000 | [diff] [blame] | 69 | remote_md5 = base64.b64decode(metadata['md5Hash']).decode('utf-8') |
hinoka@chromium.org | 7a79054 | 2014-12-10 02:04:39 +0000 | [diff] [blame] | 70 | |
| 71 | if local_md5 == remote_md5: |
| 72 | return target_filename |
| 73 | os.remove(target_filename) |
| 74 | |
| 75 | # Do the download. |
| 76 | url = '%s%s' % (GSUTIL_URL, filename) |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 77 | u = urllib.urlopen(url) |
hinoka@chromium.org | 7a79054 | 2014-12-10 02:04:39 +0000 | [diff] [blame] | 78 | with open(target_filename, 'wb') as f: |
| 79 | while True: |
| 80 | buf = u.read(4096) |
| 81 | if not buf: |
| 82 | break |
| 83 | f.write(buf) |
| 84 | return target_filename |
| 85 | |
| 86 | |
dnj@chromium.org | 605d81d | 2015-09-18 22:33:53 +0000 | [diff] [blame] | 87 | @contextlib.contextmanager |
| 88 | def temporary_directory(base): |
Takuto Ikuta | 8daf244 | 2021-10-28 05:51:18 +0000 | [diff] [blame] | 89 | tmpdir = tempfile.mkdtemp(prefix='t', dir=base) |
dnj@chromium.org | 605d81d | 2015-09-18 22:33:53 +0000 | [diff] [blame] | 90 | try: |
| 91 | yield tmpdir |
| 92 | finally: |
| 93 | if os.path.isdir(tmpdir): |
| 94 | shutil.rmtree(tmpdir) |
| 95 | |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 96 | |
dnj@chromium.org | 605d81d | 2015-09-18 22:33:53 +0000 | [diff] [blame] | 97 | def ensure_gsutil(version, target, clean): |
hinoka@chromium.org | 7a79054 | 2014-12-10 02:04:39 +0000 | [diff] [blame] | 98 | bin_dir = os.path.join(target, 'gsutil_%s' % version) |
| 99 | gsutil_bin = os.path.join(bin_dir, 'gsutil', 'gsutil') |
Ryan Tseng | 83fd81f | 2017-10-23 11:13:48 -0700 | [diff] [blame] | 100 | gsutil_flag = os.path.join(bin_dir, 'gsutil', 'install.flag') |
| 101 | # We assume that if gsutil_flag exists, then we have a good version |
| 102 | # of the gsutil package. |
| 103 | if not clean and os.path.isfile(gsutil_flag): |
hinoka@chromium.org | 7a79054 | 2014-12-10 02:04:39 +0000 | [diff] [blame] | 104 | # Everything is awesome! we're all done here. |
| 105 | return gsutil_bin |
| 106 | |
dnj@chromium.org | 605d81d | 2015-09-18 22:33:53 +0000 | [diff] [blame] | 107 | if not os.path.exists(target): |
Josip Sokcevic | fa474e8 | 2021-09-17 16:59:49 +0000 | [diff] [blame] | 108 | try: |
| 109 | os.makedirs(target) |
| 110 | except FileExistsError: |
| 111 | # Another process is prepping workspace, so let's check if gsutil_bin is |
| 112 | # present. If after several checks it's still not, continue with |
| 113 | # downloading gsutil. |
| 114 | delay = 2 # base delay, in seconds |
| 115 | for _ in range(3): # make N attempts |
| 116 | # sleep first as it's not expected to have file ready just yet. |
| 117 | time.sleep(delay) |
| 118 | delay *= 1.5 # next delay increased by that factor |
| 119 | if os.path.isfile(gsutil_bin): |
| 120 | return gsutil_bin |
| 121 | |
dnj@chromium.org | 605d81d | 2015-09-18 22:33:53 +0000 | [diff] [blame] | 122 | with temporary_directory(target) as instance_dir: |
hinoka@chromium.org | 7a79054 | 2014-12-10 02:04:39 +0000 | [diff] [blame] | 123 | # Clean up if we're redownloading a corrupted gsutil. |
dnj@chromium.org | 605d81d | 2015-09-18 22:33:53 +0000 | [diff] [blame] | 124 | cleanup_path = os.path.join(instance_dir, 'clean') |
| 125 | try: |
| 126 | os.rename(bin_dir, cleanup_path) |
| 127 | except (OSError, IOError): |
| 128 | cleanup_path = None |
| 129 | if cleanup_path: |
| 130 | shutil.rmtree(cleanup_path) |
| 131 | |
Takuto Ikuta | 8daf244 | 2021-10-28 05:51:18 +0000 | [diff] [blame] | 132 | download_dir = os.path.join(instance_dir, 'd') |
dnj@chromium.org | 605d81d | 2015-09-18 22:33:53 +0000 | [diff] [blame] | 133 | target_zip_filename = download_gsutil(version, instance_dir) |
| 134 | with zipfile.ZipFile(target_zip_filename, 'r') as target_zip: |
| 135 | target_zip.extractall(download_dir) |
| 136 | |
Joanna Wang | 07d6e69 | 2022-09-08 01:49:38 +0000 | [diff] [blame] | 137 | shutil.move(download_dir, bin_dir) |
Ryan Tseng | 83fd81f | 2017-10-23 11:13:48 -0700 | [diff] [blame] | 138 | # Final check that the gsutil bin exists. This should never fail. |
| 139 | if not os.path.isfile(gsutil_bin): |
| 140 | raise InvalidGsutilError() |
| 141 | # Drop a flag file. |
| 142 | with open(gsutil_flag, 'w') as f: |
| 143 | f.write('This flag file is dropped by gsutil.py') |
hinoka@chromium.org | 7a79054 | 2014-12-10 02:04:39 +0000 | [diff] [blame] | 144 | |
hinoka@chromium.org | 7a79054 | 2014-12-10 02:04:39 +0000 | [diff] [blame] | 145 | return gsutil_bin |
| 146 | |
| 147 | |
Aravind Vasudevan | 7af6169 | 2023-01-09 23:15:15 +0000 | [diff] [blame] | 148 | def _is_luci_context(): |
| 149 | """Returns True if the script is run within luci-context""" |
| 150 | luci_context_env = os.getenv('LUCI_CONTEXT') |
| 151 | if not luci_context_env: |
| 152 | return False |
| 153 | |
| 154 | try: |
| 155 | with open(luci_context_env) as f: |
| 156 | luci_context_json = json.load(f) |
| 157 | return 'local_auth' in luci_context_json |
| 158 | except (ValueError, FileNotFoundError): |
| 159 | return False |
| 160 | |
| 161 | |
| 162 | def luci_context(cmd): |
| 163 | """Helper to call`luci-auth context`.""" |
Aravind Vasudevan | effdecd | 2023-01-30 17:02:17 +0000 | [diff] [blame] | 164 | p = _luci_auth_cmd('context', wrapped_cmds=cmd) |
| 165 | |
| 166 | # If luci-auth is not logged in, fallback to normal execution. |
| 167 | if b'Not logged in.' in p.stderr: |
| 168 | return _run_subprocess(cmd, interactive=True) |
| 169 | |
Aravind Vasudevan | f15baea | 2023-02-16 19:07:12 +0000 | [diff] [blame] | 170 | if p.stdout: |
| 171 | print(p.stdout.decode('utf-8'), end='') |
| 172 | |
| 173 | if p.stderr: |
| 174 | print(p.stderr.decode('utf-8'), file=sys.stderr, end='') |
| 175 | |
Aravind Vasudevan | effdecd | 2023-01-30 17:02:17 +0000 | [diff] [blame] | 176 | return p |
Aravind Vasudevan | 7af6169 | 2023-01-09 23:15:15 +0000 | [diff] [blame] | 177 | |
| 178 | |
| 179 | def luci_login(): |
| 180 | """Helper to run `luci-auth login`.""" |
Aravind Vasudevan | 1757677 | 2023-01-13 19:50:51 +0000 | [diff] [blame] | 181 | # luci-auth requires interactive shell. |
| 182 | return _luci_auth_cmd('login', interactive=True) |
Aravind Vasudevan | 7af6169 | 2023-01-09 23:15:15 +0000 | [diff] [blame] | 183 | |
| 184 | |
Aravind Vasudevan | 1757677 | 2023-01-13 19:50:51 +0000 | [diff] [blame] | 185 | def _luci_auth_cmd(luci_cmd, wrapped_cmds=None, interactive=False): |
Aravind Vasudevan | 7af6169 | 2023-01-09 23:15:15 +0000 | [diff] [blame] | 186 | """Helper to call luci-auth command.""" |
Aravind Vasudevan | 7af6169 | 2023-01-09 23:15:15 +0000 | [diff] [blame] | 187 | cmd = ['luci-auth', luci_cmd, '-scopes', ' '.join(LUCI_AUTH_SCOPES)] |
| 188 | if wrapped_cmds: |
| 189 | cmd += ['--'] + wrapped_cmds |
| 190 | |
Aravind Vasudevan | effdecd | 2023-01-30 17:02:17 +0000 | [diff] [blame] | 191 | return _run_subprocess(cmd, interactive) |
Aravind Vasudevan | b7d8efd | 2023-01-27 18:46:40 +0000 | [diff] [blame] | 192 | |
| 193 | |
Aravind Vasudevan | 1757677 | 2023-01-13 19:50:51 +0000 | [diff] [blame] | 194 | def _run_subprocess(cmd, interactive=False, env=None): |
Aravind Vasudevan | 7af6169 | 2023-01-09 23:15:15 +0000 | [diff] [blame] | 195 | """Wrapper to run the given command within a subprocess.""" |
Aravind Vasudevan | 1757677 | 2023-01-13 19:50:51 +0000 | [diff] [blame] | 196 | kwargs = {'shell': IS_WINDOWS} |
| 197 | |
| 198 | if env: |
| 199 | kwargs['env'] = dict(os.environ, **env) |
| 200 | |
| 201 | if not interactive: |
| 202 | kwargs['stdout'] = subprocess.PIPE |
| 203 | kwargs['stderr'] = subprocess.PIPE |
| 204 | |
| 205 | return subprocess.run(cmd, **kwargs) |
Aravind Vasudevan | 7af6169 | 2023-01-09 23:15:15 +0000 | [diff] [blame] | 206 | |
| 207 | |
Aravind Vasudevan | 7b1f98e | 2023-01-18 17:34:15 +0000 | [diff] [blame] | 208 | def is_boto_present(): |
| 209 | """Returns true if the .boto file is present in the default path.""" |
Aravind Vasudevan | f15baea | 2023-02-16 19:07:12 +0000 | [diff] [blame] | 210 | return os.path.isfile(os.path.join(os.path.expanduser('~'), '.boto')) |
Aravind Vasudevan | 7b1f98e | 2023-01-18 17:34:15 +0000 | [diff] [blame] | 211 | |
| 212 | |
Josip Sokcevic | fa474e8 | 2021-09-17 16:59:49 +0000 | [diff] [blame] | 213 | def run_gsutil(target, args, clean=False): |
Aravind Vasudevan | 7af6169 | 2023-01-09 23:15:15 +0000 | [diff] [blame] | 214 | # Redirect gsutil config calls to luci-auth. |
Aravind Vasudevan | 9ae55e5 | 2023-02-14 22:18:58 +0000 | [diff] [blame] | 215 | if 'config' in args: |
Aravind Vasudevan | 1757677 | 2023-01-13 19:50:51 +0000 | [diff] [blame] | 216 | return luci_login().returncode |
Aravind Vasudevan | 7af6169 | 2023-01-09 23:15:15 +0000 | [diff] [blame] | 217 | |
Josip Sokcevic | fa474e8 | 2021-09-17 16:59:49 +0000 | [diff] [blame] | 218 | gsutil_bin = ensure_gsutil(VERSION, target, clean) |
| 219 | args_opt = ['-o', 'GSUtil:software_update_check_period=0'] |
Dan Jacques | 509776e | 2017-09-07 18:01:08 -0700 | [diff] [blame] | 220 | |
Josip Sokcevic | fa474e8 | 2021-09-17 16:59:49 +0000 | [diff] [blame] | 221 | if sys.platform == 'darwin': |
| 222 | # We are experiencing problems with multiprocessing on MacOS where gsutil.py |
| 223 | # may hang. |
| 224 | # This behavior is documented in gsutil codebase, and recommendation is to |
| 225 | # set GSUtil:parallel_process_count=1. |
| 226 | # https://github.com/GoogleCloudPlatform/gsutil/blob/06efc9dc23719fab4fd5fadb506d252bbd3fe0dd/gslib/command.py#L1331 |
| 227 | # https://github.com/GoogleCloudPlatform/gsutil/issues/1100 |
| 228 | args_opt.extend(['-o', 'GSUtil:parallel_process_count=1']) |
Chris Nardi | ab816ce | 2017-10-31 15:45:05 -0400 | [diff] [blame] | 229 | if sys.platform == 'cygwin': |
| 230 | # This script requires Windows Python, so invoke with depot_tools' |
| 231 | # Python. |
| 232 | def winpath(path): |
Edward Lesmes | 94d6f48 | 2019-11-04 20:55:09 +0000 | [diff] [blame] | 233 | stdout = subprocess.check_output(['cygpath', '-w', path]) |
| 234 | return stdout.strip().decode('utf-8', 'replace') |
Chris Nardi | ab816ce | 2017-10-31 15:45:05 -0400 | [diff] [blame] | 235 | cmd = ['python.bat', winpath(__file__)] |
| 236 | cmd.extend(args) |
| 237 | sys.exit(subprocess.call(cmd)) |
| 238 | assert sys.platform != 'cygwin' |
| 239 | |
Dan Jacques | 509776e | 2017-09-07 18:01:08 -0700 | [diff] [blame] | 240 | cmd = [ |
Josip Sokcevic | 1909696 | 2022-03-10 17:56:09 +0000 | [diff] [blame] | 241 | 'vpython3', |
| 242 | '-vpython-spec', os.path.join(THIS_DIR, 'gsutil.vpython3'), |
Gavin Mak | 37db69d | 2022-03-10 00:54:39 +0000 | [diff] [blame] | 243 | '--', |
Dan Jacques | 509776e | 2017-09-07 18:01:08 -0700 | [diff] [blame] | 244 | gsutil_bin |
Josip Sokcevic | fa474e8 | 2021-09-17 16:59:49 +0000 | [diff] [blame] | 245 | ] + args_opt + args |
Aravind Vasudevan | 7af6169 | 2023-01-09 23:15:15 +0000 | [diff] [blame] | 246 | |
Aravind Vasudevan | f15baea | 2023-02-16 19:07:12 +0000 | [diff] [blame] | 247 | # Bypass luci-auth when run within a bot or .boto file is set. |
| 248 | if (_is_luci_context() or os.getenv('SWARMING_HEADLESS') == '1' |
| 249 | or os.getenv('BOTO_CONFIG') or os.getenv('AWS_CREDENTIAL_FILE') |
| 250 | or is_boto_present()): |
Aravind Vasudevan | 1757677 | 2023-01-13 19:50:51 +0000 | [diff] [blame] | 251 | return _run_subprocess(cmd, interactive=True).returncode |
Aravind Vasudevan | 7af6169 | 2023-01-09 23:15:15 +0000 | [diff] [blame] | 252 | |
Aravind Vasudevan | 1757677 | 2023-01-13 19:50:51 +0000 | [diff] [blame] | 253 | return luci_context(cmd).returncode |
hinoka@chromium.org | 7a79054 | 2014-12-10 02:04:39 +0000 | [diff] [blame] | 254 | |
| 255 | |
| 256 | def parse_args(): |
dnj@chromium.org | 605d81d | 2015-09-18 22:33:53 +0000 | [diff] [blame] | 257 | bin_dir = os.environ.get('DEPOT_TOOLS_GSUTIL_BIN_DIR', DEFAULT_BIN_DIR) |
| 258 | |
Josip Sokcevic | c1fd44b | 2021-09-20 22:31:37 +0000 | [diff] [blame] | 259 | # Help is disabled as it conflicts with gsutil -h, which controls headers. |
| 260 | parser = argparse.ArgumentParser(add_help=False) |
Josip Sokcevic | fa474e8 | 2021-09-17 16:59:49 +0000 | [diff] [blame] | 261 | |
dnj@chromium.org | 605d81d | 2015-09-18 22:33:53 +0000 | [diff] [blame] | 262 | parser.add_argument('--clean', action='store_true', |
| 263 | help='Clear any existing gsutil package, forcing a new download.') |
dnj@chromium.org | 605d81d | 2015-09-18 22:33:53 +0000 | [diff] [blame] | 264 | parser.add_argument('--target', default=bin_dir, |
| 265 | help='The target directory to download/store a gsutil version in. ' |
| 266 | '(default is %(default)s).') |
Josip Sokcevic | fa474e8 | 2021-09-17 16:59:49 +0000 | [diff] [blame] | 267 | |
| 268 | # These two args exist for backwards-compatibility but are no-ops. |
| 269 | parser.add_argument('--force-version', default=VERSION, |
| 270 | help='(deprecated, this flag has no effect)') |
| 271 | parser.add_argument('--fallback', |
| 272 | help='(deprecated, this flag has no effect)') |
| 273 | |
hinoka@chromium.org | 7a79054 | 2014-12-10 02:04:39 +0000 | [diff] [blame] | 274 | parser.add_argument('args', nargs=argparse.REMAINDER) |
| 275 | |
hinoka@chromium.org | c13b054 | 2014-12-18 01:06:20 +0000 | [diff] [blame] | 276 | args, extras = parser.parse_known_args() |
| 277 | if args.args and args.args[0] == '--': |
| 278 | args.args.pop(0) |
| 279 | if extras: |
| 280 | args.args = extras + args.args |
dnj@chromium.org | 605d81d | 2015-09-18 22:33:53 +0000 | [diff] [blame] | 281 | return args |
hinoka@chromium.org | 7a79054 | 2014-12-10 02:04:39 +0000 | [diff] [blame] | 282 | |
| 283 | |
| 284 | def main(): |
dnj@chromium.org | 605d81d | 2015-09-18 22:33:53 +0000 | [diff] [blame] | 285 | args = parse_args() |
Josip Sokcevic | fa474e8 | 2021-09-17 16:59:49 +0000 | [diff] [blame] | 286 | return run_gsutil(args.target, args.args, clean=args.clean) |
hinoka@chromium.org | 7a79054 | 2014-12-10 02:04:39 +0000 | [diff] [blame] | 287 | |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 288 | |
hinoka@chromium.org | 7a79054 | 2014-12-10 02:04:39 +0000 | [diff] [blame] | 289 | if __name__ == '__main__': |
| 290 | sys.exit(main()) |