blob: 8370515e6a15879c3ddf5c1e8693efeb595a8ccd [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(
23 os.path.dirname(os.path.abspath(__file__)),
24 'third_party', 'gsutil', 'gsutil')
[email protected]c8270632014-01-17 22:28:3025# Maps sys.platform to what we actually want to call them.
26PLATFORM_MAPPING = {
27 'cygwin': 'win',
28 'darwin': 'mac',
29 'linux2': 'linux',
30 'win32': 'win',
31}
[email protected]867e5b52013-03-13 21:43:5132
33
34class FileNotFoundError(IOError):
35 pass
36
37
38class InvalidFileError(IOError):
39 pass
40
41
[email protected]c8270632014-01-17 22:28:3042class InvalidPlatformError(Exception):
43 pass
44
45
[email protected]7d6ffa52013-12-05 18:43:1146def GetNormalizedPlatform():
47 """Returns the result of sys.platform accounting for cygwin.
48 Under cygwin, this will always return "win32" like the native Python."""
49 if sys.platform == 'cygwin':
50 return 'win32'
51 return sys.platform
52
53
[email protected]867e5b52013-03-13 21:43:5154# Common utilities
55class Gsutil(object):
56 """Call gsutil with some predefined settings. This is a convenience object,
57 and is also immutable."""
[email protected]c6a2ee62013-12-12 08:26:1858 def __init__(self, path, boto_path, timeout=None, bypass_prodaccess=False):
[email protected]867e5b52013-03-13 21:43:5159 if not os.path.exists(path):
60 raise FileNotFoundError('GSUtil not found in %s' % path)
61 self.path = path
62 self.timeout = timeout
63 self.boto_path = boto_path
[email protected]c6a2ee62013-12-12 08:26:1864 self.bypass_prodaccess = bypass_prodaccess
[email protected]867e5b52013-03-13 21:43:5165
[email protected]3e31fca2013-06-28 17:04:4466 def get_sub_env(self):
[email protected]867e5b52013-03-13 21:43:5167 env = os.environ.copy()
[email protected]c61894c2013-11-19 20:25:2168 if self.boto_path == os.devnull:
69 env['AWS_CREDENTIAL_FILE'] = ''
70 env['BOTO_CONFIG'] = ''
71 elif self.boto_path:
[email protected]867e5b52013-03-13 21:43:5172 env['AWS_CREDENTIAL_FILE'] = self.boto_path
[email protected]c61894c2013-11-19 20:25:2173 env['BOTO_CONFIG'] = self.boto_path
[email protected]3e31fca2013-06-28 17:04:4474 else:
75 custompath = env.get('AWS_CREDENTIAL_FILE', '~/.boto') + '.depot_tools'
76 custompath = os.path.expanduser(custompath)
77 if os.path.exists(custompath):
78 env['AWS_CREDENTIAL_FILE'] = custompath
79
80 return env
81
82 def call(self, *args):
[email protected]c6a2ee62013-12-12 08:26:1883 cmd = [sys.executable, self.path]
84 if self.bypass_prodaccess:
85 cmd.append('--bypass_prodaccess')
86 cmd.extend(args)
87 return subprocess2.call(cmd, env=self.get_sub_env(), timeout=self.timeout)
[email protected]867e5b52013-03-13 21:43:5188
89 def check_call(self, *args):
[email protected]c6a2ee62013-12-12 08:26:1890 cmd = [sys.executable, self.path]
91 if self.bypass_prodaccess:
92 cmd.append('--bypass_prodaccess')
93 cmd.extend(args)
[email protected]867e5b52013-03-13 21:43:5194 ((out, err), code) = subprocess2.communicate(
[email protected]c6a2ee62013-12-12 08:26:1895 cmd,
[email protected]867e5b52013-03-13 21:43:5196 stdout=subprocess2.PIPE,
97 stderr=subprocess2.PIPE,
[email protected]3e31fca2013-06-28 17:04:4498 env=self.get_sub_env(),
[email protected]867e5b52013-03-13 21:43:5199 timeout=self.timeout)
100
101 # Parse output.
102 status_code_match = re.search('status=([0-9]+)', err)
103 if status_code_match:
104 return (int(status_code_match.group(1)), out, err)
105 if ('You are attempting to access protected data with '
106 'no configured credentials.' in err):
107 return (403, out, err)
108 if 'No such object' in err:
109 return (404, out, err)
110 return (code, out, err)
111
112
113def check_bucket_permissions(bucket, gsutil):
114 if not bucket:
115 print >> sys.stderr, 'Missing bucket %s.'
116 return (None, 1)
117 base_url = 'gs://%s' % bucket
118
119 code, _, ls_err = gsutil.check_call('ls', base_url)
[email protected]8b3cad72013-09-19 20:00:48120 if code != 0:
121 print >> sys.stderr, ls_err
[email protected]867e5b52013-03-13 21:43:51122 if code == 403:
[email protected]f9cc91d2013-06-04 03:25:42123 print >> sys.stderr, 'Got error 403 while authenticating to %s.' % base_url
[email protected]0477f8c2013-06-26 22:23:57124 print >> sys.stderr, 'Try running "download_from_google_storage --config".'
[email protected]867e5b52013-03-13 21:43:51125 elif code == 404:
126 print >> sys.stderr, '%s not found.' % base_url
[email protected]867e5b52013-03-13 21:43:51127 return (base_url, code)
128
129
[email protected]c8270632014-01-17 22:28:30130def check_platform(target):
131 """Checks if any parent directory of target matches (win|mac|linux)."""
132 assert os.path.isabs(target)
133 root, target_name = os.path.split(target)
134 if not target_name:
135 return None
136 if target_name in ('linux', 'mac', 'win'):
137 return target_name
138 return check_platform(root)
139
140
[email protected]867e5b52013-03-13 21:43:51141def get_sha1(filename):
142 sha1 = hashlib.sha1()
143 with open(filename, 'rb') as f:
144 while True:
145 # Read in 1mb chunks, so it doesn't all have to be loaded into memory.
146 chunk = f.read(1024*1024)
147 if not chunk:
148 break
149 sha1.update(chunk)
150 return sha1.hexdigest()
151
152
153# Download-specific code starts here
154
155def enumerate_work_queue(input_filename, work_queue, directory,
[email protected]c8270632014-01-17 22:28:30156 recursive, ignore_errors, output, sha1_file,
157 auto_platform):
[email protected]867e5b52013-03-13 21:43:51158 if sha1_file:
159 if not os.path.exists(input_filename):
160 if not ignore_errors:
161 raise FileNotFoundError('%s not found.' % input_filename)
162 print >> sys.stderr, '%s not found.' % input_filename
163 with open(input_filename, 'rb') as f:
164 sha1_match = re.match('^([A-Za-z0-9]{40})$', f.read(1024).rstrip())
165 if sha1_match:
166 work_queue.put(
167 (sha1_match.groups(1)[0], input_filename.replace('.sha1', '')))
168 return 1
169 if not ignore_errors:
170 raise InvalidFileError('No sha1 sum found in %s.' % input_filename)
171 print >> sys.stderr, 'No sha1 sum found in %s.' % input_filename
172 return 0
173
174 if not directory:
175 work_queue.put((input_filename, output))
176 return 1
177
178 work_queue_size = 0
179 for root, dirs, files in os.walk(input_filename):
180 if not recursive:
181 for item in dirs[:]:
182 dirs.remove(item)
183 else:
184 for exclude in ['.svn', '.git']:
185 if exclude in dirs:
186 dirs.remove(exclude)
187 for filename in files:
188 full_path = os.path.join(root, filename)
189 if full_path.endswith('.sha1'):
[email protected]c8270632014-01-17 22:28:30190 if auto_platform:
191 # Skip if the platform does not match.
192 target_platform = check_platform(os.path.abspath(full_path))
193 if not target_platform:
194 err = ('--auto_platform passed in but no platform name found in '
195 'the path of %s' % full_path)
196 if not ignore_errors:
197 raise InvalidFileError(err)
198 print >> sys.stderr, err
199 continue
200 current_platform = PLATFORM_MAPPING[sys.platform]
201 if current_platform != target_platform:
202 continue
203
[email protected]867e5b52013-03-13 21:43:51204 with open(full_path, 'rb') as f:
205 sha1_match = re.match('^([A-Za-z0-9]{40})$', f.read(1024).rstrip())
206 if sha1_match:
207 work_queue.put(
208 (sha1_match.groups(1)[0], full_path.replace('.sha1', '')))
209 work_queue_size += 1
210 else:
211 if not ignore_errors:
212 raise InvalidFileError('No sha1 sum found in %s.' % filename)
213 print >> sys.stderr, 'No sha1 sum found in %s.' % filename
214 return work_queue_size
215
216
217def _downloader_worker_thread(thread_num, q, force, base_url,
[email protected]ff7ea002013-11-25 19:28:54218 gsutil, out_q, ret_codes, verbose):
[email protected]867e5b52013-03-13 21:43:51219 while True:
220 input_sha1_sum, output_filename = q.get()
221 if input_sha1_sum is None:
222 return
223 if os.path.exists(output_filename) and not force:
224 if get_sha1(output_filename) == input_sha1_sum:
[email protected]ff7ea002013-11-25 19:28:54225 if verbose:
226 out_q.put(
227 '%d> File %s exists and SHA1 matches. Skipping.' % (
228 thread_num, output_filename))
[email protected]867e5b52013-03-13 21:43:51229 continue
230 # Check if file exists.
231 file_url = '%s/%s' % (base_url, input_sha1_sum)
232 if gsutil.check_call('ls', file_url)[0] != 0:
233 out_q.put('%d> File %s for %s does not exist, skipping.' % (
234 thread_num, file_url, output_filename))
235 ret_codes.put((1, 'File %s for %s does not exist.' % (
236 file_url, output_filename)))
237 continue
238 # Fetch the file.
239 out_q.put('%d> Downloading %s...' % (
240 thread_num, output_filename))
241 code, _, err = gsutil.check_call('cp', '-q', file_url, output_filename)
242 if code != 0:
243 out_q.put('%d> %s' % (thread_num, err))
244 ret_codes.put((code, err))
245
[email protected]25a33d32013-12-05 22:34:27246 # Set executable bit.
247 if sys.platform == 'cygwin':
248 # Under cygwin, mark all files as executable. The executable flag in
249 # Google Storage will not be set when uploading from Windows, so if
250 # this script is running under cygwin and we're downloading an
251 # executable, it will be unrunnable from inside cygwin without this.
252 st = os.stat(output_filename)
253 os.chmod(output_filename, st.st_mode | stat.S_IEXEC)
254 elif sys.platform != 'win32':
255 # On non-Windows platforms, key off of the custom header
256 # "x-goog-meta-executable".
257 #
258 # TODO(hinoka): It is supposedly faster to use "gsutil stat" but that
259 # doesn't appear to be supported by the gsutil currently in our tree. When
260 # we update, this code should use that instead of "gsutil ls -L".
[email protected]ba63bcb2013-10-28 19:55:48261 code, out, _ = gsutil.check_call('ls', '-L', file_url)
262 if code != 0:
263 out_q.put('%d> %s' % (thread_num, err))
264 ret_codes.put((code, err))
265 elif re.search('x-goog-meta-executable:', out):
266 st = os.stat(output_filename)
267 os.chmod(output_filename, st.st_mode | stat.S_IEXEC)
[email protected]867e5b52013-03-13 21:43:51268
269def printer_worker(output_queue):
270 while True:
271 line = output_queue.get()
272 # Its plausible we want to print empty lines.
273 if line is None:
274 break
275 print line
276
277
278def download_from_google_storage(
279 input_filename, base_url, gsutil, num_threads, directory, recursive,
[email protected]c8270632014-01-17 22:28:30280 force, output, ignore_errors, sha1_file, verbose, auto_platform):
[email protected]867e5b52013-03-13 21:43:51281 # Start up all the worker threads.
282 all_threads = []
283 download_start = time.time()
284 stdout_queue = Queue.Queue()
285 work_queue = Queue.Queue()
286 ret_codes = Queue.Queue()
287 ret_codes.put((0, None))
288 for thread_num in range(num_threads):
289 t = threading.Thread(
290 target=_downloader_worker_thread,
291 args=[thread_num, work_queue, force, base_url,
[email protected]ff7ea002013-11-25 19:28:54292 gsutil, stdout_queue, ret_codes, verbose])
[email protected]867e5b52013-03-13 21:43:51293 t.daemon = True
294 t.start()
295 all_threads.append(t)
296 printer_thread = threading.Thread(target=printer_worker, args=[stdout_queue])
297 printer_thread.daemon = True
298 printer_thread.start()
299
300 # Enumerate our work queue.
301 work_queue_size = enumerate_work_queue(
302 input_filename, work_queue, directory, recursive,
[email protected]c8270632014-01-17 22:28:30303 ignore_errors, output, sha1_file, auto_platform)
[email protected]867e5b52013-03-13 21:43:51304 for _ in all_threads:
305 work_queue.put((None, None)) # Used to tell worker threads to stop.
306
307 # Wait for all downloads to finish.
308 for t in all_threads:
309 t.join()
310 stdout_queue.put(None)
311 printer_thread.join()
312
313 # See if we ran into any errors.
314 max_ret_code = 0
315 for ret_code, message in ret_codes.queue:
316 max_ret_code = max(ret_code, max_ret_code)
317 if message:
318 print >> sys.stderr, message
[email protected]ff7ea002013-11-25 19:28:54319 if verbose and not max_ret_code:
[email protected]867e5b52013-03-13 21:43:51320 print 'Success!'
321
[email protected]ff7ea002013-11-25 19:28:54322 if verbose:
323 print 'Downloading %d files took %1f second(s)' % (
324 work_queue_size, time.time() - download_start)
[email protected]867e5b52013-03-13 21:43:51325 return max_ret_code
326
327
328def main(args):
329 usage = ('usage: %prog [options] target\n'
330 'Target must be:\n'
331 ' (default) a sha1 sum ([A-Za-z0-9]{40}).\n'
332 ' (-s or --sha1_file) a .sha1 file, containing a sha1 sum on '
333 'the first line.\n'
334 ' (-d or --directory) A directory to scan for .sha1 files.')
335 parser = optparse.OptionParser(usage)
336 parser.add_option('-o', '--output',
337 help='Specify the output file name. Defaults to: '
338 '(a) Given a SHA1 hash, the name is the SHA1 hash. '
339 '(b) Given a .sha1 file or directory, the name will '
340 'match (.*).sha1.')
341 parser.add_option('-b', '--bucket',
342 help='Google Storage bucket to fetch from.')
343 parser.add_option('-e', '--boto',
344 help='Specify a custom boto file.')
345 parser.add_option('-c', '--no_resume', action='store_true',
346 help='Resume download if file is partially downloaded.')
347 parser.add_option('-f', '--force', action='store_true',
348 help='Force download even if local file exists.')
349 parser.add_option('-i', '--ignore_errors', action='store_true',
350 help='Don\'t throw error if we find an invalid .sha1 file.')
351 parser.add_option('-r', '--recursive', action='store_true',
352 help='Scan folders recursively for .sha1 files. '
353 'Must be used with -d/--directory')
354 parser.add_option('-t', '--num_threads', default=1, type='int',
355 help='Number of downloader threads to run.')
356 parser.add_option('-d', '--directory', action='store_true',
357 help='The target is a directory. '
358 'Cannot be used with -s/--sha1_file.')
359 parser.add_option('-s', '--sha1_file', action='store_true',
360 help='The target is a file containing a sha1 sum. '
361 'Cannot be used with -d/--directory.')
[email protected]0477f8c2013-06-26 22:23:57362 parser.add_option('-g', '--config', action='store_true',
363 help='Alias for "gsutil config". Run this if you want '
364 'to initialize your saved Google Storage '
[email protected]4b74fcd2014-01-10 23:36:24365 'credentials. This will create a read-only '
366 'credentials file in ~/.boto.depot_tools.')
[email protected]c61894c2013-11-19 20:25:21367 parser.add_option('-n', '--no_auth', action='store_true',
368 help='Skip auth checking. Use if it\'s known that the '
369 'target bucket is a public bucket.')
370 parser.add_option('-p', '--platform',
[email protected]ba63bcb2013-10-28 19:55:48371 help='A regular expression that is compared against '
372 'Python\'s sys.platform. If this option is specified, '
373 'the download will happen only if there is a match.')
[email protected]c8270632014-01-17 22:28:30374 parser.add_option('-a', '--auto_platform',
375 action='store_true',
376 help='Detects if any parent folder of the target matches '
377 '(linux|mac|win). If so, the script will only '
378 'process files that are in the paths that '
379 'that matches the current platform.')
[email protected]ff7ea002013-11-25 19:28:54380 parser.add_option('-v', '--verbose', action='store_true',
381 help='Output extra diagnostic and progress information.')
[email protected]867e5b52013-03-13 21:43:51382
383 (options, args) = parser.parse_args()
[email protected]ba63bcb2013-10-28 19:55:48384
385 # Make sure we should run at all based on platform matching.
386 if options.platform:
[email protected]c8270632014-01-17 22:28:30387 if options.auto_platform:
388 parser.error('--platform can not be specified with --auto_platform')
[email protected]7d4cc4a2013-12-06 18:30:57389 if not re.match(options.platform, GetNormalizedPlatform()):
[email protected]ff7ea002013-11-25 19:28:54390 if options.verbose:
391 print('The current platform doesn\'t match "%s", skipping.' %
392 options.platform)
[email protected]ba63bcb2013-10-28 19:55:48393 return 0
394
[email protected]c61894c2013-11-19 20:25:21395 # Set the boto file to /dev/null if we don't need auth.
396 if options.no_auth:
397 options.boto = os.devnull
398
[email protected]c6a2ee62013-12-12 08:26:18399 # Make sure gsutil exists where we expect it to.
[email protected]0477f8c2013-06-26 22:23:57400 if os.path.exists(GSUTIL_DEFAULT_PATH):
[email protected]c6a2ee62013-12-12 08:26:18401 gsutil = Gsutil(GSUTIL_DEFAULT_PATH,
402 boto_path=options.boto,
403 bypass_prodaccess=options.no_auth)
[email protected]0477f8c2013-06-26 22:23:57404 else:
[email protected]c6a2ee62013-12-12 08:26:18405 parser.error('gsutil not found in %s, bad depot_tools checkout?' %
406 GSUTIL_DEFAULT_PATH)
[email protected]0477f8c2013-06-26 22:23:57407
408 # Passing in -g/--config will run our copy of GSUtil, then quit.
409 if options.config:
[email protected]4b74fcd2014-01-10 23:36:24410 return gsutil.call('config', '-r', '-o',
411 os.path.expanduser('~/.boto.depot_tools'))
[email protected]0477f8c2013-06-26 22:23:57412
[email protected]867e5b52013-03-13 21:43:51413 if not args:
414 parser.error('Missing target.')
415 if len(args) > 1:
416 parser.error('Too many targets.')
417 if not options.bucket:
418 parser.error('Missing bucket. Specify bucket with --bucket.')
419 if options.sha1_file and options.directory:
420 parser.error('Both --directory and --sha1_file are specified, '
421 'can only specify one.')
422 if options.recursive and not options.directory:
423 parser.error('--recursive specified but --directory not specified.')
424 if options.output and options.directory:
425 parser.error('--directory is specified, so --output has no effect.')
[email protected]c8270632014-01-17 22:28:30426 if (not (options.sha1_file or options.directory)
427 and options.auto_platform):
428 parser.error('--auto_platform must be specified with either '
429 '--sha1_file or --directory')
430
[email protected]867e5b52013-03-13 21:43:51431 input_filename = args[0]
432
433 # Set output filename if not specified.
434 if not options.output and not options.directory:
435 if not options.sha1_file:
436 # Target is a sha1 sum, so output filename would also be the sha1 sum.
437 options.output = input_filename
438 elif options.sha1_file:
439 # Target is a .sha1 file.
440 if not input_filename.endswith('.sha1'):
441 parser.error('--sha1_file is specified, but the input filename '
442 'does not end with .sha1, and no --output is specified. '
443 'Either make sure the input filename has a .sha1 '
444 'extension, or specify --output.')
445 options.output = input_filename[:-5]
446 else:
447 parser.error('Unreachable state.')
448
449 # Check if output file already exists.
450 if not options.directory and not options.force and not options.no_resume:
451 if os.path.exists(options.output):
452 parser.error('Output file %s exists and --no_resume is specified.'
453 % options.output)
454
[email protected]867e5b52013-03-13 21:43:51455 # Check we have a valid bucket with valid permissions.
456 base_url, code = check_bucket_permissions(options.bucket, gsutil)
457 if code:
458 return code
459
460 return download_from_google_storage(
461 input_filename, base_url, gsutil, options.num_threads, options.directory,
462 options.recursive, options.force, options.output, options.ignore_errors,
[email protected]c8270632014-01-17 22:28:30463 options.sha1_file, options.verbose, options.auto_platform)
[email protected]867e5b52013-03-13 21:43:51464
465
466if __name__ == '__main__':
[email protected]acb9ed72013-06-20 12:16:15467 sys.exit(main(sys.argv))