OLD | NEW |
---|---|
(Empty) | |
1 #!/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 | |
9 import optparse | |
10 import os | |
11 import Queue | |
12 import re | |
13 import sys | |
14 import threading | |
15 import time | |
16 | |
17 import gstools | |
18 | |
19 | |
20 GSUTIL_DEFAULT_PATH = os.path.join( | |
21 os.path.dirname(os.path.abspath(__file__)), | |
22 'third_party', 'gsutil', 'gsutil') | |
23 | |
24 | |
25 def enumerate_work_queue(input_filename, work_queue, directory, | |
26 recursive, ignore_errors, output, sha1_file): | |
27 if sha1_file: | |
28 with open(input_filename, 'rb') as f: | |
M-A Ruel
2013/03/03 02:13:14
is it fine if it throws an exception when the file
| |
29 sha1_match = re.match('^([A-Za-z0-9]{40})$', f.read(1024).rstrip()) | |
30 if sha1_match: | |
M-A Ruel
2013/03/03 02:13:14
It's awkward that you silently ignore invalid .sha
Ryan Tseng
2013/03/04 21:43:54
Errors added. Ignorable using the -i flag.
| |
31 work_queue.put( | |
32 (sha1_match.groups(1)[0], input_filename.replace('.sha1', ''))) | |
33 return 1 | |
34 return 0 | |
35 | |
36 if not directory: | |
37 work_queue.put((input_filename, output)) | |
38 return 1 | |
39 | |
40 work_queue_size = 0 | |
41 for root, dirs, files in os.walk(input_filename): | |
42 if not recursive: | |
43 for item in dirs[:]: | |
44 dirs.remove(item) | |
45 else: | |
46 for exclude in ['.svn', '.git']: | |
47 if exclude in dirs: | |
48 dirs.remove(exclude) | |
49 for filename in files: | |
50 full_path = os.path.join(root, filename) | |
51 if full_path.endswith('.sha1'): | |
52 with open(full_path, 'rb') as f: | |
53 sha1_match = re.match('^([A-Za-z0-9]{40})$', f.read(1024).rstrip()) | |
54 if sha1_match: | |
55 work_queue.put( | |
56 (sha1_match.groups(1)[0], full_path.replace('.sha1', ''))) | |
57 work_queue_size += 1 | |
58 else: | |
59 print >> sys.stderr, 'No sha1 sum found in %s.' % filename | |
60 if not ignore_errors: | |
61 raise Exception('No sha1 sum found in %s.' % filename) | |
62 return work_queue_size | |
63 | |
64 | |
65 def _downloader_worker_thread(thread_num, q, force, base_url, gsutil, out_q): | |
66 while True: | |
67 input_sha1_sum, output_filename = q.get() | |
68 if input_sha1_sum is None: | |
69 out_q.put('Thread %d is done' % thread_num) | |
70 return | |
71 if os.path.exists(output_filename) and not force: | |
72 if gstools.GetSHA1(output_filename) == input_sha1_sum: | |
73 out_q.put( | |
74 'File %s exists and SHA1 sum (%s) matches. Skipping.' % ( | |
75 output_filename , input_sha1_sum)) | |
76 continue | |
77 # Check if file exists. | |
78 file_url = '%s/%s' % (base_url, input_sha1_sum) | |
79 if gsutil.check_call('ls', file_url)[0] != 0: | |
80 out_q.put('File %s for %s does not exist, skipping.' % ( | |
81 file_url, output_filename)) | |
82 continue | |
83 # Fetch the file. | |
84 out_q.put('Downloading %s to %s...' % (file_url, output_filename)) | |
85 code, _, err = gsutil.check_call('cp', '-q', file_url, output_filename) | |
86 if code != 0: | |
87 out_q.put(err) | |
88 return code | |
89 | |
90 | |
91 def download_from_google_storage( | |
92 input_filename, base_url, gsutil, num_threads, directory, recursive, | |
93 force, output, ignore_errors, sha1_file): | |
94 # Start up all the worker threads. | |
95 all_threads = [] | |
96 download_timer = time.time() | |
97 stdout_queue = Queue.Queue() | |
98 work_queue = Queue.Queue() | |
99 for thread_num in range(num_threads): | |
100 t = threading.Thread( | |
101 target=_downloader_worker_thread, | |
102 args=[thread_num, work_queue, force, base_url, | |
103 gsutil.clone(), stdout_queue]) | |
104 t.daemon = True | |
105 t.start() | |
106 all_threads.append(t) | |
107 | |
108 # Enumerate our work queue. | |
109 work_queue_size = enumerate_work_queue( | |
110 input_filename, work_queue, directory, recursive, | |
111 ignore_errors, output, sha1_file) | |
112 for _ in all_threads: | |
113 work_queue.put((None, None)) # Used to tell worker threads to stop. | |
114 | |
115 # Wait for all downloads to finish. | |
116 while not work_queue.empty() or any(t.is_alive() for t in all_threads): | |
117 print stdout_queue.get() | |
118 while not stdout_queue.empty(): | |
119 print stdout_queue.get() | |
120 | |
121 print 'Success.' | |
122 print 'Downloading %d files took %1f second(s)' % ( | |
123 work_queue_size, time.time() - download_timer) | |
124 return 0 | |
125 | |
126 | |
127 def main(args): | |
128 usage = ('usage: %prog [options] target\nTarget must be:\n' | |
129 '(default) a sha1 sum ([A-Za-z0-9]{40}).\n(-s or --sha1_file) a ' | |
130 '.sha1 file, containing a sha1 sum on the first line. (-d or ' | |
131 '--directory) A directory to scan for .sha1 files. ') | |
132 parser = optparse.OptionParser(usage) | |
133 parser.add_option('-o', '--output', | |
134 help='Specify the output file name. Defaults to:\n' | |
135 '(a) Given a SHA1 hash, the name is the SHA1 hash.\n' | |
136 '(b) Given a .sha1 file or directory, the name will ' | |
137 'match (.*).sha1.') | |
138 parser.add_option('-b', '--bucket', | |
139 help='Google Storage bucket to fetch from.') | |
140 parser.add_option('-e', '--boto', | |
141 help='Specify a custom boto file.') | |
142 parser.add_option('-c', '--no_resume', action='store_true', | |
143 help='Resume download if file is partially downloaded.') | |
144 parser.add_option('-f', '--force', action='store_true', | |
145 help='Force download even if local file exists.') | |
146 parser.add_option('-i', '--ignore_errors', action='store_true', | |
147 help='Don\'t throw error if we find an invalid .sha1 file.') | |
148 parser.add_option('-r', '--recursive', action='store_true', | |
149 help='Scan folders recursively for .sha1 files. ' | |
150 'Must be used with -d/--directory') | |
151 parser.add_option('-t', '--num_threads', default=1, type='int', | |
152 help='Number of downloader threads to run.') | |
153 parser.add_option('-d', '--directory', action='store_true', | |
154 help='The target is a directory. ' | |
155 'Cannot be used with -s/--sha1_file.') | |
156 parser.add_option('-s', '--sha1_file', action='store_true', | |
157 help='The target is a file containing a sha1 sum. ' | |
158 'Cannot be used with -d/--directory.') | |
159 | |
160 (options, args) = parser.parse_args() | |
161 if not args: | |
162 parser.error('Missing target.') | |
163 if len(args) > 1: | |
164 parser.error('Too many targets.') | |
165 if not options.bucket: | |
166 parser.error('Missing bucket. Specify bucket with --bucket.') | |
167 if options.sha1_file and options.directory: | |
168 parser.error('Both --directory and --sha1_file are specified, ' | |
169 'can only specify one.') | |
170 elif options.recursive and not options.directory: | |
171 parser.error('--recursive specified but --directory not specified.') | |
172 elif options.output and options.directory: | |
173 parser.error('--directory is specified, so --output has no effect.') | |
174 else: | |
175 input_filename = args[0] | |
176 | |
177 # Set output filename if not specified. | |
178 if not options.output and not options.directory: | |
179 if not options.sha1_file: | |
180 # Target is a sha1 sum, so output filename would also be the sha1 sum. | |
181 options.output = input_filename | |
182 elif options.sha1_file: | |
183 # Target is a .sha1 file. | |
184 if not input_filename.endswith('.sha1'): | |
185 parser.error('--sha1_file is specified, but the input filename ' | |
186 'does not end with .sha1, and no --output is specified. ' | |
187 'Either make sure the input filename has a .sha1 ' | |
188 'extension, or specify --output.') | |
189 options.output = input_filename[:-5] | |
190 else: | |
191 raise NotImplementedError('Unreachable state.') | |
192 | |
193 # Check if output file already exists. | |
194 if not options.directory and not options.force and not options.no_resume: | |
195 if os.path.exists(options.output): | |
196 parser.error('Output file %s exists and --no_resume is specified.' | |
197 % options.output) | |
198 | |
199 # Make sure we can find a working instance of gsutil. | |
200 if os.path.exists(GSUTIL_DEFAULT_PATH): | |
201 gsutil = gstools.Gsutil(GSUTIL_DEFAULT_PATH) | |
202 else: | |
203 print >> sys.stderr, ('gsutil not found in %s, bad depot_tools checkout?' % | |
204 GSUTIL_DEFAULT_PATH) | |
205 return 1 | |
206 | |
207 # Check we have a valid bucket with valid permissions. | |
208 base_url, code = gstools.CheckBucketPermissions(options.bucket, gsutil) | |
209 if code: | |
210 return code | |
211 | |
212 return download_from_google_storage( | |
213 input_filename, base_url, gsutil, options.num_threads, options.directory, | |
214 options.recursive, options.force, options.output, options.ignore_errors, | |
215 options.sha1_file) | |
216 | |
217 | |
218 if __name__ == '__main__': | |
219 sys.exit(main(sys.argv)) | |
OLD | NEW |