blob: 8b1e523f0d2d78e98e232da09409cedecac04a6f [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"""
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
162def luci_context(cmd):
163 """Helper to call`luci-auth context`."""
Aravind Vasudevaneffdecd2023-01-30 17:02:17 +0000164 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
170 if p.stdout:
Aravind Vasudevanef2d0112023-02-03 22:50:21 +0000171 print(p.stdout.decode('utf-8'), end='')
Aravind Vasudevaneffdecd2023-01-30 17:02:17 +0000172
173 if p.stderr:
Aravind Vasudevanef2d0112023-02-03 22:50:21 +0000174 print(p.stderr.decode('utf-8'), file=sys.stderr, end='')
Aravind Vasudevaneffdecd2023-01-30 17:02:17 +0000175
176 return p
Aravind Vasudevan7af61692023-01-09 23:15:15 +0000177
178
179def luci_login():
180 """Helper to run `luci-auth login`."""
Aravind Vasudevan17576772023-01-13 19:50:51 +0000181 # luci-auth requires interactive shell.
182 return _luci_auth_cmd('login', interactive=True)
Aravind Vasudevan7af61692023-01-09 23:15:15 +0000183
184
Aravind Vasudevan17576772023-01-13 19:50:51 +0000185def _luci_auth_cmd(luci_cmd, wrapped_cmds=None, interactive=False):
Aravind Vasudevan7af61692023-01-09 23:15:15 +0000186 """Helper to call luci-auth command."""
Aravind Vasudevan7af61692023-01-09 23:15:15 +0000187 cmd = ['luci-auth', luci_cmd, '-scopes', ' '.join(LUCI_AUTH_SCOPES)]
188 if wrapped_cmds:
189 cmd += ['--'] + wrapped_cmds
190
Aravind Vasudevaneffdecd2023-01-30 17:02:17 +0000191 return _run_subprocess(cmd, interactive)
Aravind Vasudevanb7d8efd2023-01-27 18:46:40 +0000192
193
Aravind Vasudevan17576772023-01-13 19:50:51 +0000194def _run_subprocess(cmd, interactive=False, env=None):
Aravind Vasudevan7af61692023-01-09 23:15:15 +0000195 """Wrapper to run the given command within a subprocess."""
Aravind Vasudevan17576772023-01-13 19:50:51 +0000196 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 Vasudevan7af61692023-01-09 23:15:15 +0000206
207
Aravind Vasudevan7b1f98e2023-01-18 17:34:15 +0000208def is_boto_present():
209 """Returns true if the .boto file is present in the default path."""
210 return os.path.isfile(os.path.join(os.path.expanduser('~'), '.boto'))
211
212
Josip Sokcevicfa474e82021-09-17 16:59:49 +0000213def run_gsutil(target, args, clean=False):
Aravind Vasudevan7af61692023-01-09 23:15:15 +0000214 # Redirect gsutil config calls to luci-auth.
Aravind Vasudevan9ae55e52023-02-14 22:18:58 +0000215 if 'config' in args:
Aravind Vasudevan17576772023-01-13 19:50:51 +0000216 return luci_login().returncode
Aravind Vasudevan7af61692023-01-09 23:15:15 +0000217
Josip Sokcevicfa474e82021-09-17 16:59:49 +0000218 gsutil_bin = ensure_gsutil(VERSION, target, clean)
219 args_opt = ['-o', 'GSUtil:software_update_check_period=0']
Dan Jacques509776e2017-09-07 18:01:08 -0700220
Josip Sokcevicfa474e82021-09-17 16:59:49 +0000221 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 Nardiab816ce2017-10-31 15:45:05 -0400229 if sys.platform == 'cygwin':
230 # This script requires Windows Python, so invoke with depot_tools'
231 # Python.
232 def winpath(path):
Edward Lesmes94d6f482019-11-04 20:55:09 +0000233 stdout = subprocess.check_output(['cygpath', '-w', path])
234 return stdout.strip().decode('utf-8', 'replace')
Chris Nardiab816ce2017-10-31 15:45:05 -0400235 cmd = ['python.bat', winpath(__file__)]
236 cmd.extend(args)
237 sys.exit(subprocess.call(cmd))
238 assert sys.platform != 'cygwin'
239
Dan Jacques509776e2017-09-07 18:01:08 -0700240 cmd = [
Josip Sokcevic19096962022-03-10 17:56:09 +0000241 'vpython3',
242 '-vpython-spec', os.path.join(THIS_DIR, 'gsutil.vpython3'),
Gavin Mak37db69d2022-03-10 00:54:39 +0000243 '--',
Dan Jacques509776e2017-09-07 18:01:08 -0700244 gsutil_bin
Josip Sokcevicfa474e82021-09-17 16:59:49 +0000245 ] + args_opt + args
Aravind Vasudevan7af61692023-01-09 23:15:15 +0000246
247 # Bypass luci-auth when run within a bot or .boto file is set.
Aravind Vasudevan9ae55e52023-02-14 22:18:58 +0000248 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 Vasudevan17576772023-01-13 19:50:51 +0000251 return _run_subprocess(cmd, interactive=True).returncode
Aravind Vasudevan7af61692023-01-09 23:15:15 +0000252
Aravind Vasudevan17576772023-01-13 19:50:51 +0000253 return luci_context(cmd).returncode
hinoka@chromium.org7a790542014-12-10 02:04:39 +0000254
255
256def parse_args():
dnj@chromium.org605d81d2015-09-18 22:33:53 +0000257 bin_dir = os.environ.get('DEPOT_TOOLS_GSUTIL_BIN_DIR', DEFAULT_BIN_DIR)
258
Josip Sokcevicc1fd44b2021-09-20 22:31:37 +0000259 # Help is disabled as it conflicts with gsutil -h, which controls headers.
260 parser = argparse.ArgumentParser(add_help=False)
Josip Sokcevicfa474e82021-09-17 16:59:49 +0000261
dnj@chromium.org605d81d2015-09-18 22:33:53 +0000262 parser.add_argument('--clean', action='store_true',
263 help='Clear any existing gsutil package, forcing a new download.')
dnj@chromium.org605d81d2015-09-18 22:33:53 +0000264 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 Sokcevicfa474e82021-09-17 16:59:49 +0000267
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.org7a790542014-12-10 02:04:39 +0000274 parser.add_argument('args', nargs=argparse.REMAINDER)
275
hinoka@chromium.orgc13b0542014-12-18 01:06:20 +0000276 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.org605d81d2015-09-18 22:33:53 +0000281 return args
hinoka@chromium.org7a790542014-12-10 02:04:39 +0000282
283
284def main():
dnj@chromium.org605d81d2015-09-18 22:33:53 +0000285 args = parse_args()
Josip Sokcevicfa474e82021-09-17 16:59:49 +0000286 return run_gsutil(args.target, args.args, clean=args.clean)
hinoka@chromium.org7a790542014-12-10 02:04:39 +0000287
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000288
hinoka@chromium.org7a790542014-12-10 02:04:39 +0000289if __name__ == '__main__':
290 sys.exit(main())