gsutil.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. #!/usr/bin/env python3
  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. """Run a pinned gsutil."""
  6. from __future__ import print_function
  7. import argparse
  8. import base64
  9. import contextlib
  10. import hashlib
  11. import json
  12. import os
  13. import shutil
  14. import subprocess
  15. import sys
  16. import tempfile
  17. import time
  18. try:
  19. import urllib2 as urllib
  20. except ImportError: # For Py3 compatibility
  21. import urllib.request as urllib
  22. import zipfile
  23. GSUTIL_URL = 'https://storage.googleapis.com/pub/'
  24. API_URL = 'https://www.googleapis.com/storage/v1/b/pub/o/'
  25. THIS_DIR = os.path.dirname(os.path.abspath(__file__))
  26. DEFAULT_BIN_DIR = os.path.join(THIS_DIR, 'external_bin', 'gsutil')
  27. IS_WINDOWS = os.name == 'nt'
  28. VERSION = '4.68'
  29. # Google OAuth Context required by gsutil.
  30. LUCI_AUTH_SCOPES = [
  31. 'https://www.googleapis.com/auth/devstorage.full_control',
  32. 'https://www.googleapis.com/auth/userinfo.email',
  33. ]
  34. class InvalidGsutilError(Exception):
  35. pass
  36. def download_gsutil(version, target_dir):
  37. """Downloads gsutil into the target_dir."""
  38. filename = 'gsutil_%s.zip' % version
  39. target_filename = os.path.join(target_dir, filename)
  40. # Check if the target exists already.
  41. if os.path.exists(target_filename):
  42. md5_calc = hashlib.md5()
  43. with open(target_filename, 'rb') as f:
  44. while True:
  45. buf = f.read(4096)
  46. if not buf:
  47. break
  48. md5_calc.update(buf)
  49. local_md5 = md5_calc.hexdigest()
  50. metadata_url = '%s%s' % (API_URL, filename)
  51. metadata = json.load(urllib.urlopen(metadata_url))
  52. remote_md5 = base64.b64decode(metadata['md5Hash']).decode('utf-8')
  53. if local_md5 == remote_md5:
  54. return target_filename
  55. os.remove(target_filename)
  56. # Do the download.
  57. url = '%s%s' % (GSUTIL_URL, filename)
  58. u = urllib.urlopen(url)
  59. with open(target_filename, 'wb') as f:
  60. while True:
  61. buf = u.read(4096)
  62. if not buf:
  63. break
  64. f.write(buf)
  65. return target_filename
  66. @contextlib.contextmanager
  67. def temporary_directory(base):
  68. tmpdir = tempfile.mkdtemp(prefix='t', dir=base)
  69. try:
  70. yield tmpdir
  71. finally:
  72. if os.path.isdir(tmpdir):
  73. shutil.rmtree(tmpdir)
  74. def ensure_gsutil(version, target, clean):
  75. bin_dir = os.path.join(target, 'gsutil_%s' % version)
  76. gsutil_bin = os.path.join(bin_dir, 'gsutil', 'gsutil')
  77. gsutil_flag = os.path.join(bin_dir, 'gsutil', 'install.flag')
  78. # We assume that if gsutil_flag exists, then we have a good version
  79. # of the gsutil package.
  80. if not clean and os.path.isfile(gsutil_flag):
  81. # Everything is awesome! we're all done here.
  82. return gsutil_bin
  83. if not os.path.exists(target):
  84. try:
  85. os.makedirs(target)
  86. except FileExistsError:
  87. # Another process is prepping workspace, so let's check if gsutil_bin is
  88. # present. If after several checks it's still not, continue with
  89. # downloading gsutil.
  90. delay = 2 # base delay, in seconds
  91. for _ in range(3): # make N attempts
  92. # sleep first as it's not expected to have file ready just yet.
  93. time.sleep(delay)
  94. delay *= 1.5 # next delay increased by that factor
  95. if os.path.isfile(gsutil_bin):
  96. return gsutil_bin
  97. with temporary_directory(target) as instance_dir:
  98. # Clean up if we're redownloading a corrupted gsutil.
  99. cleanup_path = os.path.join(instance_dir, 'clean')
  100. try:
  101. os.rename(bin_dir, cleanup_path)
  102. except (OSError, IOError):
  103. cleanup_path = None
  104. if cleanup_path:
  105. shutil.rmtree(cleanup_path)
  106. download_dir = os.path.join(instance_dir, 'd')
  107. target_zip_filename = download_gsutil(version, instance_dir)
  108. with zipfile.ZipFile(target_zip_filename, 'r') as target_zip:
  109. target_zip.extractall(download_dir)
  110. shutil.move(download_dir, bin_dir)
  111. # Final check that the gsutil bin exists. This should never fail.
  112. if not os.path.isfile(gsutil_bin):
  113. raise InvalidGsutilError()
  114. # Drop a flag file.
  115. with open(gsutil_flag, 'w') as f:
  116. f.write('This flag file is dropped by gsutil.py')
  117. return gsutil_bin
  118. def _is_luci_context():
  119. """Returns True if the script is run within luci-context"""
  120. if os.getenv('SWARMING_HEADLESS') == '1':
  121. return True
  122. luci_context_env = os.getenv('LUCI_CONTEXT')
  123. if not luci_context_env:
  124. return False
  125. try:
  126. with open(luci_context_env) as f:
  127. luci_context_json = json.load(f)
  128. return 'local_auth' in luci_context_json
  129. except (ValueError, FileNotFoundError):
  130. return False
  131. def luci_context(cmd):
  132. """Helper to call`luci-auth context`."""
  133. p = _luci_auth_cmd('context', wrapped_cmds=cmd)
  134. # If luci-auth is not logged in, fallback to normal execution.
  135. if b'Not logged in.' in p.stderr:
  136. return _run_subprocess(cmd, interactive=True)
  137. _print_subprocess_result(p)
  138. return p
  139. def luci_login():
  140. """Helper to run `luci-auth login`."""
  141. # luci-auth requires interactive shell.
  142. return _luci_auth_cmd('login', interactive=True)
  143. def _luci_auth_cmd(luci_cmd, wrapped_cmds=None, interactive=False):
  144. """Helper to call luci-auth command."""
  145. cmd = ['luci-auth', luci_cmd, '-scopes', ' '.join(LUCI_AUTH_SCOPES)]
  146. if wrapped_cmds:
  147. cmd += ['--'] + wrapped_cmds
  148. return _run_subprocess(cmd, interactive)
  149. def _run_subprocess(cmd, interactive=False, env=None):
  150. """Wrapper to run the given command within a subprocess."""
  151. kwargs = {'shell': IS_WINDOWS}
  152. if env:
  153. kwargs['env'] = dict(os.environ, **env)
  154. if not interactive:
  155. kwargs['stdout'] = subprocess.PIPE
  156. kwargs['stderr'] = subprocess.PIPE
  157. return subprocess.run(cmd, **kwargs)
  158. def _print_subprocess_result(p):
  159. """Prints the subprocess result to stdout & stderr."""
  160. if p.stdout:
  161. sys.stdout.buffer.write(p.stdout)
  162. if p.stderr:
  163. sys.stderr.buffer.write(p.stderr)
  164. def is_boto_present():
  165. """Returns true if the .boto file is present in the default path."""
  166. return os.getenv('BOTO_CONFIG') or os.getenv(
  167. 'AWS_CREDENTIAL_FILE') or os.path.isfile(
  168. os.path.join(os.path.expanduser('~'), '.boto'))
  169. def run_gsutil(target, args, clean=False):
  170. # Redirect gsutil config calls to luci-auth.
  171. if 'config' in args:
  172. return luci_login().returncode
  173. gsutil_bin = ensure_gsutil(VERSION, target, clean)
  174. args_opt = ['-o', 'GSUtil:software_update_check_period=0']
  175. if sys.platform == 'darwin':
  176. # We are experiencing problems with multiprocessing on MacOS where gsutil.py
  177. # may hang.
  178. # This behavior is documented in gsutil codebase, and recommendation is to
  179. # set GSUtil:parallel_process_count=1.
  180. # https://github.com/GoogleCloudPlatform/gsutil/blob/06efc9dc23719fab4fd5fadb506d252bbd3fe0dd/gslib/command.py#L1331
  181. # https://github.com/GoogleCloudPlatform/gsutil/issues/1100
  182. args_opt.extend(['-o', 'GSUtil:parallel_process_count=1'])
  183. if sys.platform == 'cygwin':
  184. # This script requires Windows Python, so invoke with depot_tools'
  185. # Python.
  186. def winpath(path):
  187. stdout = subprocess.check_output(['cygpath', '-w', path])
  188. return stdout.strip().decode('utf-8', 'replace')
  189. cmd = ['python.bat', winpath(__file__)]
  190. cmd.extend(args)
  191. sys.exit(subprocess.call(cmd))
  192. assert sys.platform != 'cygwin'
  193. cmd = [
  194. 'vpython3',
  195. '-vpython-spec', os.path.join(THIS_DIR, 'gsutil.vpython3'),
  196. '--',
  197. gsutil_bin
  198. ] + args_opt + args
  199. # When .boto is present, try without additional wrappers and handle specific
  200. # errors.
  201. if is_boto_present():
  202. p = _run_subprocess(cmd)
  203. # Notify user that their .boto file might be outdated.
  204. if b'Your credentials are invalid.' in p.stderr:
  205. # Make sure this error message is visible when invoked by gclient runhooks
  206. separator = '*' * 80
  207. print(
  208. '\n' + separator + '\n' +
  209. 'Warning: You might have an outdated .boto file. If this issue '
  210. 'persists after running `gsutil.py config`, try removing your '
  211. '.boto file.\n' + separator + '\n',
  212. file=sys.stderr)
  213. _print_subprocess_result(p)
  214. return p.returncode
  215. # Skip wrapping commands if luci-auth is already being
  216. if _is_luci_context():
  217. return _run_subprocess(cmd, interactive=True).returncode
  218. # Wrap gsutil with luci-auth context.
  219. return luci_context(cmd).returncode
  220. def parse_args():
  221. bin_dir = os.environ.get('DEPOT_TOOLS_GSUTIL_BIN_DIR', DEFAULT_BIN_DIR)
  222. # Help is disabled as it conflicts with gsutil -h, which controls headers.
  223. parser = argparse.ArgumentParser(add_help=False)
  224. parser.add_argument('--clean', action='store_true',
  225. help='Clear any existing gsutil package, forcing a new download.')
  226. parser.add_argument('--target', default=bin_dir,
  227. help='The target directory to download/store a gsutil version in. '
  228. '(default is %(default)s).')
  229. # These two args exist for backwards-compatibility but are no-ops.
  230. parser.add_argument('--force-version', default=VERSION,
  231. help='(deprecated, this flag has no effect)')
  232. parser.add_argument('--fallback',
  233. help='(deprecated, this flag has no effect)')
  234. parser.add_argument('args', nargs=argparse.REMAINDER)
  235. args, extras = parser.parse_known_args()
  236. if args.args and args.args[0] == '--':
  237. args.args.pop(0)
  238. if extras:
  239. args.args = extras + args.args
  240. return args
  241. def main():
  242. args = parse_args()
  243. return run_gsutil(args.target, args.args, clean=args.clean)
  244. if __name__ == '__main__':
  245. sys.exit(main())