blob: ce3b4501ce42469c48c2047370e288f7d5592490 [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
maruel@chromium.orge82112e2013-04-24 14:41:55 +000016import urllib
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +000017import zlib
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000018
19import run_isolated
csharp@chromium.org07fa7592013-01-11 18:19:30 +000020import run_test_cases
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000021
22
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000023# The minimum size of files to upload directly to the blobstore.
maruel@chromium.orgaef29f82012-12-12 15:00:42 +000024MIN_SIZE_FOR_DIRECT_BLOBSTORE = 20 * 1024
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000025
csharp@chromium.org07fa7592013-01-11 18:19:30 +000026# The number of files to check the isolate server for each query.
csharp@chromium.org20a888c2013-01-15 15:06:55 +000027ITEMS_PER_CONTAINS_QUERY = 500
csharp@chromium.org07fa7592013-01-11 18:19:30 +000028
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +000029# A list of already compressed extension types that should not receive any
30# compression before being uploaded.
31ALREADY_COMPRESSED_TYPES = [
32 '7z', 'avi', 'cur', 'gif', 'h264', 'jar', 'jpeg', 'jpg', 'pdf', 'png',
33 'wav', 'zip'
34]
35
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000036
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +000037def randomness():
38 """Generates low-entropy randomness for MIME encoding.
39
40 Exists so it can be mocked out in unit tests.
41 """
42 return str(time.time())
43
44
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000045def encode_multipart_formdata(fields, files,
46 mime_mapper=lambda _: 'application/octet-stream'):
47 """Encodes a Multipart form data object.
48
49 Args:
50 fields: a sequence (name, value) elements for
51 regular form fields.
52 files: a sequence of (name, filename, value) elements for data to be
53 uploaded as files.
54 mime_mapper: function to return the mime type from the filename.
55 Returns:
56 content_type: for httplib.HTTP instance
57 body: for httplib.HTTP instance
58 """
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +000059 boundary = hashlib.md5(randomness()).hexdigest()
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000060 body_list = []
61 for (key, value) in fields:
62 if isinstance(key, unicode):
63 value = key.encode('utf-8')
64 if isinstance(value, unicode):
65 value = value.encode('utf-8')
66 body_list.append('--' + boundary)
67 body_list.append('Content-Disposition: form-data; name="%s"' % key)
68 body_list.append('')
69 body_list.append(value)
70 body_list.append('--' + boundary)
71 body_list.append('')
72 for (key, filename, value) in files:
73 if isinstance(key, unicode):
74 value = key.encode('utf-8')
75 if isinstance(filename, unicode):
76 value = filename.encode('utf-8')
77 if isinstance(value, unicode):
78 value = value.encode('utf-8')
79 body_list.append('--' + boundary)
80 body_list.append('Content-Disposition: form-data; name="%s"; '
81 'filename="%s"' % (key, filename))
82 body_list.append('Content-Type: %s' % mime_mapper(filename))
83 body_list.append('')
84 body_list.append(value)
85 body_list.append('--' + boundary)
86 body_list.append('')
87 if body_list:
88 body_list[-2] += '--'
89 body = '\r\n'.join(body_list)
90 content_type = 'multipart/form-data; boundary=%s' % boundary
91 return content_type, body
92
93
maruel@chromium.org037758d2012-12-10 17:59:46 +000094def sha1_file(filepath):
95 """Calculates the SHA-1 of a file without reading it all in memory at once."""
96 digest = hashlib.sha1()
97 with open(filepath, 'rb') as f:
98 while True:
99 # Read in 1mb chunks.
100 chunk = f.read(1024*1024)
101 if not chunk:
102 break
103 digest.update(chunk)
104 return digest.hexdigest()
105
106
maruel@chromium.org000bb4d2013-04-26 17:53:27 +0000107def url_open(url, **kwargs):
108 result = run_isolated.url_open(url, **kwargs)
maruel@chromium.orgef333122013-03-12 20:36:40 +0000109 if not result:
110 # If we get no response from the server, assume it is down and raise an
111 # exception.
112 raise run_isolated.MappingError('Unable to connect to server %s' % url)
113 return result
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000114
115
maruel@chromium.orgdc359e62013-03-14 13:08:55 +0000116def upload_hash_content_to_blobstore(
117 generate_upload_url, data, hash_key, content):
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000118 """Uploads the given hash contents directly to the blobsotre via a generated
119 url.
120
121 Arguments:
122 generate_upload_url: The url to get the new upload url from.
maruel@chromium.orgdc359e62013-03-14 13:08:55 +0000123 data: extra POST data.
124 hash_key: sha1 of the uncompressed version of content.
125 content: The contents to upload. Must fit in memory for now.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000126 """
127 logging.debug('Generating url to directly upload file to blobstore')
maruel@chromium.org92a3d2e2012-12-20 16:22:29 +0000128 assert isinstance(hash_key, str), hash_key
129 assert isinstance(content, str), (hash_key, content)
maruel@chromium.org000bb4d2013-04-26 17:53:27 +0000130 upload_url = url_open(generate_upload_url, data=data).read()
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000131
132 if not upload_url:
133 logging.error('Unable to generate upload url')
134 return
135
maruel@chromium.orgdc359e62013-03-14 13:08:55 +0000136 # TODO(maruel): Support large files.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000137 content_type, body = encode_multipart_formdata(
maruel@chromium.orgd7d83cc2013-04-25 19:21:30 +0000138 data, [('content', hash_key, content)])
maruel@chromium.org000bb4d2013-04-26 17:53:27 +0000139 return url_open(upload_url, data=body, content_type=content_type)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000140
141
142class UploadRemote(run_isolated.Remote):
maruel@chromium.org034e3962013-03-13 13:34:25 +0000143 def __init__(self, namespace, base_url, token):
maruel@chromium.org21243ce2012-12-20 17:43:00 +0000144 self.namespace = str(namespace)
maruel@chromium.org034e3962013-03-13 13:34:25 +0000145 self._token = token
146 super(UploadRemote, self).__init__(base_url)
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000147
148 def get_file_handler(self, base_url):
maruel@chromium.org21243ce2012-12-20 17:43:00 +0000149 base_url = str(base_url)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000150 def upload_file(content, hash_key):
maruel@chromium.org034e3962013-03-13 13:34:25 +0000151 # TODO(maruel): Detect failures.
maruel@chromium.org21243ce2012-12-20 17:43:00 +0000152 hash_key = str(hash_key)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000153 content_url = base_url.rstrip('/') + '/content/'
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000154 if len(content) > MIN_SIZE_FOR_DIRECT_BLOBSTORE:
maruel@chromium.orgdc359e62013-03-14 13:08:55 +0000155 url = '%sgenerate_blobstore_url/%s/%s' % (
156 content_url, self.namespace, hash_key)
maruel@chromium.orge82112e2013-04-24 14:41:55 +0000157 # self._token is stored already quoted but it is unnecessary here, and
158 # only here.
159 data = [('token', urllib.unquote(self._token))]
maruel@chromium.orgdc359e62013-03-14 13:08:55 +0000160 upload_hash_content_to_blobstore(url, data, hash_key, content)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000161 else:
maruel@chromium.org034e3962013-03-13 13:34:25 +0000162 url = '%sstore/%s/%s?token=%s' % (
163 content_url, self.namespace, hash_key, self._token)
maruel@chromium.org000bb4d2013-04-26 17:53:27 +0000164 url_open(url, data=content, content_type='application/octet-stream')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000165 return upload_file
166
167
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000168def update_files_to_upload(query_url, queries, upload):
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000169 """Queries the server to see which files from this batch already exist there.
170
171 Arguments:
172 queries: The hash files to potential upload to the server.
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000173 upload: Any new files that need to be upload are sent to this function.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000174 """
175 body = ''.join(
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000176 (binascii.unhexlify(meta_data['h']) for (_, meta_data) in queries))
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000177 assert (len(body) % 20) == 0, repr(body)
178
maruel@chromium.orgef333122013-03-12 20:36:40 +0000179 response = url_open(
maruel@chromium.org000bb4d2013-04-26 17:53:27 +0000180 query_url, data=body, content_type='application/octet-stream').read()
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000181 if len(queries) != len(response):
182 raise run_isolated.MappingError(
183 'Got an incorrect number of responses from the server. Expected %d, '
184 'but got %d' % (len(queries), len(response)))
185
186 hit = 0
187 for i in range(len(response)):
188 if response[i] == chr(0):
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000189 upload(queries[i])
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000190 else:
191 hit += 1
192 logging.info('Queried %d files, %d cache hit', len(queries), hit)
193
194
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000195def compression_level(filename):
196 """Given a filename calculates the ideal compression level to use."""
197 file_ext = os.path.splitext(filename)[1].lower()
198 # TODO(csharp): Profile to find what compression level works best.
199 return 0 if file_ext in ALREADY_COMPRESSED_TYPES else 7
200
201
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000202def read_and_compress(filepath, level):
203 """Reads a file and returns its content gzip compressed."""
204 compressor = zlib.compressobj(level)
205 compressed_data = cStringIO.StringIO()
206 with open(filepath, 'rb') as f:
207 while True:
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000208 chunk = f.read(run_isolated.ZIPPED_FILE_CHUNK)
209 if not chunk:
210 break
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000211 compressed_data.write(compressor.compress(chunk))
212 compressed_data.write(compressor.flush(zlib.Z_FINISH))
213 value = compressed_data.getvalue()
214 compressed_data.close()
215 return value
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000216
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000217
218def zip_and_trigger_upload(infile, metadata, upload_function):
219 # TODO(csharp): Fix crbug.com/150823 and enable the touched logic again.
220 # if not metadata['T']:
221 compressed_data = read_and_compress(infile, compression_level(infile))
222 priority = (
223 run_isolated.Remote.HIGH if metadata.get('priority', '1') == '0'
224 else run_isolated.Remote.MED)
225 return upload_function(priority, compressed_data, metadata['h'], None)
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000226
227
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000228def process_items(contains_hash_url, infiles, zip_and_upload):
229 """Generates the list of files that need to be uploaded and send them to
230 zip_and_upload.
231
232 Some may already be on the server.
233 """
234 next_queries = []
csharp@chromium.org90c45812013-01-23 14:27:21 +0000235 items = ((k, v) for k, v in infiles.iteritems() if 's' in v)
236 for relfile, metadata in sorted(items, key=lambda x: -x[1]['s']):
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000237 next_queries.append((relfile, metadata))
238 if len(next_queries) == ITEMS_PER_CONTAINS_QUERY:
239 update_files_to_upload(contains_hash_url, next_queries, zip_and_upload)
240 next_queries = []
241 if next_queries:
242 update_files_to_upload(contains_hash_url, next_queries, zip_and_upload)
243
244
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000245def upload_sha1_tree(base_url, indir, infiles, namespace):
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000246 """Uploads the given tree to the given url.
247
248 Arguments:
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000249 base_url: The base url, it is assume that |base_url|/has/ can be used to
250 query if an element was already uploaded, and |base_url|/store/
251 can be used to upload a new element.
252 indir: Root directory the infiles are based in.
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000253 infiles: dict of files to upload files from |indir| to |base_url|.
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000254 namespace: The namespace to use on the server.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000255 """
256 logging.info('upload tree(base_url=%s, indir=%s, files=%d)' %
257 (base_url, indir, len(infiles)))
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000258 assert base_url.startswith('http'), base_url
259 base_url = base_url.rstrip('/')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000260
maruel@chromium.org034e3962013-03-13 13:34:25 +0000261 # TODO(maruel): Make this request much earlier asynchronously while the files
262 # are being enumerated.
maruel@chromium.orge82112e2013-04-24 14:41:55 +0000263 token = urllib.quote(url_open(base_url + '/content/get_token').read())
maruel@chromium.org034e3962013-03-13 13:34:25 +0000264
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000265 # Create a pool of workers to zip and upload any files missing from
266 # the server.
maruel@chromium.org6b0c9ec2013-01-18 00:34:31 +0000267 num_threads = run_test_cases.num_processors()
268 zipping_pool = run_isolated.ThreadPool(num_threads, num_threads, 0)
maruel@chromium.org034e3962013-03-13 13:34:25 +0000269 remote_uploader = UploadRemote(namespace, base_url, token)
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000270
271 # Starts the zip and upload process for a given query. The query is assumed
272 # to be in the format (relfile, metadata).
csharp@chromium.org20a888c2013-01-15 15:06:55 +0000273 uploaded = []
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000274 def zip_and_upload(query):
275 relfile, metadata = query
276 infile = os.path.join(indir, relfile)
maruel@chromium.org831958f2013-01-22 15:01:46 +0000277 zipping_pool.add_task(0, zip_and_trigger_upload, infile, metadata,
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000278 remote_uploader.add_item)
csharp@chromium.org20a888c2013-01-15 15:06:55 +0000279 uploaded.append(query)
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000280
maruel@chromium.org034e3962013-03-13 13:34:25 +0000281 contains_hash_url = '%s/content/contains/%s?token=%s' % (
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000282 base_url, namespace, token)
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000283 process_items(contains_hash_url, infiles, zip_and_upload)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000284
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000285 logging.info('Waiting for all files to finish zipping')
286 zipping_pool.join()
287 logging.info('All files zipped.')
288
289 logging.info('Waiting for all files to finish uploading')
maruel@chromium.org13eca0b2013-01-22 16:42:21 +0000290 # Will raise if any exception occurred.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000291 remote_uploader.join()
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000292 logging.info('All files are uploaded')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000293
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000294 total = len(infiles)
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000295 total_size = sum(metadata.get('s', 0) for metadata in infiles.itervalues())
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000296 logging.info(
297 'Total: %6d, %9.1fkb',
298 total,
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000299 sum(m.get('s', 0) for m in infiles.itervalues()) / 1024.)
csharp@chromium.org20a888c2013-01-15 15:06:55 +0000300 cache_hit = set(infiles.iterkeys()) - set(x[0] for x in uploaded)
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000301 cache_hit_size = sum(infiles[i].get('s', 0) for i in cache_hit)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000302 logging.info(
303 'cache hit: %6d, %9.1fkb, %6.2f%% files, %6.2f%% size',
304 len(cache_hit),
305 cache_hit_size / 1024.,
306 len(cache_hit) * 100. / total,
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000307 cache_hit_size * 100. / total_size if total_size else 0)
csharp@chromium.org20a888c2013-01-15 15:06:55 +0000308 cache_miss = uploaded
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000309 cache_miss_size = sum(infiles[i[0]].get('s', 0) for i in cache_miss)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000310 logging.info(
311 'cache miss: %6d, %9.1fkb, %6.2f%% files, %6.2f%% size',
312 len(cache_miss),
313 cache_miss_size / 1024.,
314 len(cache_miss) * 100. / total,
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000315 cache_miss_size * 100. / total_size if total_size else 0)
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000316 return 0
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000317
318
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000319def main(args):
maruel@chromium.org46e61cc2013-03-25 19:55:34 +0000320 run_isolated.disable_buffering()
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000321 parser = optparse.OptionParser(
322 usage='%prog [options] <file1..fileN> or - to read from stdin',
323 description=sys.modules[__name__].__doc__)
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000324 parser.add_option('-r', '--remote', help='Remote server to archive to')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000325 parser.add_option(
326 '-v', '--verbose',
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000327 action='count', default=0,
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000328 help='Use multiple times to increase verbosity')
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000329 parser.add_option('--namespace', default='default-gzip',
330 help='The namespace to use on the server.')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000331
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000332 options, files = parser.parse_args(args)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000333
334 levels = [logging.ERROR, logging.INFO, logging.DEBUG]
335 logging.basicConfig(
336 level=levels[min(len(levels)-1, options.verbose)],
337 format='%(levelname)5s %(module)15s(%(lineno)3d): %(message)s')
338 if files == ['-']:
339 files = sys.stdin.readlines()
340
341 if not files:
342 parser.error('Nothing to upload')
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000343 if not options.remote:
344 parser.error('Nowhere to send. Please specify --remote')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000345
346 # Load the necessary metadata. This is going to be rewritten eventually to be
347 # more efficient.
348 infiles = dict(
349 (
350 f,
351 {
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000352 's': os.stat(f).st_size,
maruel@chromium.org037758d2012-12-10 17:59:46 +0000353 'h': sha1_file(f),
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000354 }
355 )
356 for f in files)
357
358 with run_isolated.Profiler('Archive'):
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000359 return upload_sha1_tree(
360 base_url=options.remote,
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000361 indir=os.getcwd(),
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000362 infiles=infiles,
363 namespace=options.namespace)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000364
365
366if __name__ == '__main__':
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000367 sys.exit(main(sys.argv[1:]))