gsutil.py 10 KB

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