blob: 09be339d452bbaefbafd2055ecfe1458aa607e2d [file] [log] [blame]
[email protected]867e5b52013-03-13 21:43:511#!/usr/bin/env python
2# Copyright (c) 2012 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"""Download files from Google Storage based on SHA1 sums."""
7
8
9import hashlib
10import optparse
11import os
12import Queue
13import re
[email protected]ba63bcb2013-10-28 19:55:4814import stat
[email protected]867e5b52013-03-13 21:43:5115import sys
16import threading
17import time
18
19import subprocess2
20
21
22GSUTIL_DEFAULT_PATH = os.path.join(
[email protected]199bc5f2014-12-17 02:17:1423 os.path.dirname(os.path.abspath(__file__)), 'gsutil.py')
[email protected]c8270632014-01-17 22:28:3024# Maps sys.platform to what we actually want to call them.
25PLATFORM_MAPPING = {
26 'cygwin': 'win',
27 'darwin': 'mac',
28 'linux2': 'linux',
29 'win32': 'win',
30}
[email protected]867e5b52013-03-13 21:43:5131
32
33class FileNotFoundError(IOError):
34 pass
35
36
37class InvalidFileError(IOError):
38 pass
39
40
[email protected]c8270632014-01-17 22:28:3041class InvalidPlatformError(Exception):
42 pass
43
44
[email protected]7d6ffa52013-12-05 18:43:1145def GetNormalizedPlatform():
46 """Returns the result of sys.platform accounting for cygwin.
47 Under cygwin, this will always return "win32" like the native Python."""
48 if sys.platform == 'cygwin':
49 return 'win32'
50 return sys.platform
51
52
[email protected]867e5b52013-03-13 21:43:5153# Common utilities
54class Gsutil(object):
55 """Call gsutil with some predefined settings. This is a convenience object,
56 and is also immutable."""
[email protected]199bc5f2014-12-17 02:17:1457 def __init__(self, path, boto_path, timeout=None, version='4.7'):
[email protected]867e5b52013-03-13 21:43:5158 if not os.path.exists(path):
59 raise FileNotFoundError('GSUtil not found in %s' % path)
60 self.path = path
61 self.timeout = timeout
62 self.boto_path = boto_path
[email protected]199bc5f2014-12-17 02:17:1463 self.version = version
[email protected]867e5b52013-03-13 21:43:5164
[email protected]3e31fca2013-06-28 17:04:4465 def get_sub_env(self):
[email protected]867e5b52013-03-13 21:43:5166 env = os.environ.copy()
[email protected]c61894c2013-11-19 20:25:2167 if self.boto_path == os.devnull:
68 env['AWS_CREDENTIAL_FILE'] = ''
69 env['BOTO_CONFIG'] = ''
70 elif self.boto_path:
[email protected]867e5b52013-03-13 21:43:5171 env['AWS_CREDENTIAL_FILE'] = self.boto_path
[email protected]c61894c2013-11-19 20:25:2172 env['BOTO_CONFIG'] = self.boto_path
[email protected]3e31fca2013-06-28 17:04:4473 else:
74 custompath = env.get('AWS_CREDENTIAL_FILE', '~/.boto') + '.depot_tools'
75 custompath = os.path.expanduser(custompath)
76 if os.path.exists(custompath):
77 env['AWS_CREDENTIAL_FILE'] = custompath
78
79 return env
80
81 def call(self, *args):
[email protected]199bc5f2014-12-17 02:17:1482 cmd = [sys.executable, self.path, '--force-version', self.version]
[email protected]c6a2ee62013-12-12 08:26:1883 cmd.extend(args)
84 return subprocess2.call(cmd, env=self.get_sub_env(), timeout=self.timeout)
[email protected]867e5b52013-03-13 21:43:5185
86 def check_call(self, *args):
[email protected]199bc5f2014-12-17 02:17:1487 cmd = [sys.executable, self.path, '--force-version', self.version]
[email protected]c6a2ee62013-12-12 08:26:1888 cmd.extend(args)
[email protected]867e5b52013-03-13 21:43:5189 ((out, err), code) = subprocess2.communicate(
[email protected]c6a2ee62013-12-12 08:26:1890 cmd,
[email protected]867e5b52013-03-13 21:43:5191 stdout=subprocess2.PIPE,
92 stderr=subprocess2.PIPE,
[email protected]3e31fca2013-06-28 17:04:4493 env=self.get_sub_env(),
[email protected]867e5b52013-03-13 21:43:5194 timeout=self.timeout)
95
96 # Parse output.
97 status_code_match = re.search('status=([0-9]+)', err)
98 if status_code_match:
99 return (int(status_code_match.group(1)), out, err)
100 if ('You are attempting to access protected data with '
101 'no configured credentials.' in err):
102 return (403, out, err)
103 if 'No such object' in err:
104 return (404, out, err)
105 return (code, out, err)
106
107
[email protected]d3e713b2014-12-04 22:11:08108def check_bucket_permissions(base_url, gsutil):
[email protected]867e5b52013-03-13 21:43:51109 code, _, ls_err = gsutil.check_call('ls', base_url)
[email protected]8b3cad72013-09-19 20:00:48110 if code != 0:
111 print >> sys.stderr, ls_err
[email protected]867e5b52013-03-13 21:43:51112 if code == 403:
[email protected]f9cc91d2013-06-04 03:25:42113 print >> sys.stderr, 'Got error 403 while authenticating to %s.' % base_url
[email protected]0477f8c2013-06-26 22:23:57114 print >> sys.stderr, 'Try running "download_from_google_storage --config".'
[email protected]867e5b52013-03-13 21:43:51115 elif code == 404:
116 print >> sys.stderr, '%s not found.' % base_url
[email protected]af2591b2014-12-04 23:03:04117 return code
[email protected]867e5b52013-03-13 21:43:51118
119
[email protected]c8270632014-01-17 22:28:30120def check_platform(target):
121 """Checks if any parent directory of target matches (win|mac|linux)."""
122 assert os.path.isabs(target)
123 root, target_name = os.path.split(target)
124 if not target_name:
125 return None
126 if target_name in ('linux', 'mac', 'win'):
127 return target_name
128 return check_platform(root)
129
130
[email protected]867e5b52013-03-13 21:43:51131def get_sha1(filename):
132 sha1 = hashlib.sha1()
133 with open(filename, 'rb') as f:
134 while True:
135 # Read in 1mb chunks, so it doesn't all have to be loaded into memory.
136 chunk = f.read(1024*1024)
137 if not chunk:
138 break
139 sha1.update(chunk)
140 return sha1.hexdigest()
141
142
143# Download-specific code starts here
144
145def enumerate_work_queue(input_filename, work_queue, directory,
[email protected]c8270632014-01-17 22:28:30146 recursive, ignore_errors, output, sha1_file,
147 auto_platform):
[email protected]867e5b52013-03-13 21:43:51148 if sha1_file:
149 if not os.path.exists(input_filename):
150 if not ignore_errors:
151 raise FileNotFoundError('%s not found.' % input_filename)
152 print >> sys.stderr, '%s not found.' % input_filename
153 with open(input_filename, 'rb') as f:
154 sha1_match = re.match('^([A-Za-z0-9]{40})$', f.read(1024).rstrip())
155 if sha1_match:
[email protected]50c8e0e2014-12-04 22:18:36156 work_queue.put((sha1_match.groups(1)[0], output))
[email protected]867e5b52013-03-13 21:43:51157 return 1
158 if not ignore_errors:
159 raise InvalidFileError('No sha1 sum found in %s.' % input_filename)
160 print >> sys.stderr, 'No sha1 sum found in %s.' % input_filename
161 return 0
162
163 if not directory:
164 work_queue.put((input_filename, output))
165 return 1
166
167 work_queue_size = 0
168 for root, dirs, files in os.walk(input_filename):
169 if not recursive:
170 for item in dirs[:]:
171 dirs.remove(item)
172 else:
173 for exclude in ['.svn', '.git']:
174 if exclude in dirs:
175 dirs.remove(exclude)
176 for filename in files:
177 full_path = os.path.join(root, filename)
178 if full_path.endswith('.sha1'):
[email protected]c8270632014-01-17 22:28:30179 if auto_platform:
180 # Skip if the platform does not match.
181 target_platform = check_platform(os.path.abspath(full_path))
182 if not target_platform:
183 err = ('--auto_platform passed in but no platform name found in '
184 'the path of %s' % full_path)
185 if not ignore_errors:
186 raise InvalidFileError(err)
187 print >> sys.stderr, err
188 continue
189 current_platform = PLATFORM_MAPPING[sys.platform]
190 if current_platform != target_platform:
191 continue
192
[email protected]867e5b52013-03-13 21:43:51193 with open(full_path, 'rb') as f:
194 sha1_match = re.match('^([A-Za-z0-9]{40})$', f.read(1024).rstrip())
195 if sha1_match:
196 work_queue.put(
197 (sha1_match.groups(1)[0], full_path.replace('.sha1', '')))
198 work_queue_size += 1
199 else:
200 if not ignore_errors:
201 raise InvalidFileError('No sha1 sum found in %s.' % filename)
202 print >> sys.stderr, 'No sha1 sum found in %s.' % filename
203 return work_queue_size
204
205
206def _downloader_worker_thread(thread_num, q, force, base_url,
[email protected]ff7ea002013-11-25 19:28:54207 gsutil, out_q, ret_codes, verbose):
[email protected]867e5b52013-03-13 21:43:51208 while True:
209 input_sha1_sum, output_filename = q.get()
210 if input_sha1_sum is None:
211 return
212 if os.path.exists(output_filename) and not force:
213 if get_sha1(output_filename) == input_sha1_sum:
[email protected]ff7ea002013-11-25 19:28:54214 if verbose:
215 out_q.put(
216 '%d> File %s exists and SHA1 matches. Skipping.' % (
217 thread_num, output_filename))
[email protected]867e5b52013-03-13 21:43:51218 continue
219 # Check if file exists.
220 file_url = '%s/%s' % (base_url, input_sha1_sum)
221 if gsutil.check_call('ls', file_url)[0] != 0:
222 out_q.put('%d> File %s for %s does not exist, skipping.' % (
223 thread_num, file_url, output_filename))
224 ret_codes.put((1, 'File %s for %s does not exist.' % (
225 file_url, output_filename)))
226 continue
227 # Fetch the file.
[email protected]6b6a1142014-11-04 00:40:53228 out_q.put('%d> Downloading %s...' % (thread_num, output_filename))
229 try:
230 os.remove(output_filename) # Delete the file if it exists already.
231 except OSError:
232 if os.path.exists(output_filename):
233 out_q.put('%d> Warning: deleting %s failed.' % (
234 thread_num, output_filename))
[email protected]199bc5f2014-12-17 02:17:14235 code, _, err = gsutil.check_call('cp', file_url, output_filename)
[email protected]867e5b52013-03-13 21:43:51236 if code != 0:
237 out_q.put('%d> %s' % (thread_num, err))
238 ret_codes.put((code, err))
239
[email protected]25a33d32013-12-05 22:34:27240 # Set executable bit.
241 if sys.platform == 'cygwin':
242 # Under cygwin, mark all files as executable. The executable flag in
243 # Google Storage will not be set when uploading from Windows, so if
244 # this script is running under cygwin and we're downloading an
245 # executable, it will be unrunnable from inside cygwin without this.
246 st = os.stat(output_filename)
247 os.chmod(output_filename, st.st_mode | stat.S_IEXEC)
248 elif sys.platform != 'win32':
249 # On non-Windows platforms, key off of the custom header
250 # "x-goog-meta-executable".
[email protected]20bef062014-12-17 23:47:23251 code, out, _ = gsutil.check_call('stat', file_url)
[email protected]ba63bcb2013-10-28 19:55:48252 if code != 0:
253 out_q.put('%d> %s' % (thread_num, err))
254 ret_codes.put((code, err))
[email protected]20bef062014-12-17 23:47:23255 elif re.search(r'executable:\s*1', out):
[email protected]ba63bcb2013-10-28 19:55:48256 st = os.stat(output_filename)
257 os.chmod(output_filename, st.st_mode | stat.S_IEXEC)
[email protected]867e5b52013-03-13 21:43:51258
259def printer_worker(output_queue):
260 while True:
261 line = output_queue.get()
262 # Its plausible we want to print empty lines.
263 if line is None:
264 break
265 print line
266
267
268def download_from_google_storage(
269 input_filename, base_url, gsutil, num_threads, directory, recursive,
[email protected]c8270632014-01-17 22:28:30270 force, output, ignore_errors, sha1_file, verbose, auto_platform):
[email protected]867e5b52013-03-13 21:43:51271 # Start up all the worker threads.
272 all_threads = []
273 download_start = time.time()
274 stdout_queue = Queue.Queue()
275 work_queue = Queue.Queue()
276 ret_codes = Queue.Queue()
277 ret_codes.put((0, None))
278 for thread_num in range(num_threads):
279 t = threading.Thread(
280 target=_downloader_worker_thread,
281 args=[thread_num, work_queue, force, base_url,
[email protected]ff7ea002013-11-25 19:28:54282 gsutil, stdout_queue, ret_codes, verbose])
[email protected]867e5b52013-03-13 21:43:51283 t.daemon = True
284 t.start()
285 all_threads.append(t)
286 printer_thread = threading.Thread(target=printer_worker, args=[stdout_queue])
287 printer_thread.daemon = True
288 printer_thread.start()
289
290 # Enumerate our work queue.
291 work_queue_size = enumerate_work_queue(
292 input_filename, work_queue, directory, recursive,
[email protected]c8270632014-01-17 22:28:30293 ignore_errors, output, sha1_file, auto_platform)
[email protected]867e5b52013-03-13 21:43:51294 for _ in all_threads:
295 work_queue.put((None, None)) # Used to tell worker threads to stop.
296
297 # Wait for all downloads to finish.
298 for t in all_threads:
299 t.join()
300 stdout_queue.put(None)
301 printer_thread.join()
302
303 # See if we ran into any errors.
304 max_ret_code = 0
305 for ret_code, message in ret_codes.queue:
306 max_ret_code = max(ret_code, max_ret_code)
307 if message:
308 print >> sys.stderr, message
[email protected]ff7ea002013-11-25 19:28:54309 if verbose and not max_ret_code:
[email protected]867e5b52013-03-13 21:43:51310 print 'Success!'
311
[email protected]ff7ea002013-11-25 19:28:54312 if verbose:
313 print 'Downloading %d files took %1f second(s)' % (
314 work_queue_size, time.time() - download_start)
[email protected]867e5b52013-03-13 21:43:51315 return max_ret_code
316
317
318def main(args):
319 usage = ('usage: %prog [options] target\n'
320 'Target must be:\n'
321 ' (default) a sha1 sum ([A-Za-z0-9]{40}).\n'
322 ' (-s or --sha1_file) a .sha1 file, containing a sha1 sum on '
323 'the first line.\n'
324 ' (-d or --directory) A directory to scan for .sha1 files.')
325 parser = optparse.OptionParser(usage)
326 parser.add_option('-o', '--output',
327 help='Specify the output file name. Defaults to: '
328 '(a) Given a SHA1 hash, the name is the SHA1 hash. '
329 '(b) Given a .sha1 file or directory, the name will '
330 'match (.*).sha1.')
331 parser.add_option('-b', '--bucket',
332 help='Google Storage bucket to fetch from.')
333 parser.add_option('-e', '--boto',
334 help='Specify a custom boto file.')
335 parser.add_option('-c', '--no_resume', action='store_true',
336 help='Resume download if file is partially downloaded.')
337 parser.add_option('-f', '--force', action='store_true',
338 help='Force download even if local file exists.')
339 parser.add_option('-i', '--ignore_errors', action='store_true',
340 help='Don\'t throw error if we find an invalid .sha1 file.')
341 parser.add_option('-r', '--recursive', action='store_true',
342 help='Scan folders recursively for .sha1 files. '
343 'Must be used with -d/--directory')
344 parser.add_option('-t', '--num_threads', default=1, type='int',
345 help='Number of downloader threads to run.')
346 parser.add_option('-d', '--directory', action='store_true',
347 help='The target is a directory. '
348 'Cannot be used with -s/--sha1_file.')
349 parser.add_option('-s', '--sha1_file', action='store_true',
350 help='The target is a file containing a sha1 sum. '
351 'Cannot be used with -d/--directory.')
[email protected]0477f8c2013-06-26 22:23:57352 parser.add_option('-g', '--config', action='store_true',
353 help='Alias for "gsutil config". Run this if you want '
354 'to initialize your saved Google Storage '
[email protected]4b74fcd2014-01-10 23:36:24355 'credentials. This will create a read-only '
356 'credentials file in ~/.boto.depot_tools.')
[email protected]c61894c2013-11-19 20:25:21357 parser.add_option('-n', '--no_auth', action='store_true',
358 help='Skip auth checking. Use if it\'s known that the '
359 'target bucket is a public bucket.')
360 parser.add_option('-p', '--platform',
[email protected]ba63bcb2013-10-28 19:55:48361 help='A regular expression that is compared against '
362 'Python\'s sys.platform. If this option is specified, '
363 'the download will happen only if there is a match.')
[email protected]c8270632014-01-17 22:28:30364 parser.add_option('-a', '--auto_platform',
365 action='store_true',
366 help='Detects if any parent folder of the target matches '
367 '(linux|mac|win). If so, the script will only '
368 'process files that are in the paths that '
369 'that matches the current platform.')
[email protected]ff7ea002013-11-25 19:28:54370 parser.add_option('-v', '--verbose', action='store_true',
371 help='Output extra diagnostic and progress information.')
[email protected]867e5b52013-03-13 21:43:51372
373 (options, args) = parser.parse_args()
[email protected]ba63bcb2013-10-28 19:55:48374
375 # Make sure we should run at all based on platform matching.
376 if options.platform:
[email protected]c8270632014-01-17 22:28:30377 if options.auto_platform:
378 parser.error('--platform can not be specified with --auto_platform')
[email protected]7d4cc4a2013-12-06 18:30:57379 if not re.match(options.platform, GetNormalizedPlatform()):
[email protected]ff7ea002013-11-25 19:28:54380 if options.verbose:
381 print('The current platform doesn\'t match "%s", skipping.' %
382 options.platform)
[email protected]ba63bcb2013-10-28 19:55:48383 return 0
384
[email protected]c61894c2013-11-19 20:25:21385 # Set the boto file to /dev/null if we don't need auth.
386 if options.no_auth:
387 options.boto = os.devnull
388
[email protected]c6a2ee62013-12-12 08:26:18389 # Make sure gsutil exists where we expect it to.
[email protected]0477f8c2013-06-26 22:23:57390 if os.path.exists(GSUTIL_DEFAULT_PATH):
[email protected]c6a2ee62013-12-12 08:26:18391 gsutil = Gsutil(GSUTIL_DEFAULT_PATH,
[email protected]199bc5f2014-12-17 02:17:14392 boto_path=options.boto)
[email protected]0477f8c2013-06-26 22:23:57393 else:
[email protected]c6a2ee62013-12-12 08:26:18394 parser.error('gsutil not found in %s, bad depot_tools checkout?' %
395 GSUTIL_DEFAULT_PATH)
[email protected]0477f8c2013-06-26 22:23:57396
397 # Passing in -g/--config will run our copy of GSUtil, then quit.
398 if options.config:
[email protected]4b74fcd2014-01-10 23:36:24399 return gsutil.call('config', '-r', '-o',
400 os.path.expanduser('~/.boto.depot_tools'))
[email protected]0477f8c2013-06-26 22:23:57401
[email protected]867e5b52013-03-13 21:43:51402 if not args:
403 parser.error('Missing target.')
404 if len(args) > 1:
405 parser.error('Too many targets.')
406 if not options.bucket:
407 parser.error('Missing bucket. Specify bucket with --bucket.')
408 if options.sha1_file and options.directory:
409 parser.error('Both --directory and --sha1_file are specified, '
410 'can only specify one.')
411 if options.recursive and not options.directory:
412 parser.error('--recursive specified but --directory not specified.')
413 if options.output and options.directory:
414 parser.error('--directory is specified, so --output has no effect.')
[email protected]c8270632014-01-17 22:28:30415 if (not (options.sha1_file or options.directory)
416 and options.auto_platform):
417 parser.error('--auto_platform must be specified with either '
418 '--sha1_file or --directory')
419
[email protected]867e5b52013-03-13 21:43:51420 input_filename = args[0]
421
422 # Set output filename if not specified.
423 if not options.output and not options.directory:
424 if not options.sha1_file:
425 # Target is a sha1 sum, so output filename would also be the sha1 sum.
426 options.output = input_filename
427 elif options.sha1_file:
428 # Target is a .sha1 file.
429 if not input_filename.endswith('.sha1'):
430 parser.error('--sha1_file is specified, but the input filename '
431 'does not end with .sha1, and no --output is specified. '
432 'Either make sure the input filename has a .sha1 '
433 'extension, or specify --output.')
434 options.output = input_filename[:-5]
435 else:
436 parser.error('Unreachable state.')
437
438 # Check if output file already exists.
439 if not options.directory and not options.force and not options.no_resume:
440 if os.path.exists(options.output):
441 parser.error('Output file %s exists and --no_resume is specified.'
442 % options.output)
443
[email protected]d3e713b2014-12-04 22:11:08444 base_url = 'gs://%s' % options.bucket
445
[email protected]867e5b52013-03-13 21:43:51446 # Check we have a valid bucket with valid permissions.
[email protected]d3e713b2014-12-04 22:11:08447 if not options.no_auth:
[email protected]5c88fd02014-12-04 22:44:52448 code = check_bucket_permissions(base_url, gsutil)
[email protected]d3e713b2014-12-04 22:11:08449 if code:
450 return code
[email protected]867e5b52013-03-13 21:43:51451
452 return download_from_google_storage(
453 input_filename, base_url, gsutil, options.num_threads, options.directory,
454 options.recursive, options.force, options.output, options.ignore_errors,
[email protected]c8270632014-01-17 22:28:30455 options.sha1_file, options.verbose, options.auto_platform)
[email protected]867e5b52013-03-13 21:43:51456
457
458if __name__ == '__main__':
[email protected]acb9ed72013-06-20 12:16:15459 sys.exit(main(sys.argv))