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

Side by Side Diff: download_from_google_storage.py

Issue 12042069: Scripts to download files from google storage based on sha1 sums (Closed) Base URL: https://chromium.googlesource.com/chromium/tools/depot_tools.git@master
Patch Set: Test fix Created 7 years, 9 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 unified diff | Download patch
« no previous file with comments | « no previous file | gstools.py » ('j') | upload_to_google_storage.py » ('J')
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(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, options):
M-A Ruel 2013/02/28 14:53:56 Please pass directory, recursive, output as 3 sepa
Ryan Tseng 2013/03/01 02:41:35 Done.
26 work_queue_size = 0
M-A Ruel 2013/02/28 14:53:56 if not directory: work_queue.put((input_filename
Ryan Tseng 2013/03/01 02:41:35 Done.
27 if options.directory:
28 for root, dirs, files in os.walk(input_filename):
29 if not options.recursive:
30 for item in dirs[:]:
31 dirs.remove(item)
32 else:
33 for exclude in ['.svn', '.git']:
34 if exclude in dirs:
35 dirs.remove(exclude)
36 for filename in files:
37 full_path = os.path.join(root, filename)
38 if full_path.endswith('.sha1'):
39 with open(full_path, 'rb') as f:
40 sha1_match = re.match('^([A-Za-z0-9]{40})$', f.read(1024).rstrip())
41 if sha1_match:
42 work_queue.put(
43 (sha1_match.groups(1)[0], full_path.replace('.sha1', '')))
44 work_queue_size += 1
45 else:
46 print >> sys.stderr, 'No sha1 sum found in %s.' % filename
M-A Ruel 2013/02/28 14:53:56 Is this an error or something to safely ignore?
Ryan Tseng 2013/03/01 02:41:35 Hm. This should probably throw an error and stop t
47 else:
48 work_queue.put((input_filename, options.output))
49 work_queue_size += 1
50 return work_queue_size
51
52
53 def _downloader_worker_thread(thread_num, q, options, base_url, gsutil, out_q):
54 while True:
55 input_sha1_sum, output_filename = q.get()
56 if input_sha1_sum is None:
57 out_q.put('Thread %d is done' % thread_num)
58 return
59 if os.path.exists(output_filename) and not options.force:
60 if gstools.GetSHA1(output_filename) == input_sha1_sum:
61 out_q.put('File %s exists and SHA1 sum (%s) matches. Skipping.' % (
M-A Ruel 2013/02/28 14:53:56 out_q.put( 'File ...
Ryan Tseng 2013/03/01 02:41:35 Done.
62 output_filename , input_sha1_sum))
63 continue
64 # Check if file exists.
65 file_url = '%s/%s' % (base_url, input_sha1_sum)
66 if gsutil.check_call('ls', file_url)[0] != 0:
67 out_q.put('File %s for %s does not exist, skipping.' % (
68 file_url, output_filename))
69 continue
70 # Fetch the file.
71 out_q.put('Downloading %s to %s...' % (file_url, output_filename))
72 code = gsutil.call('cp', '-q', file_url, output_filename)
73 if code != 0:
74 out_q.put(gsutil.stderr)
75 return code
76
77
78 def download_from_google_storage(input_filename, base_url, gsutil, options):
M-A Ruel 2013/02/28 14:53:56 Accept each option individually instead.
Ryan Tseng 2013/03/01 02:41:35 Done.
79 # Start up all the worker threads.
80 all_threads = []
81 download_timer = time.time()
82 stdout_queue = Queue.Queue()
83 work_queue = Queue.Queue()
84 for thread_num in range(options.num_threads):
85 t = threading.Thread(
86 target=_downloader_worker_thread,
87 args=[thread_num, work_queue, options, base_url,
88 gsutil.clone(), stdout_queue])
89 t.daemon = True
90 t.start()
91 all_threads.append(t)
92
93 # Enumerate our work queue.
94 work_queue_size = enumerate_work_queue(input_filename, work_queue, options)
95 for _ in all_threads:
96 work_queue.put((None, None)) # Used to tell worker threads to stop.
97
98 # Wait for all downloads to finish.
99 while True:
M-A Ruel 2013/02/28 14:53:56 while not any(t.is_alive() for t in all_threads) a
Ryan Tseng 2013/03/01 02:41:35 Done. That's a useful keyword :O Added some stuff
100 num_alive_threads = 0
101 for t in all_threads:
102 if t.is_alive():
103 num_alive_threads += 1
104 if num_alive_threads == 0 and stdout_queue.empty():
105 break
106 line = stdout_queue.get()
107 print line
108
109
110 print 'Success.'
111 print 'Downloading %d files took %1f second(s)' % (
112 work_queue_size, time.time() - download_timer)
113 return 0
114
115
116 def main(args):
117 usage = ('usage: %prog [options] target\nTarget must be:\n'
118 '(default) a sha1 sum ([A-Za-z0-9]{40}).\n(-s or --sha1_file) a '
119 '.sha1 file, containing a sha1 sum on the first line. (-d or '
120 '--directory) A directory to scan for .sha1 files. ')
121 parser = optparse.OptionParser(usage)
122 parser.add_option('-o', '--output',
123 help='Specify the output file name. Defaults to:\n'
124 '(a) Given a SHA1 hash, the name is the SHA1 hash.\n'
125 '(b) Given a .sha1 file or directory, the name will '
126 'match (.*).sha1.')
127 parser.add_option('-b', '--bucket',
128 help='Google Storage bucket to fetch from.')
129 parser.add_option('-e', '--boto',
130 help='Specify a custom boto file.')
131 parser.add_option('-c', '--no_resume', action='store_true',
132 help='Resume download if file is partially downloaded.')
133 parser.add_option('-f', '--force', action='store_true',
134 help='Force download even if local file exists.')
135 parser.add_option('-r', '--recursive', action='store_true',
136 help='Scan folders recursively for .sha1 files. '
137 'Must be used with -d/--directory')
138 parser.add_option('-t', '--num_threads', default=1, type='int',
139 help='Number of downloader threads to run.')
140 parser.add_option('-d', '--directory', action='store_true',
141 help='The target is a directory. '
142 'Cannot be used with -s/--sha1_file.')
143 parser.add_option('-s', '--sha1_file', action='store_true',
144 help='The target is a file containing a sha1 sum. '
145 'Cannot be used with -d/--directory.')
146
147 (options, args) = parser.parse_args()
148 if not args:
149 parser.error('Missing target.')
150 if len(args) > 1:
151 parser.error('Too many targets.')
152 if not options.bucket:
153 parser.error('Missing bucket. Specify bucket with --bucket.')
154 if options.sha1_file and options.directory:
155 parser.error('Both --directory and --sha1_file are specified, '
156 'can only specify one.')
157 elif options.recursive and not options.directory:
158 parser.error('--recursive specified but --directory not specified.')
159 elif options.output and options.directory:
160 parser.error('--directory is specified, so --output has no effect.')
161 else:
162 input_filename = args[0]
163
164 # Set output filename if not specified.
165 if not options.output and not options.directory:
166 if not options.sha1_file:
167 # Target is a sha1 sum, so output filename would also be the sha1 sum.
168 options.output = input_filename
169 elif options.sha1_file:
170 # Target is a .sha1 file.
171 if not input_filename.endswith('.sha1'):
172 parser.error('--sha1_file is specified, but the input filename '
173 'does not end with .sha1, and no --output is specified. '
174 'Either make sure the input filename has a .sha1 '
175 'extension, or specify --output.')
176 options.output = input_filename[:-5]
177 else:
178 raise NotImplementedError('Unreachable state.')
179
180 # Check if output file already exists.
181 if not options.directory and not options.force and not options.no_resume:
182 if os.path.exists(options.output):
183 parser.error('Output file %s exists and --no_resume is specified.'
184 % options.output)
185
186 # Make sure we can find a working instance of gsutil.
187 if os.path.exists(GSUTIL_DEFAULT_PATH):
188 gsutil = gstools.Gsutil(GSUTIL_DEFAULT_PATH)
189 else:
190 print >> sys.stderr, ('gsutil not found in %s, bad depot_tools checkout?' %
191 GSUTIL_DEFAULT_PATH)
192 return 1
193
194 # Check we have a valid bucket with valid permissions.
195 base_url, code = gstools.CheckBucketPermissions(options.bucket, gsutil)
196 if code:
197 return code
198
199 return download_from_google_storage(input_filename, base_url, gsutil, options)
200
201
202 if __name__ == '__main__':
203 sys.exit(main(sys.argv))
OLDNEW
« no previous file with comments | « no previous file | gstools.py » ('j') | upload_to_google_storage.py » ('J')

Powered by Google App Engine
This is Rietveld 408576698