blob: eac6e9d86e3b5fada4a08dd42600bc472cc2015f [file] [log] [blame]
Josip Sokcevicfb12b3f2021-04-19 18:09:50 +00001#!/usr/bin/env python3
hinoka@chromium.org7a790542014-12-10 02:04:39 +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"""Run a pinned gsutil."""
7
Aravind Vasudevan7af61692023-01-09 23:15:15 +00008from __future__ import print_function
hinoka@chromium.org7a790542014-12-10 02:04:39 +00009
10import argparse
hinoka@chromium.org7a790542014-12-10 02:04:39 +000011import base64
dnj@chromium.org605d81d2015-09-18 22:33:53 +000012import contextlib
primiano@chromium.orgdf351762014-12-18 11:12:34 +000013import hashlib
hinoka@chromium.org7a790542014-12-10 02:04:39 +000014import json
primiano@chromium.orgdf351762014-12-18 11:12:34 +000015import os
16import shutil
hinoka@chromium.org7a790542014-12-10 02:04:39 +000017import subprocess
primiano@chromium.orgdf351762014-12-18 11:12:34 +000018import sys
dnj@chromium.org605d81d2015-09-18 22:33:53 +000019import tempfile
20import time
Raul Tambreb946b232019-03-26 14:48:46 +000021
22try:
23 import urllib2 as urllib
24except ImportError: # For Py3 compatibility
25 import urllib.request as urllib
26
primiano@chromium.orgdf351762014-12-18 11:12:34 +000027import zipfile
hinoka@chromium.org7a790542014-12-10 02:04:39 +000028
29
30GSUTIL_URL = 'https://storage.googleapis.com/pub/'
31API_URL = 'https://www.googleapis.com/storage/v1/b/pub/o/'
32
33THIS_DIR = os.path.dirname(os.path.abspath(__file__))
34DEFAULT_BIN_DIR = os.path.join(THIS_DIR, 'external_bin', 'gsutil')
hinoka@chromium.org7a790542014-12-10 02:04:39 +000035
Dan Jacques509776e2017-09-07 18:01:08 -070036IS_WINDOWS = os.name == 'nt'
37
Josip Sokcevic19096962022-03-10 17:56:09 +000038VERSION = '4.68'
Josip Sokcevicfa474e82021-09-17 16:59:49 +000039
Aravind Vasudevan7af61692023-01-09 23:15:15 +000040# Google OAuth Context required by gsutil.
41LUCI_AUTH_SCOPES = [
42 'https://www.googleapis.com/auth/devstorage.full_control',
43 'https://www.googleapis.com/auth/userinfo.email',
44]
45
Dan Jacques509776e2017-09-07 18:01:08 -070046
hinoka@chromium.org7a790542014-12-10 02:04:39 +000047class InvalidGsutilError(Exception):
48 pass
49
50
hinoka@chromium.org7a790542014-12-10 02:04:39 +000051def 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 Tambreb946b232019-03-26 14:48:46 +000068 metadata = json.load(urllib.urlopen(metadata_url))
Edward Lemur83aafc92019-11-25 23:25:05 +000069 remote_md5 = base64.b64decode(metadata['md5Hash']).decode('utf-8')
hinoka@chromium.org7a790542014-12-10 02:04:39 +000070
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 Tambreb946b232019-03-26 14:48:46 +000077 u = urllib.urlopen(url)
hinoka@chromium.org7a790542014-12-10 02:04:39 +000078 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.org605d81d2015-09-18 22:33:53 +000087@contextlib.contextmanager
88def temporary_directory(base):
Takuto Ikuta8daf2442021-10-28 05:51:18 +000089 tmpdir = tempfile.mkdtemp(prefix='t', dir=base)
dnj@chromium.org605d81d2015-09-18 22:33:53 +000090 try:
91 yield tmpdir
92 finally:
93 if os.path.isdir(tmpdir):
94 shutil.rmtree(tmpdir)
95
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000096
dnj@chromium.org605d81d2015-09-18 22:33:53 +000097def ensure_gsutil(version, target, clean):
hinoka@chromium.org7a790542014-12-10 02:04:39 +000098 bin_dir = os.path.join(target, 'gsutil_%s' % version)
99 gsutil_bin = os.path.join(bin_dir, 'gsutil', 'gsutil')
Ryan Tseng83fd81f2017-10-23 11:13:48 -0700100 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.org7a790542014-12-10 02:04:39 +0000104 # Everything is awesome! we're all done here.
105 return gsutil_bin
106
dnj@chromium.org605d81d2015-09-18 22:33:53 +0000107 if not os.path.exists(target):
Josip Sokcevicfa474e82021-09-17 16:59:49 +0000108 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.org605d81d2015-09-18 22:33:53 +0000122 with temporary_directory(target) as instance_dir:
hinoka@chromium.org7a790542014-12-10 02:04:39 +0000123 # Clean up if we're redownloading a corrupted gsutil.
dnj@chromium.org605d81d2015-09-18 22:33:53 +0000124 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 Ikuta8daf2442021-10-28 05:51:18 +0000132 download_dir = os.path.join(instance_dir, 'd')
dnj@chromium.org605d81d2015-09-18 22:33:53 +0000133 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 Wang07d6e692022-09-08 01:49:38 +0000137 shutil.move(download_dir, bin_dir)
Ryan Tseng83fd81f2017-10-23 11:13:48 -0700138 # 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.org7a790542014-12-10 02:04:39 +0000144
hinoka@chromium.org7a790542014-12-10 02:04:39 +0000145 return gsutil_bin
146
147
Aravind Vasudevan7af61692023-01-09 23:15:15 +0000148def _is_luci_context():
149 """Returns True if the script is run within luci-context"""
Aravind Vasudevan3879bd82023-02-16 23:09:33 +0000150 if os.getenv('SWARMING_HEADLESS') == '1':
151 return True
152
Aravind Vasudevan7af61692023-01-09 23:15:15 +0000153 luci_context_env = os.getenv('LUCI_CONTEXT')
154 if not luci_context_env:
155 return False
156
157 try:
158 with open(luci_context_env) as f:
159 luci_context_json = json.load(f)
160 return 'local_auth' in luci_context_json
161 except (ValueError, FileNotFoundError):
162 return False
163
164
165def luci_context(cmd):
166 """Helper to call`luci-auth context`."""
Aravind Vasudevaneffdecd2023-01-30 17:02:17 +0000167 p = _luci_auth_cmd('context', wrapped_cmds=cmd)
168
169 # If luci-auth is not logged in, fallback to normal execution.
170 if b'Not logged in.' in p.stderr:
171 return _run_subprocess(cmd, interactive=True)
172
Aravind Vasudevan3879bd82023-02-16 23:09:33 +0000173 _print_subprocess_result(p)
Aravind Vasudevaneffdecd2023-01-30 17:02:17 +0000174 return p
Aravind Vasudevan7af61692023-01-09 23:15:15 +0000175
176
177def luci_login():
178 """Helper to run `luci-auth login`."""
Aravind Vasudevan17576772023-01-13 19:50:51 +0000179 # luci-auth requires interactive shell.
180 return _luci_auth_cmd('login', interactive=True)
Aravind Vasudevan7af61692023-01-09 23:15:15 +0000181
182
Aravind Vasudevan17576772023-01-13 19:50:51 +0000183def _luci_auth_cmd(luci_cmd, wrapped_cmds=None, interactive=False):
Aravind Vasudevan7af61692023-01-09 23:15:15 +0000184 """Helper to call luci-auth command."""
Aravind Vasudevan7af61692023-01-09 23:15:15 +0000185 cmd = ['luci-auth', luci_cmd, '-scopes', ' '.join(LUCI_AUTH_SCOPES)]
186 if wrapped_cmds:
187 cmd += ['--'] + wrapped_cmds
188
Aravind Vasudevaneffdecd2023-01-30 17:02:17 +0000189 return _run_subprocess(cmd, interactive)
Aravind Vasudevanb7d8efd2023-01-27 18:46:40 +0000190
191
Aravind Vasudevan17576772023-01-13 19:50:51 +0000192def _run_subprocess(cmd, interactive=False, env=None):
Aravind Vasudevan7af61692023-01-09 23:15:15 +0000193 """Wrapper to run the given command within a subprocess."""
Aravind Vasudevan17576772023-01-13 19:50:51 +0000194 kwargs = {'shell': IS_WINDOWS}
195
196 if env:
197 kwargs['env'] = dict(os.environ, **env)
198
199 if not interactive:
200 kwargs['stdout'] = subprocess.PIPE
201 kwargs['stderr'] = subprocess.PIPE
202
203 return subprocess.run(cmd, **kwargs)
Aravind Vasudevan7af61692023-01-09 23:15:15 +0000204
205
Aravind Vasudevan3879bd82023-02-16 23:09:33 +0000206def _print_subprocess_result(p):
207 """Prints the subprocess result to stdout & stderr."""
208 if p.stdout:
209 sys.stdout.buffer.write(p.stdout)
210
211 if p.stderr:
212 sys.stderr.buffer.write(p.stderr)
213
214
Aravind Vasudevan7b1f98e2023-01-18 17:34:15 +0000215def is_boto_present():
216 """Returns true if the .boto file is present in the default path."""
Aravind Vasudevan3879bd82023-02-16 23:09:33 +0000217 return os.getenv('BOTO_CONFIG') or os.getenv(
218 'AWS_CREDENTIAL_FILE') or os.path.isfile(
219 os.path.join(os.path.expanduser('~'), '.boto'))
Aravind Vasudevan7b1f98e2023-01-18 17:34:15 +0000220
221
Josip Sokcevicfa474e82021-09-17 16:59:49 +0000222def run_gsutil(target, args, clean=False):
Aravind Vasudevan7af61692023-01-09 23:15:15 +0000223 # Redirect gsutil config calls to luci-auth.
Aravind Vasudevan9ae55e52023-02-14 22:18:58 +0000224 if 'config' in args:
Aravind Vasudevan17576772023-01-13 19:50:51 +0000225 return luci_login().returncode
Aravind Vasudevan7af61692023-01-09 23:15:15 +0000226
Josip Sokcevicfa474e82021-09-17 16:59:49 +0000227 gsutil_bin = ensure_gsutil(VERSION, target, clean)
228 args_opt = ['-o', 'GSUtil:software_update_check_period=0']
Dan Jacques509776e2017-09-07 18:01:08 -0700229
Josip Sokcevicfa474e82021-09-17 16:59:49 +0000230 if sys.platform == 'darwin':
231 # We are experiencing problems with multiprocessing on MacOS where gsutil.py
232 # may hang.
233 # This behavior is documented in gsutil codebase, and recommendation is to
234 # set GSUtil:parallel_process_count=1.
235 # https://github.com/GoogleCloudPlatform/gsutil/blob/06efc9dc23719fab4fd5fadb506d252bbd3fe0dd/gslib/command.py#L1331
236 # https://github.com/GoogleCloudPlatform/gsutil/issues/1100
237 args_opt.extend(['-o', 'GSUtil:parallel_process_count=1'])
Chris Nardiab816ce2017-10-31 15:45:05 -0400238 if sys.platform == 'cygwin':
239 # This script requires Windows Python, so invoke with depot_tools'
240 # Python.
241 def winpath(path):
Edward Lesmes94d6f482019-11-04 20:55:09 +0000242 stdout = subprocess.check_output(['cygpath', '-w', path])
243 return stdout.strip().decode('utf-8', 'replace')
Chris Nardiab816ce2017-10-31 15:45:05 -0400244 cmd = ['python.bat', winpath(__file__)]
245 cmd.extend(args)
246 sys.exit(subprocess.call(cmd))
247 assert sys.platform != 'cygwin'
248
Dan Jacques509776e2017-09-07 18:01:08 -0700249 cmd = [
Josip Sokcevic19096962022-03-10 17:56:09 +0000250 'vpython3',
251 '-vpython-spec', os.path.join(THIS_DIR, 'gsutil.vpython3'),
Gavin Mak37db69d2022-03-10 00:54:39 +0000252 '--',
Dan Jacques509776e2017-09-07 18:01:08 -0700253 gsutil_bin
Josip Sokcevicfa474e82021-09-17 16:59:49 +0000254 ] + args_opt + args
Aravind Vasudevan7af61692023-01-09 23:15:15 +0000255
Aravind Vasudevan3879bd82023-02-16 23:09:33 +0000256 # When .boto is present, try without additional wrappers and handle specific
257 # errors.
258 if is_boto_present():
259 p = _run_subprocess(cmd)
260
261 # Notify user that their .boto file might be outdated.
262 if b'Your credentials are invalid.' in p.stderr:
Bruce Dawson04206432023-03-03 23:05:19 +0000263 # Make sure this error message is visible when invoked by gclient runhooks
264 separator = '*' * 80
Aravind Vasudevan3879bd82023-02-16 23:09:33 +0000265 print(
Bruce Dawson04206432023-03-03 23:05:19 +0000266 '\n' + separator + '\n' +
Aravind Vasudevan3879bd82023-02-16 23:09:33 +0000267 'Warning: You might have an outdated .boto file. If this issue '
268 'persists after running `gsutil.py config`, try removing your '
Josip Sokcevicdfafd0a2023-08-17 15:32:57 +0000269 '.boto, usually located in your home directory.\n' + separator + '\n',
Aravind Vasudevan3879bd82023-02-16 23:09:33 +0000270 file=sys.stderr)
271
272 _print_subprocess_result(p)
273 return p.returncode
274
275 # Skip wrapping commands if luci-auth is already being
276 if _is_luci_context():
Aravind Vasudevan17576772023-01-13 19:50:51 +0000277 return _run_subprocess(cmd, interactive=True).returncode
Aravind Vasudevan7af61692023-01-09 23:15:15 +0000278
Aravind Vasudevan3879bd82023-02-16 23:09:33 +0000279 # Wrap gsutil with luci-auth context.
Aravind Vasudevan17576772023-01-13 19:50:51 +0000280 return luci_context(cmd).returncode
hinoka@chromium.org7a790542014-12-10 02:04:39 +0000281
282
283def parse_args():
dnj@chromium.org605d81d2015-09-18 22:33:53 +0000284 bin_dir = os.environ.get('DEPOT_TOOLS_GSUTIL_BIN_DIR', DEFAULT_BIN_DIR)
285
Josip Sokcevicc1fd44b2021-09-20 22:31:37 +0000286 # Help is disabled as it conflicts with gsutil -h, which controls headers.
287 parser = argparse.ArgumentParser(add_help=False)
Josip Sokcevicfa474e82021-09-17 16:59:49 +0000288
dnj@chromium.org605d81d2015-09-18 22:33:53 +0000289 parser.add_argument('--clean', action='store_true',
290 help='Clear any existing gsutil package, forcing a new download.')
dnj@chromium.org605d81d2015-09-18 22:33:53 +0000291 parser.add_argument('--target', default=bin_dir,
292 help='The target directory to download/store a gsutil version in. '
293 '(default is %(default)s).')
Josip Sokcevicfa474e82021-09-17 16:59:49 +0000294
295 # These two args exist for backwards-compatibility but are no-ops.
296 parser.add_argument('--force-version', default=VERSION,
297 help='(deprecated, this flag has no effect)')
298 parser.add_argument('--fallback',
299 help='(deprecated, this flag has no effect)')
300
hinoka@chromium.org7a790542014-12-10 02:04:39 +0000301 parser.add_argument('args', nargs=argparse.REMAINDER)
302
hinoka@chromium.orgc13b0542014-12-18 01:06:20 +0000303 args, extras = parser.parse_known_args()
304 if args.args and args.args[0] == '--':
305 args.args.pop(0)
306 if extras:
307 args.args = extras + args.args
dnj@chromium.org605d81d2015-09-18 22:33:53 +0000308 return args
hinoka@chromium.org7a790542014-12-10 02:04:39 +0000309
310
311def main():
dnj@chromium.org605d81d2015-09-18 22:33:53 +0000312 args = parse_args()
Josip Sokcevicfa474e82021-09-17 16:59:49 +0000313 return run_gsutil(args.target, args.args, clean=args.clean)
hinoka@chromium.org7a790542014-12-10 02:04:39 +0000314
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000315
hinoka@chromium.org7a790542014-12-10 02:04:39 +0000316if __name__ == '__main__':
317 sys.exit(main())