Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(2289)

Unified Diff: build/google_storage_tools/download_from_google_storage.py

Issue 11664024: Scripts to download files from google storage based on sha1 sums (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Moved files into new folder Created 7 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « no previous file | build/google_storage_tools/upload_to_google_storage.py » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: build/google_storage_tools/download_from_google_storage.py
diff --git a/build/google_storage_tools/download_from_google_storage.py b/build/google_storage_tools/download_from_google_storage.py
new file mode 100755
index 0000000000000000000000000000000000000000..1debd3b2835b956c237d0d40d210ff86a60eac04
--- /dev/null
+++ b/build/google_storage_tools/download_from_google_storage.py
@@ -0,0 +1,273 @@
+#!/usr/bin/env python
+# Copyright (c) 2012 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+"""Script to download files from Google Storage."""
+
+
+import hashlib
+import optparse
+import os
+import Queue
+import re
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+import zipfile
+
+# TODO(hinoka): This is currently incorrect. Should find a better default.
+GSUTIL_DEFAULT_PATH = os.path.join(
+ os.path.dirname(os.path.abspath(__file__)),
+ '..', '..', 'third_party', 'gsutil', 'gsutil')
+
+
+class Gsutil(object):
+ def __init__(self, path, boto_path=None, timeout=None):
+ if not os.path.exists(path):
+ raise OSError('GSUtil not found in %s' % path)
+ self.path = path
+
+ self.timeout = timeout
+ self.boto_path = boto_path
+
+ def call(self, *args):
+ def _thread_main():
+ thr = threading.current_thread()
+ env = os.environ.copy()
+ if self.boto_path is not None:
+ env['AWS_CREDENTIAL_FILE'] = self.boto_path
+ thr.status = subprocess.call((sys.executable, self.path) + args, env=env)
+ t = threading.Thread(target=_thread_main)
+ t.start()
+ t.join(self.timeout)
+ if thr.isAlive():
+ raise RuntimeError('%s %s timed out after %d seconds.' % (
+ self.path, ' '.join(args), self.timeout))
+ return thr.status
+
+ def check_call(self, *args):
+ def _thread_main():
+ thr = threading.current_thread()
+ env = os.environ.copy()
+ if self.boto_path is not None:
+ env['AWS_CREDENTIAL_FILE'] = self.boto_path
+ p = subprocess.Popen((sys.executable, self.path) + args,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ env=env)
+ code = p.wait()
+ out, err = p.communicate()
+ thr.status = (code, out, err)
+
+ thr = threading.Thread(target=_thread_main)
+ thr.start()
+ thr.join(self.timeout)
+ if thr.isAlive():
+ raise RuntimeError('%s %s timed out after %d seconds.' % (
+ self.path, ' '.join(args), self.timeout))
+ code, out, err = thr.status
+ status_code_match = re.search('status=([0-9]+)', err)
+ if status_code_match:
+ return int(status_code_match.groups(1))
+ elif ('You are attempting to access protected data with '
+ 'no configured credentials.' in err):
+ return (403, out, err)
+ elif 'No such object' in err:
+ return (404, out, err)
+ else:
+ return (code, out, err)
+
+ def clone(self):
+ return Gsutil(self.path, self.boto_path, self.timeout)
+
+
+def CheckSHA1(sha1_sum, filename):
+ sha1 = hashlib.sha1()
+ with open(filename, 'rb') as f:
+ while True:
+ # Read in 1mb chunks, so it doesn't all have to be loaded into memory.
+ chunk = f.read(1024*1024)
+ if not chunk:
+ break
+ sha1.update(chunk)
+ return sha1_sum == sha1.hexdigest()
+
+
+def _downloader_worker_thread(thread_num, q, options, base_url, gsutil):
+ while True:
+ try:
+ input_sha1_sum, output_filename = q.get_nowait()
+ except Queue.Empty:
+ return
+ if os.path.exists(output_filename) and not options.force:
+ if CheckSHA1(input_sha1_sum, output_filename):
+ print 'File %s exists and SHA1 sum (%s) matches. Skipping.' % (
+ output_filename , input_sha1_sum)
+ continue
+ # Check if file exists.
+ file_url = '%s/%s' % (base_url, input_sha1_sum)
+ if gsutil.check_call('ls', file_url) != 0:
+ print >>sys.stderr, 'File %s for %s does not exist, skipping.' % (
+ file_url, output_filename)
+ continue
+ # Fetch the file.
+ print 'Downloading %s to %s...' % (file_url, output_filename)
+ code, out, err = gsutil.call('cp', '-q', file_url, output_filename)
+ if code != 0:
+ print >>sys.stderr, gsutil.stderr
+ return code
+
+
+def download_from_google_storage(input_filename, options):
+ # Check if output file already exists.
+ if not options.directory and not options.force and not options.no_resume:
+ if os.path.exists(options.output):
+ parser.error('Output file %s exists and --no_resume is specified.'
+ % options.output)
+
+
+ base_url = 'gs://%s' % options.bucket
+
+ # Make sure we can find a working instance of gsutil.
+ if os.path.exists(options.gsutil_path):
+ gsutil = Gsutil(options.gsutil_path, boto_path=options.boto)
+ else:
+ for path in os.environ["PATH"].split(os.pathsep):
+ if os.path.exists(path) and 'gsutil' in os.listdir(path):
+ gsutil = Gsutil(os.path.join(path, 'gsutil'), boto_path=options.boto)
+
+ # Check if we have permissions to the Google Storage bucket.
+ code, ls_out, ls_err = gsutil.check_call('ls', base_url)
+ if code == 403:
+ code, _, _ = gsutil.call('config')
+ if code != 0:
+ print >>sys.stderr, 'Error while authenticating to %s, exiting' % base_url
+ return 403
+ elif code == 404:
+ print >>sys.stderr, '%s not found.' % base_url
+ return 404
+ elif code != 0:
+ print >>sys.stderr, ls_err
+ return code
+
+ # Enumerate our work queue.
+ work_queue = Queue.Queue()
+ work_queue_size = 0
+ if options.directory:
+ if options.recursive:
+ for root, dirs, files in os.walk(input_filename):
+ for exclude in ['.svn', '.git']:
+ if exclude in dirs:
+ dirs.remove(exclude)
+ if not options.recursive:
+ for item in dirs:
+ dirs.remove(item)
+ for filename in files:
+ full_path = os.path.join(root, filename)
+ if full_path.endswith('.sha1'):
+ with open(full_path) as f:
+ sha1_match = re.search('^([A-Za-z0-9]{40})$', f.read(1024))
+ if sha1_match:
+ work_queue.put((sha1_match.groups(1)[0],
+ full_path.replace('.sha1', '')))
+ work_queue_size += 1
+ else:
+ print >>sys.stderr, 'No sha1 sum found in %s.' % filename
+ else:
+ work_queue.put((input_filename, options.output))
+ work_queue_size += 1
+
+ # Start up all the worker threads.
+ all_threads = []
+ download_timer = time.time()
+ for thread_num in range(options.num_threads):
+ t = threading.Thread(target=_downloader_worker_thread, args=[thread_num,
+ work_queue, options, base_url, gsutil.clone()])
+ t.daemon = True
+ t.start()
+ all_threads.append(t)
+
+ # Wait for all downloads to finish.
+ for t in all_threads:
+ t.join()
+
+ print 'Success.'
+ print 'Downloading %d files took %1f second(s)' % (
+ work_queue_size, time.time() - download_timer)
+ return 0
+
+
+def main(args):
+ usage = ('usage: %prog [options] target\nTarget must be:\n'
+ '(default) a sha1 sum ([A-Za-z0-9]{40}).\n(-s or --sha1_file) a '
+ '.sha1 file, containing a sha1 sum on the first line. (-d or '
+ '--directory) A directory to scan for .sha1 files. ')
+ parser = optparse.OptionParser(usage)
+ parser.add_option('-o', '--output', default=None,
+ help='Specify the output file name. Defaults to:\n'
+ '(a) Given a SHA1 hash, the name is the SHA1 hash.\n'
+ '(b) Given a .sha1 file or directory, the name will '
+ 'match (.*).sha1.')
+ parser.add_option('-b', '--bucket', default='chrome-artifacts',
+ help='Google Storage bucket to fetch from.')
+ parser.add_option('-e', '--boto', default=None,
+ help='Specify a custom boto file.')
+ parser.add_option('-c', '--no_resume', action='store_true', default=False,
+ help='Resume download if file is partially downloaded.')
+ parser.add_option('-f', '--force', action='store_true', default=False,
+ help='Force download even if local file exists.')
+ parser.add_option('-r', '--recursive', action='store_true', default=False,
+ help='Scan folders recursively for .sha1 files. '
+ 'Must be used with -d/--directory')
+ parser.add_option('-t', '--num_threads', default=1, type='int',
+ help='Number of downloader threads to run.')
+ parser.add_option('-d', '--directory', action='store_true', default=False,
+ help='The target is a directory. '
+ 'Cannot be used with -s/--sha1_file.')
+ parser.add_option('-s', '--sha1_file', action='store_true', default=False,
+ help='The target is a file containing a sha1 sum. '
+ 'Cannot be used with -d/--directory.')
+ # This file should be stored in tools/deps_scripts/ and we want the path to
+ # third_party/gsutil/gsutil
+ parser.add_option('-g', '--gsutil_path', default=GSUTIL_DEFAULT_PATH,
+ help='Path to the gsutil script.')
+
+ (options, args) = parser.parse_args()
+ if len(args) < 1:
+ parser.error('Missing target.')
+ if len(args) > 1:
+ parser.error('Too many targets.')
+ if options.sha1_file and options.directory:
+ parser.error('Both --directory and --sha1_file are specified, '
+ 'can only specify one.')
+ elif options.recursive and not options.directory:
+ parser.error('--recursive specified but --directory not specified.')
+ elif options.output and options.directory:
+ parser.error('--directory is specified, so --output has no effect.')
+ else:
+ input_filename = args[0]
+
+ # Set output filename if not specified.
+ if not options.output and not options.directory:
+ if not options.sha1_file:
+ # Target is a sha1 sum, so output filename would also be the sha1 sum.
+ options.output = input_filename
+ elif options.sha1_file:
+ # Target is a .sha1 file.
+ if not input_filename.endswith('.sha1'):
+ parser.error('--sha1_file is specified, but the input filename '
+ 'does not end with .sha1, and no --output is specified. '
+ 'Either make sure the input filename has a .sha1 '
+ 'extension, or specify --output.')
+ options.output = input_filename[:-5]
+ else:
+ raise NotImplementedError('Unreachable state.')
+
+ return download_from_google_storage(input_filename, options)
+
+
+if __name__ == '__main__':
+ sys.exit(main(sys.argv))
« no previous file with comments | « no previous file | build/google_storage_tools/upload_to_google_storage.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698