blob: 552d72b9917cf9b2b3e7a0b822dd414b197da01d [file] [log] [blame]
maruel@chromium.orgc6f90062012-11-07 18:32:22 +00001#!/usr/bin/env python
maruel@chromium.orgfb78d432013-08-28 21:22:40 +00002# Copyright 2013 The Chromium Authors. All rights reserved.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +00003# 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
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +00008__version__ = '0.2'
maruel@chromium.orgfb78d432013-08-28 21:22:40 +00009
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000010import binascii
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +000011import cStringIO
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000012import hashlib
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +000013import itertools
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000014import logging
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000015import os
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +000016import random
17import re
18import shutil
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000019import sys
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +000020import threading
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000021import time
maruel@chromium.orge82112e2013-04-24 14:41:55 +000022import urllib
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +000023import zlib
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000024
maruel@chromium.orgfb78d432013-08-28 21:22:40 +000025from third_party import colorama
26from third_party.depot_tools import fix_encoding
27from third_party.depot_tools import subcommand
28
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000029from utils import net
vadimsh@chromium.orgb074b162013-08-22 17:55:46 +000030from utils import threading_utils
vadimsh@chromium.orga4326472013-08-24 02:05:41 +000031from utils import tools
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000032
33
maruel@chromium.orgfb78d432013-08-28 21:22:40 +000034# Default server.
35# TODO(maruel): Chromium-specific.
36ISOLATE_SERVER = 'https://isolateserver-dev.appspot.com/'
37
38
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000039# The minimum size of files to upload directly to the blobstore.
maruel@chromium.orgaef29f82012-12-12 15:00:42 +000040MIN_SIZE_FOR_DIRECT_BLOBSTORE = 20 * 1024
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000041
vadimsh@chromium.orgeea52422013-08-21 19:35:54 +000042# The number of files to check the isolate server per /contains query.
43# All files are sorted by likelihood of a change in the file content
44# (currently file size is used to estimate this: larger the file -> larger the
45# possibility it has changed). Then first ITEMS_PER_CONTAINS_QUERIES[0] files
46# are taken and send to '/contains', then next ITEMS_PER_CONTAINS_QUERIES[1],
47# and so on. Numbers here is a trade-off; the more per request, the lower the
48# effect of HTTP round trip latency and TCP-level chattiness. On the other hand,
49# larger values cause longer lookups, increasing the initial latency to start
50# uploading, which is especially an issue for large files. This value is
51# optimized for the "few thousands files to look up with minimal number of large
52# files missing" case.
53ITEMS_PER_CONTAINS_QUERIES = [20, 20, 50, 50, 50, 100]
csharp@chromium.org07fa7592013-01-11 18:19:30 +000054
maruel@chromium.org9958e4a2013-09-17 00:01:48 +000055
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +000056# A list of already compressed extension types that should not receive any
57# compression before being uploaded.
58ALREADY_COMPRESSED_TYPES = [
59 '7z', 'avi', 'cur', 'gif', 'h264', 'jar', 'jpeg', 'jpg', 'pdf', 'png',
60 'wav', 'zip'
61]
62
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000063
maruel@chromium.orgdedbf492013-09-12 20:42:11 +000064# The file size to be used when we don't know the correct file size,
65# generally used for .isolated files.
66UNKNOWN_FILE_SIZE = None
67
68
69# The size of each chunk to read when downloading and unzipping files.
70ZIPPED_FILE_CHUNK = 16 * 1024
71
72
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +000073# Read timeout in seconds for downloads from isolate storage. If there's no
74# response from the server within this timeout whole download will be aborted.
75DOWNLOAD_READ_TIMEOUT = 60
76
77
maruel@chromium.orgdedbf492013-09-12 20:42:11 +000078class ConfigError(ValueError):
79 """Generic failure to load a .isolated file."""
80 pass
81
82
83class MappingError(OSError):
84 """Failed to recreate the tree."""
85 pass
86
87
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +000088def randomness():
89 """Generates low-entropy randomness for MIME encoding.
90
91 Exists so it can be mocked out in unit tests.
92 """
93 return str(time.time())
94
95
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000096def encode_multipart_formdata(fields, files,
97 mime_mapper=lambda _: 'application/octet-stream'):
98 """Encodes a Multipart form data object.
99
100 Args:
101 fields: a sequence (name, value) elements for
102 regular form fields.
103 files: a sequence of (name, filename, value) elements for data to be
104 uploaded as files.
105 mime_mapper: function to return the mime type from the filename.
106 Returns:
107 content_type: for httplib.HTTP instance
108 body: for httplib.HTTP instance
109 """
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000110 boundary = hashlib.md5(randomness()).hexdigest()
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000111 body_list = []
112 for (key, value) in fields:
113 if isinstance(key, unicode):
114 value = key.encode('utf-8')
115 if isinstance(value, unicode):
116 value = value.encode('utf-8')
117 body_list.append('--' + boundary)
118 body_list.append('Content-Disposition: form-data; name="%s"' % key)
119 body_list.append('')
120 body_list.append(value)
121 body_list.append('--' + boundary)
122 body_list.append('')
123 for (key, filename, value) in files:
124 if isinstance(key, unicode):
125 value = key.encode('utf-8')
126 if isinstance(filename, unicode):
127 value = filename.encode('utf-8')
128 if isinstance(value, unicode):
129 value = value.encode('utf-8')
130 body_list.append('--' + boundary)
131 body_list.append('Content-Disposition: form-data; name="%s"; '
132 'filename="%s"' % (key, filename))
133 body_list.append('Content-Type: %s' % mime_mapper(filename))
134 body_list.append('')
135 body_list.append(value)
136 body_list.append('--' + boundary)
137 body_list.append('')
138 if body_list:
139 body_list[-2] += '--'
140 body = '\r\n'.join(body_list)
141 content_type = 'multipart/form-data; boundary=%s' % boundary
142 return content_type, body
143
144
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000145def is_valid_hash(value, algo):
146 """Returns if the value is a valid hash for the corresponding algorithm."""
147 size = 2 * algo().digest_size
148 return bool(re.match(r'^[a-fA-F0-9]{%d}$' % size, value))
149
150
151def hash_file(filepath, algo):
152 """Calculates the hash of a file without reading it all in memory at once.
153
154 |algo| should be one of hashlib hashing algorithm.
155 """
156 digest = algo()
maruel@chromium.org037758d2012-12-10 17:59:46 +0000157 with open(filepath, 'rb') as f:
158 while True:
159 # Read in 1mb chunks.
160 chunk = f.read(1024*1024)
161 if not chunk:
162 break
163 digest.update(chunk)
164 return digest.hexdigest()
165
166
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000167def file_write(filepath, content_generator):
168 """Writes file content as generated by content_generator.
169
170 Meant to be mocked out in unit tests.
171 """
172 filedir = os.path.dirname(filepath)
173 if not os.path.isdir(filedir):
174 os.makedirs(filedir)
175 with open(filepath, 'wb') as f:
176 for d in content_generator:
177 f.write(d)
178
179
maruel@chromium.orge45728d2013-09-16 23:23:22 +0000180def is_valid_file(filepath, size):
maruel@chromium.orgdedbf492013-09-12 20:42:11 +0000181 """Determines if the given files appears valid.
182
183 Currently it just checks the file's size.
184 """
185 if size == UNKNOWN_FILE_SIZE:
186 return True
187 actual_size = os.stat(filepath).st_size
188 if size != actual_size:
189 logging.warning(
190 'Found invalid item %s; %d != %d',
191 os.path.basename(filepath), actual_size, size)
192 return False
193 return True
194
195
maruel@chromium.orge45728d2013-09-16 23:23:22 +0000196def try_remove(filepath):
197 """Removes a file without crashing even if it doesn't exist."""
198 try:
199 os.remove(filepath)
200 except OSError:
201 pass
202
203
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000204def url_read(url, **kwargs):
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000205 result = net.url_read(url, **kwargs)
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000206 if result is None:
maruel@chromium.orgef333122013-03-12 20:36:40 +0000207 # If we get no response from the server, assume it is down and raise an
208 # exception.
maruel@chromium.orgdedbf492013-09-12 20:42:11 +0000209 raise MappingError('Unable to connect to server %s' % url)
maruel@chromium.orgef333122013-03-12 20:36:40 +0000210 return result
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000211
212
maruel@chromium.orgdc359e62013-03-14 13:08:55 +0000213def upload_hash_content_to_blobstore(
214 generate_upload_url, data, hash_key, content):
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000215 """Uploads the given hash contents directly to the blobstore via a generated
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000216 url.
217
218 Arguments:
219 generate_upload_url: The url to get the new upload url from.
maruel@chromium.orgdc359e62013-03-14 13:08:55 +0000220 data: extra POST data.
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000221 hash_key: hash of the uncompressed version of content.
maruel@chromium.orgdc359e62013-03-14 13:08:55 +0000222 content: The contents to upload. Must fit in memory for now.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000223 """
224 logging.debug('Generating url to directly upload file to blobstore')
maruel@chromium.org92a3d2e2012-12-20 16:22:29 +0000225 assert isinstance(hash_key, str), hash_key
226 assert isinstance(content, str), (hash_key, content)
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000227 # TODO(maruel): Support large files. This would require streaming support.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000228 content_type, body = encode_multipart_formdata(
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000229 data, [('content', hash_key, content)])
vadimsh@chromium.org043b76d2013-09-12 16:15:13 +0000230 for _ in net.retry_loop(max_attempts=net.URL_OPEN_MAX_ATTEMPTS):
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000231 # Retry HTTP 50x here.
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000232 upload_url = net.url_read(generate_upload_url, data=data)
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000233 if not upload_url:
maruel@chromium.orgdedbf492013-09-12 20:42:11 +0000234 raise MappingError(
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000235 'Unable to connect to server %s' % generate_upload_url)
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000236
237 # Do not retry this request on HTTP 50x. Regenerate an upload url each time
238 # since uploading "consumes" the upload url.
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000239 result = net.url_read(
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000240 upload_url, data=body, content_type=content_type, retry_50x=False)
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000241 if result is not None:
242 return result
maruel@chromium.orgdedbf492013-09-12 20:42:11 +0000243 raise MappingError(
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000244 'Unable to connect to server %s' % generate_upload_url)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000245
246
maruel@chromium.org3e42ce82013-09-12 18:36:59 +0000247class IsolateServer(object):
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000248 """Client class to download or upload to Isolate Server."""
maruel@chromium.org3e42ce82013-09-12 18:36:59 +0000249 def __init__(self, base_url, namespace):
250 assert base_url.startswith('http'), base_url
251 self.content_url = base_url.rstrip('/') + '/content/'
252 self.namespace = namespace
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000253 self._token = None
254 self._lock = threading.Lock()
255
256 @property
257 def token(self):
maruel@chromium.org3e42ce82013-09-12 18:36:59 +0000258 # TODO(maruel): Make this request much earlier asynchronously while the
259 # files are being enumerated.
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000260 with self._lock:
261 if not self._token:
262 self._token = urllib.quote(url_read(self.content_url + 'get_token'))
263 return self._token
264
maruel@chromium.orge45728d2013-09-16 23:23:22 +0000265 def fetch(self, item, size):
266 """Fetches an object and yields its content."""
267 zipped_url = '%sretrieve/%s/%s' % (self.content_url, self.namespace, item)
268 logging.debug('download_file(%s)', zipped_url)
269
270 # Because the app engine DB is only eventually consistent, retry 404 errors
271 # because the file might just not be visible yet (even though it has been
272 # uploaded).
273 connection = net.url_open(
274 zipped_url, retry_404=True, read_timeout=DOWNLOAD_READ_TIMEOUT)
275 if not connection:
276 raise IOError('Unable to open connection to %s' % zipped_url)
277
278 decompressor = zlib.decompressobj()
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000279 try:
maruel@chromium.orge45728d2013-09-16 23:23:22 +0000280 compressed_size = 0
281 decompressed_size = 0
282 while True:
283 chunk = connection.read(ZIPPED_FILE_CHUNK)
284 if not chunk:
285 break
286 compressed_size += len(chunk)
287 decompressed = decompressor.decompress(chunk)
288 decompressed_size += len(decompressed)
289 yield decompressed
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000290
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000291 # Ensure that all the data was properly decompressed.
292 uncompressed_data = decompressor.flush()
maruel@chromium.orge45728d2013-09-16 23:23:22 +0000293 if uncompressed_data:
294 raise IOError('Decompression failed')
295 if size != UNKNOWN_FILE_SIZE and decompressed_size != size:
296 raise IOError('File incorrect size after download of %s. Got %s and '
297 'expected %s' % (item, decompressed_size, size))
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000298 except zlib.error as e:
299 msg = 'Corrupted zlib for item %s. Processed %d of %s bytes.\n%s' % (
maruel@chromium.orge45728d2013-09-16 23:23:22 +0000300 item, compressed_size, connection.content_length, e)
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000301 logging.error(msg)
302
303 # Testing seems to show that if a few machines are trying to download
maruel@chromium.orge45728d2013-09-16 23:23:22 +0000304 # the same blob, they can cause each other to fail. So if we hit a zip
305 # error, this is the most likely cause (it only downloads some of the
306 # data). Randomly sleep for between 5 and 25 seconds to try and spread
307 # out the downloads.
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000308 sleep_duration = (random.random() * 20) + 5
309 time.sleep(sleep_duration)
310 raise IOError(msg)
maruel@chromium.orgc2bfef42013-08-30 21:46:26 +0000311
maruel@chromium.orge45728d2013-09-16 23:23:22 +0000312 def retrieve(self, item, dest, size):
313 """Fetches an object and save its content to |dest|."""
314 try:
315 file_write(dest, self.fetch(item, size))
316 except IOError as e:
317 # Remove unfinished download.
318 try_remove(dest)
319 logging.error('Failed to download %s at %s.\n%s', item, dest, e)
320 raise
321
322 def store(self, content, hash_key, _size):
maruel@chromium.org3e42ce82013-09-12 18:36:59 +0000323 # TODO(maruel): Detect failures.
324 hash_key = str(hash_key)
325 if len(content) > MIN_SIZE_FOR_DIRECT_BLOBSTORE:
326 url = '%sgenerate_blobstore_url/%s/%s' % (
327 self.content_url, self.namespace, hash_key)
328 # token is guaranteed to be already quoted but it is unnecessary here, and
329 # only here.
330 data = [('token', urllib.unquote(self.token))]
331 return upload_hash_content_to_blobstore(url, data, hash_key, content)
332 else:
333 url = '%sstore/%s/%s?token=%s' % (
334 self.content_url, self.namespace, hash_key, self.token)
335 return url_read(
336 url, data=content, content_type='application/octet-stream')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000337
338
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000339def check_files_exist_on_server(query_url, queries):
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000340 """Queries the server to see which files from this batch already exist there.
341
342 Arguments:
343 queries: The hash files to potential upload to the server.
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000344 Returns:
345 missing_files: list of files that are missing on the server.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000346 """
maruel@chromium.org3e42ce82013-09-12 18:36:59 +0000347 # TODO(maruel): Move inside IsolateServer.
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000348 logging.info('Checking existence of %d files...', len(queries))
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000349 body = ''.join(
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000350 (binascii.unhexlify(meta_data['h']) for (_, meta_data) in queries))
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000351 assert (len(body) % 20) == 0, repr(body)
352
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000353 response = url_read(
354 query_url, data=body, content_type='application/octet-stream')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000355 if len(queries) != len(response):
maruel@chromium.orgdedbf492013-09-12 20:42:11 +0000356 raise MappingError(
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000357 'Got an incorrect number of responses from the server. Expected %d, '
358 'but got %d' % (len(queries), len(response)))
359
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000360 missing_files = [
361 queries[i] for i, flag in enumerate(response) if flag == chr(0)
362 ]
363 logging.info('Queried %d files, %d cache hit',
364 len(queries), len(queries) - len(missing_files))
365 return missing_files
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000366
367
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000368class FileSystem(object):
369 """Fetches data from the file system.
370
371 The common use case is a NFS/CIFS file server that is mounted locally that is
372 used to fetch the file on a local partition.
373 """
374 def __init__(self, base_path):
375 self.base_path = base_path
376
maruel@chromium.orge45728d2013-09-16 23:23:22 +0000377 def fetch(self, item, size):
378 source = os.path.join(self.base_path, item)
379 if size != UNKNOWN_FILE_SIZE and not is_valid_file(source, size):
380 raise IOError('Invalid file %s' % item)
381 with open(source, 'rb') as f:
382 return [f.read()]
383
384 def retrieve(self, item, dest, size):
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000385 source = os.path.join(self.base_path, item)
386 if source == dest:
387 logging.info('Source and destination are the same, no action required')
388 return
389 logging.debug('copy_file(%s, %s)', source, dest)
maruel@chromium.orge45728d2013-09-16 23:23:22 +0000390 if size != UNKNOWN_FILE_SIZE and not is_valid_file(source, size):
391 raise IOError(
392 'Invalid file %s, %d != %d' % (item, os.stat(source).st_size, size))
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000393 shutil.copy(source, dest)
394
395 def store(self, content, hash_key):
396 raise NotImplementedError()
397
398
399def get_storage_api(file_or_url, namespace):
400 """Returns an object that implements .retrieve()."""
401 if re.match(r'^https?://.+$', file_or_url):
402 return IsolateServer(file_or_url, namespace)
403 else:
404 return FileSystem(file_or_url)
405
406
maruel@chromium.orgdedbf492013-09-12 20:42:11 +0000407class RemoteOperation(object):
408 """Priority based worker queue to operate on action items.
409
410 It execute a function with the given task items. It is specialized to download
411 files.
412
413 When the priority of items is equals, works in strict FIFO mode.
414 """
415 # Initial and maximum number of worker threads.
416 INITIAL_WORKERS = 2
417 MAX_WORKERS = 16
418 # Priorities.
419 LOW, MED, HIGH = (1<<8, 2<<8, 3<<8)
420 INTERNAL_PRIORITY_BITS = (1<<8) - 1
421 RETRIES = 5
422
423 def __init__(self, do_item):
424 # Function to fetch a remote object or upload to a remote location.
425 self._do_item = do_item
maruel@chromium.orgdedbf492013-09-12 20:42:11 +0000426 self._pool = threading_utils.ThreadPool(
427 self.INITIAL_WORKERS, self.MAX_WORKERS, 0, 'remote')
428
429 def join(self):
430 """Blocks until the queue is empty."""
431 return self._pool.join()
432
433 def close(self):
434 """Terminates all worker threads."""
435 self._pool.close()
436
437 def add_item(self, priority, obj, dest, size):
438 """Retrieves an object from the remote data store.
439
440 The smaller |priority| gets fetched first.
441
442 Thread-safe.
443 """
444 assert (priority & self.INTERNAL_PRIORITY_BITS) == 0
445 return self._add_item(priority, obj, dest, size)
446
maruel@chromium.orge45728d2013-09-16 23:23:22 +0000447 def get_one_result(self):
448 return self._pool.get_one_result()
449
maruel@chromium.orgdedbf492013-09-12 20:42:11 +0000450 def _add_item(self, priority, obj, dest, size):
451 assert isinstance(obj, basestring), obj
452 assert isinstance(dest, basestring), dest
453 assert size is None or isinstance(size, int), size
454 return self._pool.add_task(
455 priority, self._task_executer, priority, obj, dest, size)
456
maruel@chromium.orgdedbf492013-09-12 20:42:11 +0000457 def _task_executer(self, priority, obj, dest, size):
458 """Wraps self._do_item to trap and retry on IOError exceptions."""
459 try:
maruel@chromium.orge45728d2013-09-16 23:23:22 +0000460 self._do_item(obj, dest, size)
maruel@chromium.orgdedbf492013-09-12 20:42:11 +0000461 # TODO(maruel): Technically, we'd want to have an output queue to be a
462 # PriorityQueue.
463 return obj
maruel@chromium.orge45728d2013-09-16 23:23:22 +0000464 except IOError:
maruel@chromium.orgdedbf492013-09-12 20:42:11 +0000465 # Retry a few times, lowering the priority.
466 if (priority & self.INTERNAL_PRIORITY_BITS) < self.RETRIES:
467 self._add_item(priority + 1, obj, dest, size)
468 return
469 raise
470
471
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000472def compression_level(filename):
473 """Given a filename calculates the ideal compression level to use."""
474 file_ext = os.path.splitext(filename)[1].lower()
475 # TODO(csharp): Profile to find what compression level works best.
476 return 0 if file_ext in ALREADY_COMPRESSED_TYPES else 7
477
478
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000479def read_and_compress(filepath, level):
480 """Reads a file and returns its content gzip compressed."""
481 compressor = zlib.compressobj(level)
482 compressed_data = cStringIO.StringIO()
483 with open(filepath, 'rb') as f:
484 while True:
maruel@chromium.orgdedbf492013-09-12 20:42:11 +0000485 chunk = f.read(ZIPPED_FILE_CHUNK)
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000486 if not chunk:
487 break
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000488 compressed_data.write(compressor.compress(chunk))
489 compressed_data.write(compressor.flush(zlib.Z_FINISH))
490 value = compressed_data.getvalue()
491 compressed_data.close()
492 return value
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000493
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000494
495def zip_and_trigger_upload(infile, metadata, upload_function):
496 # TODO(csharp): Fix crbug.com/150823 and enable the touched logic again.
497 # if not metadata['T']:
498 compressed_data = read_and_compress(infile, compression_level(infile))
499 priority = (
maruel@chromium.orgdedbf492013-09-12 20:42:11 +0000500 RemoteOperation.HIGH if metadata.get('priority', '1') == '0'
501 else RemoteOperation.MED)
maruel@chromium.orge45728d2013-09-16 23:23:22 +0000502 return upload_function(
503 priority, compressed_data, metadata['h'], UNKNOWN_FILE_SIZE)
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000504
505
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000506def batch_files_for_check(infiles):
507 """Splits list of files to check for existence on the server into batches.
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000508
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000509 Each batch corresponds to a single 'exists?' query to the server.
510
511 Yields:
512 batches: list of batches, each batch is a list of files.
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000513 """
vadimsh@chromium.orgeea52422013-08-21 19:35:54 +0000514 batch_count = 0
515 batch_size_limit = ITEMS_PER_CONTAINS_QUERIES[0]
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000516 next_queries = []
csharp@chromium.org90c45812013-01-23 14:27:21 +0000517 items = ((k, v) for k, v in infiles.iteritems() if 's' in v)
518 for relfile, metadata in sorted(items, key=lambda x: -x[1]['s']):
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000519 next_queries.append((relfile, metadata))
vadimsh@chromium.orgeea52422013-08-21 19:35:54 +0000520 if len(next_queries) == batch_size_limit:
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000521 yield next_queries
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000522 next_queries = []
vadimsh@chromium.orgeea52422013-08-21 19:35:54 +0000523 batch_count += 1
524 batch_size_limit = ITEMS_PER_CONTAINS_QUERIES[
525 min(batch_count, len(ITEMS_PER_CONTAINS_QUERIES) - 1)]
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000526 if next_queries:
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000527 yield next_queries
528
529
530def get_files_to_upload(contains_hash_url, infiles):
531 """Yields files that are missing on the server."""
vadimsh@chromium.orgb074b162013-08-22 17:55:46 +0000532 with threading_utils.ThreadPool(1, 16, 0, prefix='get_files_to_upload') as tp:
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000533 for files in batch_files_for_check(infiles):
vadimsh@chromium.orgb074b162013-08-22 17:55:46 +0000534 tp.add_task(0, check_files_exist_on_server, contains_hash_url, files)
535 for missing_file in itertools.chain.from_iterable(tp.iter_results()):
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000536 yield missing_file
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000537
538
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000539def upload_tree(base_url, indir, infiles, namespace):
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000540 """Uploads the given tree to the given url.
541
542 Arguments:
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000543 base_url: The base url, it is assume that |base_url|/has/ can be used to
544 query if an element was already uploaded, and |base_url|/store/
545 can be used to upload a new element.
546 indir: Root directory the infiles are based in.
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000547 infiles: dict of files to upload files from |indir| to |base_url|.
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000548 namespace: The namespace to use on the server.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000549 """
550 logging.info('upload tree(base_url=%s, indir=%s, files=%d)' %
551 (base_url, indir, len(infiles)))
maruel@chromium.org034e3962013-03-13 13:34:25 +0000552
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000553 # Create a pool of workers to zip and upload any files missing from
554 # the server.
vadimsh@chromium.orgb074b162013-08-22 17:55:46 +0000555 num_threads = threading_utils.num_processors()
556 zipping_pool = threading_utils.ThreadPool(min(2, num_threads),
557 num_threads, 0, 'zip')
maruel@chromium.org3e42ce82013-09-12 18:36:59 +0000558 remote = IsolateServer(base_url, namespace)
maruel@chromium.orgdedbf492013-09-12 20:42:11 +0000559 remote_uploader = RemoteOperation(remote.store)
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000560
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000561 # Starts the zip and upload process for files that are missing
562 # from the server.
maruel@chromium.org3e42ce82013-09-12 18:36:59 +0000563 contains_hash_url = '%scontains/%s?token=%s' % (
564 remote.content_url, namespace, remote.token)
csharp@chromium.org20a888c2013-01-15 15:06:55 +0000565 uploaded = []
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000566 for relfile, metadata in get_files_to_upload(contains_hash_url, infiles):
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000567 infile = os.path.join(indir, relfile)
maruel@chromium.org831958f2013-01-22 15:01:46 +0000568 zipping_pool.add_task(0, zip_and_trigger_upload, infile, metadata,
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000569 remote_uploader.add_item)
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000570 uploaded.append((relfile, metadata))
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000571
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000572 logging.info('Waiting for all files to finish zipping')
573 zipping_pool.join()
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000574 zipping_pool.close()
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000575 logging.info('All files zipped.')
576
577 logging.info('Waiting for all files to finish uploading')
maruel@chromium.org13eca0b2013-01-22 16:42:21 +0000578 # Will raise if any exception occurred.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000579 remote_uploader.join()
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000580 remote_uploader.close()
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000581 logging.info('All files are uploaded')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000582
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000583 total = len(infiles)
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000584 total_size = sum(metadata.get('s', 0) for metadata in infiles.itervalues())
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000585 logging.info(
586 'Total: %6d, %9.1fkb',
587 total,
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000588 sum(m.get('s', 0) for m in infiles.itervalues()) / 1024.)
csharp@chromium.org20a888c2013-01-15 15:06:55 +0000589 cache_hit = set(infiles.iterkeys()) - set(x[0] for x in uploaded)
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000590 cache_hit_size = sum(infiles[i].get('s', 0) for i in cache_hit)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000591 logging.info(
592 'cache hit: %6d, %9.1fkb, %6.2f%% files, %6.2f%% size',
593 len(cache_hit),
594 cache_hit_size / 1024.,
595 len(cache_hit) * 100. / total,
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000596 cache_hit_size * 100. / total_size if total_size else 0)
csharp@chromium.org20a888c2013-01-15 15:06:55 +0000597 cache_miss = uploaded
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000598 cache_miss_size = sum(infiles[i[0]].get('s', 0) for i in cache_miss)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000599 logging.info(
600 'cache miss: %6d, %9.1fkb, %6.2f%% files, %6.2f%% size',
601 len(cache_miss),
602 cache_miss_size / 1024.,
603 len(cache_miss) * 100. / total,
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000604 cache_miss_size * 100. / total_size if total_size else 0)
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000605 return 0
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000606
607
maruel@chromium.orgfb78d432013-08-28 21:22:40 +0000608@subcommand.usage('<file1..fileN> or - to read from stdin')
609def CMDarchive(parser, args):
610 """Archives data to the server."""
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000611 options, files = parser.parse_args(args)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000612
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000613 if files == ['-']:
614 files = sys.stdin.readlines()
615
616 if not files:
617 parser.error('Nothing to upload')
maruel@chromium.orgfb78d432013-08-28 21:22:40 +0000618 if not options.isolate_server:
619 parser.error('Nowhere to send. Please specify --isolate-server')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000620
621 # Load the necessary metadata. This is going to be rewritten eventually to be
622 # more efficient.
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000623 algo = hashlib.sha1
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000624 infiles = dict(
625 (
626 f,
627 {
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000628 's': os.stat(f).st_size,
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000629 'h': hash_file(f, algo),
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000630 }
631 )
632 for f in files)
633
vadimsh@chromium.orga4326472013-08-24 02:05:41 +0000634 with tools.Profiler('Archive'):
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000635 ret = upload_tree(
maruel@chromium.orgfb78d432013-08-28 21:22:40 +0000636 base_url=options.isolate_server,
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000637 indir=os.getcwd(),
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000638 infiles=infiles,
639 namespace=options.namespace)
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000640 if not ret:
641 print '\n'.join('%s %s' % (infiles[f]['h'], f) for f in sorted(infiles))
642 return ret
maruel@chromium.orgfb78d432013-08-28 21:22:40 +0000643
644
645def CMDdownload(parser, args):
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000646 """Download data from the server.
647
648 It can download individual files.
649 """
650 parser.add_option(
651 '-f', '--file', metavar='HASH DEST', default=[], action='append', nargs=2,
652 help='hash and destination of a file, can be used multiple times')
653 parser.add_option(
654 '-t', '--target', metavar='DIR', default=os.getcwd(),
655 help='destination directory')
656 options, args = parser.parse_args(args)
657 if args:
658 parser.error('Unsupported arguments: %s' % args)
659 if not options.file:
660 parser.error('Use one of --file is required.')
661
662 options.target = os.path.abspath(options.target)
663 remote = IsolateServer(options.isolate_server, options.namespace)
664 for h, dest in options.file:
665 logging.info('%s: %s', h, dest)
maruel@chromium.orge45728d2013-09-16 23:23:22 +0000666 remote.retrieve(h, os.path.join(options.target, dest), UNKNOWN_FILE_SIZE)
maruel@chromium.orgfb78d432013-08-28 21:22:40 +0000667 return 0
668
669
670class OptionParserIsolateServer(tools.OptionParserWithLogging):
671 def __init__(self, **kwargs):
672 tools.OptionParserWithLogging.__init__(self, **kwargs)
673 self.add_option(
674 '-I', '--isolate-server',
675 default=ISOLATE_SERVER,
676 metavar='URL',
677 help='Isolate server where data is stored. default: %default')
678 self.add_option(
679 '--namespace', default='default-gzip',
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000680 help='The namespace to use on the server, default: %default')
maruel@chromium.orgfb78d432013-08-28 21:22:40 +0000681
682 def parse_args(self, *args, **kwargs):
683 options, args = tools.OptionParserWithLogging.parse_args(
684 self, *args, **kwargs)
685 options.isolate_server = options.isolate_server.rstrip('/')
686 if not options.isolate_server:
687 self.error('--isolate-server is required.')
688 return options, args
689
690
691def main(args):
692 dispatcher = subcommand.CommandDispatcher(__name__)
693 try:
694 return dispatcher.execute(
695 OptionParserIsolateServer(version=__version__), args)
maruel@chromium.orgdedbf492013-09-12 20:42:11 +0000696 except (ConfigError, MappingError) as e:
maruel@chromium.orgfb78d432013-08-28 21:22:40 +0000697 sys.stderr.write('\nError: ')
698 sys.stderr.write(str(e))
699 sys.stderr.write('\n')
700 return 1
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000701
702
703if __name__ == '__main__':
maruel@chromium.orgfb78d432013-08-28 21:22:40 +0000704 fix_encoding.fix_encoding()
705 tools.disable_buffering()
706 colorama.init()
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000707 sys.exit(main(sys.argv[1:]))