blob: 868f4f17ef3a38ca19647ce68ace310b43d93de6 [file] [log] [blame]
maruel@chromium.orgc6f90062012-11-07 18:32:22 +00001#!/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"""Archives a set of files to a server."""
7
8import binascii
9import hashlib
10import logging
11import optparse
12import os
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +000013import cStringIO
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000014import sys
15import time
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +000016import zlib
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000017
18import run_isolated
csharp@chromium.org07fa7592013-01-11 18:19:30 +000019import run_test_cases
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000020
21
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000022# The minimum size of files to upload directly to the blobstore.
maruel@chromium.orgaef29f82012-12-12 15:00:42 +000023MIN_SIZE_FOR_DIRECT_BLOBSTORE = 20 * 1024
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000024
csharp@chromium.org07fa7592013-01-11 18:19:30 +000025# The number of files to check the isolate server for each query.
csharp@chromium.org20a888c2013-01-15 15:06:55 +000026ITEMS_PER_CONTAINS_QUERY = 500
csharp@chromium.org07fa7592013-01-11 18:19:30 +000027
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +000028# A list of already compressed extension types that should not receive any
29# compression before being uploaded.
30ALREADY_COMPRESSED_TYPES = [
31 '7z', 'avi', 'cur', 'gif', 'h264', 'jar', 'jpeg', 'jpg', 'pdf', 'png',
32 'wav', 'zip'
33]
34
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000035
36def encode_multipart_formdata(fields, files,
37 mime_mapper=lambda _: 'application/octet-stream'):
38 """Encodes a Multipart form data object.
39
40 Args:
41 fields: a sequence (name, value) elements for
42 regular form fields.
43 files: a sequence of (name, filename, value) elements for data to be
44 uploaded as files.
45 mime_mapper: function to return the mime type from the filename.
46 Returns:
47 content_type: for httplib.HTTP instance
48 body: for httplib.HTTP instance
49 """
50 boundary = hashlib.md5(str(time.time())).hexdigest()
51 body_list = []
52 for (key, value) in fields:
53 if isinstance(key, unicode):
54 value = key.encode('utf-8')
55 if isinstance(value, unicode):
56 value = value.encode('utf-8')
57 body_list.append('--' + boundary)
58 body_list.append('Content-Disposition: form-data; name="%s"' % key)
59 body_list.append('')
60 body_list.append(value)
61 body_list.append('--' + boundary)
62 body_list.append('')
63 for (key, filename, value) in files:
64 if isinstance(key, unicode):
65 value = key.encode('utf-8')
66 if isinstance(filename, unicode):
67 value = filename.encode('utf-8')
68 if isinstance(value, unicode):
69 value = value.encode('utf-8')
70 body_list.append('--' + boundary)
71 body_list.append('Content-Disposition: form-data; name="%s"; '
72 'filename="%s"' % (key, filename))
73 body_list.append('Content-Type: %s' % mime_mapper(filename))
74 body_list.append('')
75 body_list.append(value)
76 body_list.append('--' + boundary)
77 body_list.append('')
78 if body_list:
79 body_list[-2] += '--'
80 body = '\r\n'.join(body_list)
81 content_type = 'multipart/form-data; boundary=%s' % boundary
82 return content_type, body
83
84
maruel@chromium.org037758d2012-12-10 17:59:46 +000085def sha1_file(filepath):
86 """Calculates the SHA-1 of a file without reading it all in memory at once."""
87 digest = hashlib.sha1()
88 with open(filepath, 'rb') as f:
89 while True:
90 # Read in 1mb chunks.
91 chunk = f.read(1024*1024)
92 if not chunk:
93 break
94 digest.update(chunk)
95 return digest.hexdigest()
96
97
maruel@chromium.orgef333122013-03-12 20:36:40 +000098def url_open(url, *args, **kwargs):
99 result = run_isolated.url_open(url, *args, **kwargs)
100 if not result:
101 # If we get no response from the server, assume it is down and raise an
102 # exception.
103 raise run_isolated.MappingError('Unable to connect to server %s' % url)
104 return result
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000105
106
maruel@chromium.orgdc359e62013-03-14 13:08:55 +0000107def upload_hash_content_to_blobstore(
108 generate_upload_url, data, hash_key, content):
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000109 """Uploads the given hash contents directly to the blobsotre via a generated
110 url.
111
112 Arguments:
113 generate_upload_url: The url to get the new upload url from.
maruel@chromium.orgdc359e62013-03-14 13:08:55 +0000114 data: extra POST data.
115 hash_key: sha1 of the uncompressed version of content.
116 content: The contents to upload. Must fit in memory for now.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000117 """
118 logging.debug('Generating url to directly upload file to blobstore')
maruel@chromium.org92a3d2e2012-12-20 16:22:29 +0000119 assert isinstance(hash_key, str), hash_key
120 assert isinstance(content, str), (hash_key, content)
maruel@chromium.orgdc359e62013-03-14 13:08:55 +0000121 upload_url = url_open(generate_upload_url, data).read()
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000122
123 if not upload_url:
124 logging.error('Unable to generate upload url')
125 return
126
maruel@chromium.orgdc359e62013-03-14 13:08:55 +0000127 # TODO(maruel): Support large files.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000128 content_type, body = encode_multipart_formdata(
maruel@chromium.orgdc359e62013-03-14 13:08:55 +0000129 [], [('hash_contents', hash_key, content)] + data)
maruel@chromium.orgef333122013-03-12 20:36:40 +0000130 return url_open(upload_url, body, content_type=content_type)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000131
132
133class UploadRemote(run_isolated.Remote):
maruel@chromium.org034e3962013-03-13 13:34:25 +0000134 def __init__(self, namespace, base_url, token):
maruel@chromium.org21243ce2012-12-20 17:43:00 +0000135 self.namespace = str(namespace)
maruel@chromium.org034e3962013-03-13 13:34:25 +0000136 self._token = token
137 super(UploadRemote, self).__init__(base_url)
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000138
139 def get_file_handler(self, base_url):
maruel@chromium.org21243ce2012-12-20 17:43:00 +0000140 base_url = str(base_url)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000141 def upload_file(content, hash_key):
maruel@chromium.org034e3962013-03-13 13:34:25 +0000142 # TODO(maruel): Detect failures.
maruel@chromium.org21243ce2012-12-20 17:43:00 +0000143 hash_key = str(hash_key)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000144 content_url = base_url.rstrip('/') + '/content/'
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000145 if len(content) > MIN_SIZE_FOR_DIRECT_BLOBSTORE:
maruel@chromium.orgdc359e62013-03-14 13:08:55 +0000146 url = '%sgenerate_blobstore_url/%s/%s' % (
147 content_url, self.namespace, hash_key)
148 data = [('token', self._token)]
149 upload_hash_content_to_blobstore(url, data, hash_key, content)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000150 else:
maruel@chromium.org034e3962013-03-13 13:34:25 +0000151 url = '%sstore/%s/%s?token=%s' % (
152 content_url, self.namespace, hash_key, self._token)
153 url_open(url, content, content_type='application/octet-stream')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000154 return upload_file
155
156
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000157def update_files_to_upload(query_url, queries, upload):
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000158 """Queries the server to see which files from this batch already exist there.
159
160 Arguments:
161 queries: The hash files to potential upload to the server.
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000162 upload: Any new files that need to be upload are sent to this function.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000163 """
164 body = ''.join(
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000165 (binascii.unhexlify(meta_data['h']) for (_, meta_data) in queries))
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000166 assert (len(body) % 20) == 0, repr(body)
167
maruel@chromium.orgef333122013-03-12 20:36:40 +0000168 response = url_open(
169 query_url, body, content_type='application/octet-stream').read()
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000170 if len(queries) != len(response):
171 raise run_isolated.MappingError(
172 'Got an incorrect number of responses from the server. Expected %d, '
173 'but got %d' % (len(queries), len(response)))
174
175 hit = 0
176 for i in range(len(response)):
177 if response[i] == chr(0):
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000178 upload(queries[i])
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000179 else:
180 hit += 1
181 logging.info('Queried %d files, %d cache hit', len(queries), hit)
182
183
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000184def compression_level(filename):
185 """Given a filename calculates the ideal compression level to use."""
186 file_ext = os.path.splitext(filename)[1].lower()
187 # TODO(csharp): Profile to find what compression level works best.
188 return 0 if file_ext in ALREADY_COMPRESSED_TYPES else 7
189
190
191def zip_and_trigger_upload(infile, metadata, upload_function):
192 compressor = zlib.compressobj(compression_level(infile))
193 hash_data = cStringIO.StringIO()
194 with open(infile, 'rb') as f:
195 # TODO(csharp): Fix crbug.com/150823 and enable the touched logic again.
196 while True: # and not metadata['T']:
197 chunk = f.read(run_isolated.ZIPPED_FILE_CHUNK)
198 if not chunk:
199 break
200 hash_data.write(compressor.compress(chunk))
201
202 hash_data.write(compressor.flush(zlib.Z_FINISH))
203 priority = (
204 run_isolated.Remote.HIGH if metadata.get('priority', '1') == '0'
205 else run_isolated.Remote.MED)
206 upload_function(priority, hash_data.getvalue(), metadata['h'],
207 None)
208 hash_data.close()
209
210
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000211def process_items(contains_hash_url, infiles, zip_and_upload):
212 """Generates the list of files that need to be uploaded and send them to
213 zip_and_upload.
214
215 Some may already be on the server.
216 """
217 next_queries = []
csharp@chromium.org90c45812013-01-23 14:27:21 +0000218 items = ((k, v) for k, v in infiles.iteritems() if 's' in v)
219 for relfile, metadata in sorted(items, key=lambda x: -x[1]['s']):
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000220 next_queries.append((relfile, metadata))
221 if len(next_queries) == ITEMS_PER_CONTAINS_QUERY:
222 update_files_to_upload(contains_hash_url, next_queries, zip_and_upload)
223 next_queries = []
224 if next_queries:
225 update_files_to_upload(contains_hash_url, next_queries, zip_and_upload)
226
227
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000228def upload_sha1_tree(base_url, indir, infiles, namespace):
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000229 """Uploads the given tree to the given url.
230
231 Arguments:
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000232 base_url: The base url, it is assume that |base_url|/has/ can be used to
233 query if an element was already uploaded, and |base_url|/store/
234 can be used to upload a new element.
235 indir: Root directory the infiles are based in.
236 infiles: dict of files to map from |indir| to |outdir|.
237 namespace: The namespace to use on the server.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000238 """
239 logging.info('upload tree(base_url=%s, indir=%s, files=%d)' %
240 (base_url, indir, len(infiles)))
241
maruel@chromium.org034e3962013-03-13 13:34:25 +0000242 # TODO(maruel): Make this request much earlier asynchronously while the files
243 # are being enumerated.
244 token = url_open(base_url + '/content/get_token').read()
245
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000246 # Create a pool of workers to zip and upload any files missing from
247 # the server.
maruel@chromium.org6b0c9ec2013-01-18 00:34:31 +0000248 num_threads = run_test_cases.num_processors()
249 zipping_pool = run_isolated.ThreadPool(num_threads, num_threads, 0)
maruel@chromium.org034e3962013-03-13 13:34:25 +0000250 remote_uploader = UploadRemote(namespace, base_url, token)
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000251
252 # Starts the zip and upload process for a given query. The query is assumed
253 # to be in the format (relfile, metadata).
csharp@chromium.org20a888c2013-01-15 15:06:55 +0000254 uploaded = []
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000255 def zip_and_upload(query):
256 relfile, metadata = query
257 infile = os.path.join(indir, relfile)
maruel@chromium.org831958f2013-01-22 15:01:46 +0000258 zipping_pool.add_task(0, zip_and_trigger_upload, infile, metadata,
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000259 remote_uploader.add_item)
csharp@chromium.org20a888c2013-01-15 15:06:55 +0000260 uploaded.append(query)
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000261
maruel@chromium.org034e3962013-03-13 13:34:25 +0000262 contains_hash_url = '%s/content/contains/%s?token=%s' % (
263 base_url.rstrip('/'), namespace, token)
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000264 process_items(contains_hash_url, infiles, zip_and_upload)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000265
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000266 logging.info('Waiting for all files to finish zipping')
267 zipping_pool.join()
268 logging.info('All files zipped.')
269
270 logging.info('Waiting for all files to finish uploading')
maruel@chromium.org13eca0b2013-01-22 16:42:21 +0000271 # Will raise if any exception occurred.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000272 remote_uploader.join()
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000273 logging.info('All files are uploaded')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000274
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000275 total = len(infiles)
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000276 total_size = sum(metadata.get('s', 0) for metadata in infiles.itervalues())
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000277 logging.info(
278 'Total: %6d, %9.1fkb',
279 total,
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000280 sum(m.get('s', 0) for m in infiles.itervalues()) / 1024.)
csharp@chromium.org20a888c2013-01-15 15:06:55 +0000281 cache_hit = set(infiles.iterkeys()) - set(x[0] for x in uploaded)
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000282 cache_hit_size = sum(infiles[i].get('s', 0) for i in cache_hit)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000283 logging.info(
284 'cache hit: %6d, %9.1fkb, %6.2f%% files, %6.2f%% size',
285 len(cache_hit),
286 cache_hit_size / 1024.,
287 len(cache_hit) * 100. / total,
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000288 cache_hit_size * 100. / total_size if total_size else 0)
csharp@chromium.org20a888c2013-01-15 15:06:55 +0000289 cache_miss = uploaded
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000290 cache_miss_size = sum(infiles[i[0]].get('s', 0) for i in cache_miss)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000291 logging.info(
292 'cache miss: %6d, %9.1fkb, %6.2f%% files, %6.2f%% size',
293 len(cache_miss),
294 cache_miss_size / 1024.,
295 len(cache_miss) * 100. / total,
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000296 cache_miss_size * 100. / total_size if total_size else 0)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000297
298
299def main():
300 parser = optparse.OptionParser(
301 usage='%prog [options] <file1..fileN> or - to read from stdin',
302 description=sys.modules[__name__].__doc__)
303 # TODO(maruel): Support both NFS and isolateserver.
304 parser.add_option('-o', '--outdir', help='Remote server to archive to')
305 parser.add_option(
306 '-v', '--verbose',
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000307 action='count', default=0,
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000308 help='Use multiple times to increase verbosity')
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000309 parser.add_option('--namespace', default='default-gzip',
310 help='The namespace to use on the server.')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000311
312 options, files = parser.parse_args()
313
314 levels = [logging.ERROR, logging.INFO, logging.DEBUG]
315 logging.basicConfig(
316 level=levels[min(len(levels)-1, options.verbose)],
317 format='%(levelname)5s %(module)15s(%(lineno)3d): %(message)s')
318 if files == ['-']:
319 files = sys.stdin.readlines()
320
321 if not files:
322 parser.error('Nothing to upload')
323 if not options.outdir:
324 parser.error('Nowhere to send. Please specify --outdir')
325
326 # Load the necessary metadata. This is going to be rewritten eventually to be
327 # more efficient.
328 infiles = dict(
329 (
330 f,
331 {
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000332 's': os.stat(f).st_size,
maruel@chromium.org037758d2012-12-10 17:59:46 +0000333 'h': sha1_file(f),
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000334 }
335 )
336 for f in files)
337
338 with run_isolated.Profiler('Archive'):
339 upload_sha1_tree(
340 base_url=options.outdir,
341 indir=os.getcwd(),
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000342 infiles=infiles,
343 namespace=options.namespace)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000344 return 0
345
346
347if __name__ == '__main__':
348 sys.exit(main())