blob: 9e6d76e660f7c0359f04fa925294f341da6eb479 [file] [log] [blame]
hinoka@chromium.org7a790542014-12-10 02:04:39 +00001#!/usr/bin/env python
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
8
9import argparse
hinoka@chromium.org7a790542014-12-10 02:04:39 +000010import base64
dnj@chromium.org605d81d2015-09-18 22:33:53 +000011import contextlib
primiano@chromium.orgdf351762014-12-18 11:12:34 +000012import hashlib
hinoka@chromium.org7a790542014-12-10 02:04:39 +000013import json
primiano@chromium.orgdf351762014-12-18 11:12:34 +000014import os
15import shutil
hinoka@chromium.org7a790542014-12-10 02:04:39 +000016import subprocess
primiano@chromium.orgdf351762014-12-18 11:12:34 +000017import sys
dnj@chromium.org605d81d2015-09-18 22:33:53 +000018import tempfile
19import time
primiano@chromium.orgdf351762014-12-18 11:12:34 +000020import urllib2
21import zipfile
hinoka@chromium.org7a790542014-12-10 02:04:39 +000022
23
24GSUTIL_URL = 'https://storage.googleapis.com/pub/'
25API_URL = 'https://www.googleapis.com/storage/v1/b/pub/o/'
26
27THIS_DIR = os.path.dirname(os.path.abspath(__file__))
28DEFAULT_BIN_DIR = os.path.join(THIS_DIR, 'external_bin', 'gsutil')
29DEFAULT_FALLBACK_GSUTIL = os.path.join(
30 THIS_DIR, 'third_party', 'gsutil', 'gsutil')
31
Dan Jacques509776e2017-09-07 18:01:08 -070032IS_WINDOWS = os.name == 'nt'
33
34
hinoka@chromium.org7a790542014-12-10 02:04:39 +000035class InvalidGsutilError(Exception):
36 pass
37
38
hinoka@chromium.org7a790542014-12-10 02:04:39 +000039def download_gsutil(version, target_dir):
40 """Downloads gsutil into the target_dir."""
41 filename = 'gsutil_%s.zip' % version
42 target_filename = os.path.join(target_dir, filename)
43
44 # Check if the target exists already.
45 if os.path.exists(target_filename):
46 md5_calc = hashlib.md5()
47 with open(target_filename, 'rb') as f:
48 while True:
49 buf = f.read(4096)
50 if not buf:
51 break
52 md5_calc.update(buf)
53 local_md5 = md5_calc.hexdigest()
54
55 metadata_url = '%s%s' % (API_URL, filename)
primiano@chromium.orgdf351762014-12-18 11:12:34 +000056 metadata = json.load(urllib2.urlopen(metadata_url))
hinoka@chromium.org7a790542014-12-10 02:04:39 +000057 remote_md5 = base64.b64decode(metadata['md5Hash'])
58
59 if local_md5 == remote_md5:
60 return target_filename
61 os.remove(target_filename)
62
63 # Do the download.
64 url = '%s%s' % (GSUTIL_URL, filename)
primiano@chromium.orgdf351762014-12-18 11:12:34 +000065 u = urllib2.urlopen(url)
hinoka@chromium.org7a790542014-12-10 02:04:39 +000066 with open(target_filename, 'wb') as f:
67 while True:
68 buf = u.read(4096)
69 if not buf:
70 break
71 f.write(buf)
72 return target_filename
73
74
dnj@chromium.org605d81d2015-09-18 22:33:53 +000075@contextlib.contextmanager
76def temporary_directory(base):
77 tmpdir = tempfile.mkdtemp(prefix='gsutil_py', dir=base)
78 try:
79 yield tmpdir
80 finally:
81 if os.path.isdir(tmpdir):
82 shutil.rmtree(tmpdir)
83
84def ensure_gsutil(version, target, clean):
hinoka@chromium.org7a790542014-12-10 02:04:39 +000085 bin_dir = os.path.join(target, 'gsutil_%s' % version)
86 gsutil_bin = os.path.join(bin_dir, 'gsutil', 'gsutil')
Ryan Tseng83fd81f2017-10-23 11:13:48 -070087 gsutil_flag = os.path.join(bin_dir, 'gsutil', 'install.flag')
88 # We assume that if gsutil_flag exists, then we have a good version
89 # of the gsutil package.
90 if not clean and os.path.isfile(gsutil_flag):
hinoka@chromium.org7a790542014-12-10 02:04:39 +000091 # Everything is awesome! we're all done here.
92 return gsutil_bin
93
dnj@chromium.org605d81d2015-09-18 22:33:53 +000094 if not os.path.exists(target):
95 os.makedirs(target)
96 with temporary_directory(target) as instance_dir:
hinoka@chromium.org7a790542014-12-10 02:04:39 +000097 # Clean up if we're redownloading a corrupted gsutil.
dnj@chromium.org605d81d2015-09-18 22:33:53 +000098 cleanup_path = os.path.join(instance_dir, 'clean')
99 try:
100 os.rename(bin_dir, cleanup_path)
101 except (OSError, IOError):
102 cleanup_path = None
103 if cleanup_path:
104 shutil.rmtree(cleanup_path)
105
106 download_dir = os.path.join(instance_dir, 'download')
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
111 try:
112 os.rename(download_dir, bin_dir)
113 except (OSError, IOError):
114 # Something else did this in parallel.
115 pass
Ryan Tseng83fd81f2017-10-23 11:13:48 -0700116 # Final check that the gsutil bin exists. This should never fail.
117 if not os.path.isfile(gsutil_bin):
118 raise InvalidGsutilError()
119 # Drop a flag file.
120 with open(gsutil_flag, 'w') as f:
121 f.write('This flag file is dropped by gsutil.py')
hinoka@chromium.org7a790542014-12-10 02:04:39 +0000122
hinoka@chromium.org7a790542014-12-10 02:04:39 +0000123 return gsutil_bin
124
125
dnj@chromium.org605d81d2015-09-18 22:33:53 +0000126def run_gsutil(force_version, fallback, target, args, clean=False):
hinoka@chromium.org7a790542014-12-10 02:04:39 +0000127 if force_version:
dnj@chromium.org605d81d2015-09-18 22:33:53 +0000128 gsutil_bin = ensure_gsutil(force_version, target, clean)
hinoka@chromium.org7a790542014-12-10 02:04:39 +0000129 else:
130 gsutil_bin = fallback
hinoka@chromium.orgfdb9ce32016-04-05 23:57:12 +0000131 disable_update = ['-o', 'GSUtil:software_update_check_period=0']
Dan Jacques509776e2017-09-07 18:01:08 -0700132
Chris Nardiab816ce2017-10-31 15:45:05 -0400133 if sys.platform == 'cygwin':
134 # This script requires Windows Python, so invoke with depot_tools'
135 # Python.
136 def winpath(path):
137 return subprocess.check_output(['cygpath', '-w', path]).strip()
138 cmd = ['python.bat', winpath(__file__)]
139 cmd.extend(args)
140 sys.exit(subprocess.call(cmd))
141 assert sys.platform != 'cygwin'
142
Dan Jacques509776e2017-09-07 18:01:08 -0700143 # Run "gsutil" through "vpython". We need to do this because on GCE instances,
144 # expectations are made about Python having access to "google-compute-engine"
145 # and "boto" packages that are not met with non-system Python (e.g., bundles).
146 cmd = [
147 'vpython',
148 '-vpython-spec', os.path.join(THIS_DIR, 'gsutil.vpython'),
149 '--',
150 gsutil_bin
151 ] + disable_update + args
152 return subprocess.call(cmd, shell=IS_WINDOWS)
hinoka@chromium.org7a790542014-12-10 02:04:39 +0000153
154
155def parse_args():
dnj@chromium.org605d81d2015-09-18 22:33:53 +0000156 bin_dir = os.environ.get('DEPOT_TOOLS_GSUTIL_BIN_DIR', DEFAULT_BIN_DIR)
157
hinoka@chromium.org7a790542014-12-10 02:04:39 +0000158 parser = argparse.ArgumentParser()
hinoka@chromium.org493270e2015-07-15 19:37:31 +0000159 parser.add_argument('--force-version', default='4.13')
dnj@chromium.org605d81d2015-09-18 22:33:53 +0000160 parser.add_argument('--clean', action='store_true',
161 help='Clear any existing gsutil package, forcing a new download.')
hinoka@chromium.org7a790542014-12-10 02:04:39 +0000162 parser.add_argument('--fallback', default=DEFAULT_FALLBACK_GSUTIL)
dnj@chromium.org605d81d2015-09-18 22:33:53 +0000163 parser.add_argument('--target', default=bin_dir,
164 help='The target directory to download/store a gsutil version in. '
165 '(default is %(default)s).')
hinoka@chromium.org7a790542014-12-10 02:04:39 +0000166 parser.add_argument('args', nargs=argparse.REMAINDER)
167
hinoka@chromium.orgc13b0542014-12-18 01:06:20 +0000168 args, extras = parser.parse_known_args()
169 if args.args and args.args[0] == '--':
170 args.args.pop(0)
171 if extras:
172 args.args = extras + args.args
dnj@chromium.org605d81d2015-09-18 22:33:53 +0000173 return args
hinoka@chromium.org7a790542014-12-10 02:04:39 +0000174
175
176def main():
dnj@chromium.org605d81d2015-09-18 22:33:53 +0000177 args = parse_args()
178 return run_gsutil(args.force_version, args.fallback, args.target, args.args,
179 clean=args.clean)
hinoka@chromium.org7a790542014-12-10 02:04:39 +0000180
181if __name__ == '__main__':
182 sys.exit(main())