blob: 1bb9fca7f4f6b11af69207876dc00e2a79c6c0ce [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.orgfb78d432013-08-28 21:22:40 +00008__version__ = '0.1'
9
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000010import binascii
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +000011import cStringIO
maruel@chromium.orgc2bfef42013-08-30 21:46:26 +000012import functools
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000013import hashlib
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +000014import itertools
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000015import logging
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000016import os
17import sys
18import time
maruel@chromium.orge82112e2013-04-24 14:41:55 +000019import urllib
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +000020import zlib
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000021
maruel@chromium.orgfb78d432013-08-28 21:22:40 +000022from third_party import colorama
23from third_party.depot_tools import fix_encoding
24from third_party.depot_tools import subcommand
25
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000026import run_isolated
vadimsh@chromium.orga4326472013-08-24 02:05:41 +000027
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000028from utils import net
vadimsh@chromium.orgb074b162013-08-22 17:55:46 +000029from utils import threading_utils
vadimsh@chromium.orga4326472013-08-24 02:05:41 +000030from utils import tools
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000031
32
maruel@chromium.orgfb78d432013-08-28 21:22:40 +000033# Default server.
34# TODO(maruel): Chromium-specific.
35ISOLATE_SERVER = 'https://isolateserver-dev.appspot.com/'
36
37
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000038# The minimum size of files to upload directly to the blobstore.
maruel@chromium.orgaef29f82012-12-12 15:00:42 +000039MIN_SIZE_FOR_DIRECT_BLOBSTORE = 20 * 1024
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000040
vadimsh@chromium.orgeea52422013-08-21 19:35:54 +000041# The number of files to check the isolate server per /contains query.
42# All files are sorted by likelihood of a change in the file content
43# (currently file size is used to estimate this: larger the file -> larger the
44# possibility it has changed). Then first ITEMS_PER_CONTAINS_QUERIES[0] files
45# are taken and send to '/contains', then next ITEMS_PER_CONTAINS_QUERIES[1],
46# and so on. Numbers here is a trade-off; the more per request, the lower the
47# effect of HTTP round trip latency and TCP-level chattiness. On the other hand,
48# larger values cause longer lookups, increasing the initial latency to start
49# uploading, which is especially an issue for large files. This value is
50# optimized for the "few thousands files to look up with minimal number of large
51# files missing" case.
52ITEMS_PER_CONTAINS_QUERIES = [20, 20, 50, 50, 50, 100]
csharp@chromium.org07fa7592013-01-11 18:19:30 +000053
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +000054# A list of already compressed extension types that should not receive any
55# compression before being uploaded.
56ALREADY_COMPRESSED_TYPES = [
57 '7z', 'avi', 'cur', 'gif', 'h264', 'jar', 'jpeg', 'jpg', 'pdf', 'png',
58 'wav', 'zip'
59]
60
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000061
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +000062def randomness():
63 """Generates low-entropy randomness for MIME encoding.
64
65 Exists so it can be mocked out in unit tests.
66 """
67 return str(time.time())
68
69
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000070def encode_multipart_formdata(fields, files,
71 mime_mapper=lambda _: 'application/octet-stream'):
72 """Encodes a Multipart form data object.
73
74 Args:
75 fields: a sequence (name, value) elements for
76 regular form fields.
77 files: a sequence of (name, filename, value) elements for data to be
78 uploaded as files.
79 mime_mapper: function to return the mime type from the filename.
80 Returns:
81 content_type: for httplib.HTTP instance
82 body: for httplib.HTTP instance
83 """
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +000084 boundary = hashlib.md5(randomness()).hexdigest()
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000085 body_list = []
86 for (key, value) in fields:
87 if isinstance(key, unicode):
88 value = key.encode('utf-8')
89 if isinstance(value, unicode):
90 value = value.encode('utf-8')
91 body_list.append('--' + boundary)
92 body_list.append('Content-Disposition: form-data; name="%s"' % key)
93 body_list.append('')
94 body_list.append(value)
95 body_list.append('--' + boundary)
96 body_list.append('')
97 for (key, filename, value) in files:
98 if isinstance(key, unicode):
99 value = key.encode('utf-8')
100 if isinstance(filename, unicode):
101 value = filename.encode('utf-8')
102 if isinstance(value, unicode):
103 value = value.encode('utf-8')
104 body_list.append('--' + boundary)
105 body_list.append('Content-Disposition: form-data; name="%s"; '
106 'filename="%s"' % (key, filename))
107 body_list.append('Content-Type: %s' % mime_mapper(filename))
108 body_list.append('')
109 body_list.append(value)
110 body_list.append('--' + boundary)
111 body_list.append('')
112 if body_list:
113 body_list[-2] += '--'
114 body = '\r\n'.join(body_list)
115 content_type = 'multipart/form-data; boundary=%s' % boundary
116 return content_type, body
117
118
maruel@chromium.org037758d2012-12-10 17:59:46 +0000119def sha1_file(filepath):
120 """Calculates the SHA-1 of a file without reading it all in memory at once."""
121 digest = hashlib.sha1()
122 with open(filepath, 'rb') as f:
123 while True:
124 # Read in 1mb chunks.
125 chunk = f.read(1024*1024)
126 if not chunk:
127 break
128 digest.update(chunk)
129 return digest.hexdigest()
130
131
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000132def url_read(url, **kwargs):
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000133 result = net.url_read(url, **kwargs)
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000134 if result is None:
maruel@chromium.orgef333122013-03-12 20:36:40 +0000135 # If we get no response from the server, assume it is down and raise an
136 # exception.
137 raise run_isolated.MappingError('Unable to connect to server %s' % url)
138 return result
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000139
140
maruel@chromium.orgdc359e62013-03-14 13:08:55 +0000141def upload_hash_content_to_blobstore(
142 generate_upload_url, data, hash_key, content):
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000143 """Uploads the given hash contents directly to the blobstore via a generated
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000144 url.
145
146 Arguments:
147 generate_upload_url: The url to get the new upload url from.
maruel@chromium.orgdc359e62013-03-14 13:08:55 +0000148 data: extra POST data.
149 hash_key: sha1 of the uncompressed version of content.
150 content: The contents to upload. Must fit in memory for now.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000151 """
152 logging.debug('Generating url to directly upload file to blobstore')
maruel@chromium.org92a3d2e2012-12-20 16:22:29 +0000153 assert isinstance(hash_key, str), hash_key
154 assert isinstance(content, str), (hash_key, content)
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000155 # TODO(maruel): Support large files. This would require streaming support.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000156 content_type, body = encode_multipart_formdata(
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000157 data, [('content', hash_key, content)])
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000158 for attempt in xrange(net.URL_OPEN_MAX_ATTEMPTS):
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000159 # Retry HTTP 50x here.
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000160 upload_url = net.url_read(generate_upload_url, data=data)
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000161 if not upload_url:
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000162 raise run_isolated.MappingError(
163 'Unable to connect to server %s' % generate_upload_url)
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000164
165 # Do not retry this request on HTTP 50x. Regenerate an upload url each time
166 # since uploading "consumes" the upload url.
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000167 result = net.url_read(
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000168 upload_url, data=body, content_type=content_type, retry_50x=False)
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000169 if result is not None:
170 return result
vadimsh@chromium.org6b706212013-08-28 15:03:46 +0000171 if attempt != net.URL_OPEN_MAX_ATTEMPTS - 1:
172 net.HttpService.sleep_before_retry(attempt, None)
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000173 raise run_isolated.MappingError(
174 'Unable to connect to server %s' % generate_upload_url)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000175
176
maruel@chromium.orgc2bfef42013-08-30 21:46:26 +0000177def upload_file(base_url, namespace, content, hash_key, token):
178 # TODO(maruel): Detect failures.
179 hash_key = str(hash_key)
180 content_url = base_url.rstrip('/') + '/content/'
181 if len(content) > MIN_SIZE_FOR_DIRECT_BLOBSTORE:
182 url = '%sgenerate_blobstore_url/%s/%s' % (
183 content_url, namespace, hash_key)
184 # token is guaranteed to be already quoted but it is unnecessary here, and
185 # only here.
186 data = [('token', urllib.unquote(token))]
187 return upload_hash_content_to_blobstore(url, data, hash_key, content)
188 else:
189 url = '%sstore/%s/%s?token=%s' % (
190 content_url, namespace, hash_key, token)
191 return url_read(url, data=content, content_type='application/octet-stream')
192
193
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000194class UploadRemote(run_isolated.Remote):
maruel@chromium.org034e3962013-03-13 13:34:25 +0000195 def __init__(self, namespace, base_url, token):
maruel@chromium.org21243ce2012-12-20 17:43:00 +0000196 self.namespace = str(namespace)
maruel@chromium.org034e3962013-03-13 13:34:25 +0000197 self._token = token
198 super(UploadRemote, self).__init__(base_url)
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000199
200 def get_file_handler(self, base_url):
maruel@chromium.org21243ce2012-12-20 17:43:00 +0000201 base_url = str(base_url)
maruel@chromium.orgc2bfef42013-08-30 21:46:26 +0000202 return functools.partial(
203 upload_file, base_url, self.namespace, token=self._token)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000204
205
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000206def check_files_exist_on_server(query_url, queries):
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000207 """Queries the server to see which files from this batch already exist there.
208
209 Arguments:
210 queries: The hash files to potential upload to the server.
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000211 Returns:
212 missing_files: list of files that are missing on the server.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000213 """
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000214 logging.info('Checking existence of %d files...', len(queries))
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000215 body = ''.join(
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000216 (binascii.unhexlify(meta_data['h']) for (_, meta_data) in queries))
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000217 assert (len(body) % 20) == 0, repr(body)
218
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000219 response = url_read(
220 query_url, data=body, content_type='application/octet-stream')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000221 if len(queries) != len(response):
222 raise run_isolated.MappingError(
223 'Got an incorrect number of responses from the server. Expected %d, '
224 'but got %d' % (len(queries), len(response)))
225
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000226 missing_files = [
227 queries[i] for i, flag in enumerate(response) if flag == chr(0)
228 ]
229 logging.info('Queried %d files, %d cache hit',
230 len(queries), len(queries) - len(missing_files))
231 return missing_files
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000232
233
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000234def compression_level(filename):
235 """Given a filename calculates the ideal compression level to use."""
236 file_ext = os.path.splitext(filename)[1].lower()
237 # TODO(csharp): Profile to find what compression level works best.
238 return 0 if file_ext in ALREADY_COMPRESSED_TYPES else 7
239
240
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000241def read_and_compress(filepath, level):
242 """Reads a file and returns its content gzip compressed."""
243 compressor = zlib.compressobj(level)
244 compressed_data = cStringIO.StringIO()
245 with open(filepath, 'rb') as f:
246 while True:
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000247 chunk = f.read(run_isolated.ZIPPED_FILE_CHUNK)
248 if not chunk:
249 break
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000250 compressed_data.write(compressor.compress(chunk))
251 compressed_data.write(compressor.flush(zlib.Z_FINISH))
252 value = compressed_data.getvalue()
253 compressed_data.close()
254 return value
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000255
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000256
257def zip_and_trigger_upload(infile, metadata, upload_function):
258 # TODO(csharp): Fix crbug.com/150823 and enable the touched logic again.
259 # if not metadata['T']:
260 compressed_data = read_and_compress(infile, compression_level(infile))
261 priority = (
262 run_isolated.Remote.HIGH if metadata.get('priority', '1') == '0'
263 else run_isolated.Remote.MED)
264 return upload_function(priority, compressed_data, metadata['h'], None)
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000265
266
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000267def batch_files_for_check(infiles):
268 """Splits list of files to check for existence on the server into batches.
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000269
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000270 Each batch corresponds to a single 'exists?' query to the server.
271
272 Yields:
273 batches: list of batches, each batch is a list of files.
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000274 """
vadimsh@chromium.orgeea52422013-08-21 19:35:54 +0000275 batch_count = 0
276 batch_size_limit = ITEMS_PER_CONTAINS_QUERIES[0]
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000277 next_queries = []
csharp@chromium.org90c45812013-01-23 14:27:21 +0000278 items = ((k, v) for k, v in infiles.iteritems() if 's' in v)
279 for relfile, metadata in sorted(items, key=lambda x: -x[1]['s']):
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000280 next_queries.append((relfile, metadata))
vadimsh@chromium.orgeea52422013-08-21 19:35:54 +0000281 if len(next_queries) == batch_size_limit:
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000282 yield next_queries
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000283 next_queries = []
vadimsh@chromium.orgeea52422013-08-21 19:35:54 +0000284 batch_count += 1
285 batch_size_limit = ITEMS_PER_CONTAINS_QUERIES[
286 min(batch_count, len(ITEMS_PER_CONTAINS_QUERIES) - 1)]
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000287 if next_queries:
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000288 yield next_queries
289
290
291def get_files_to_upload(contains_hash_url, infiles):
292 """Yields files that are missing on the server."""
vadimsh@chromium.orgb074b162013-08-22 17:55:46 +0000293 with threading_utils.ThreadPool(1, 16, 0, prefix='get_files_to_upload') as tp:
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000294 for files in batch_files_for_check(infiles):
vadimsh@chromium.orgb074b162013-08-22 17:55:46 +0000295 tp.add_task(0, check_files_exist_on_server, contains_hash_url, files)
296 for missing_file in itertools.chain.from_iterable(tp.iter_results()):
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000297 yield missing_file
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000298
299
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000300def upload_sha1_tree(base_url, indir, infiles, namespace):
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000301 """Uploads the given tree to the given url.
302
303 Arguments:
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000304 base_url: The base url, it is assume that |base_url|/has/ can be used to
305 query if an element was already uploaded, and |base_url|/store/
306 can be used to upload a new element.
307 indir: Root directory the infiles are based in.
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000308 infiles: dict of files to upload files from |indir| to |base_url|.
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000309 namespace: The namespace to use on the server.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000310 """
311 logging.info('upload tree(base_url=%s, indir=%s, files=%d)' %
312 (base_url, indir, len(infiles)))
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000313 assert base_url.startswith('http'), base_url
314 base_url = base_url.rstrip('/')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000315
maruel@chromium.org034e3962013-03-13 13:34:25 +0000316 # TODO(maruel): Make this request much earlier asynchronously while the files
317 # are being enumerated.
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000318 token = urllib.quote(url_read(base_url + '/content/get_token'))
maruel@chromium.org034e3962013-03-13 13:34:25 +0000319
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000320 # Create a pool of workers to zip and upload any files missing from
321 # the server.
vadimsh@chromium.orgb074b162013-08-22 17:55:46 +0000322 num_threads = threading_utils.num_processors()
323 zipping_pool = threading_utils.ThreadPool(min(2, num_threads),
324 num_threads, 0, 'zip')
maruel@chromium.org034e3962013-03-13 13:34:25 +0000325 remote_uploader = UploadRemote(namespace, base_url, token)
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000326
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000327 # Starts the zip and upload process for files that are missing
328 # from the server.
329 contains_hash_url = '%s/content/contains/%s?token=%s' % (
330 base_url, namespace, token)
csharp@chromium.org20a888c2013-01-15 15:06:55 +0000331 uploaded = []
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000332 for relfile, metadata in get_files_to_upload(contains_hash_url, infiles):
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000333 infile = os.path.join(indir, relfile)
maruel@chromium.org831958f2013-01-22 15:01:46 +0000334 zipping_pool.add_task(0, zip_and_trigger_upload, infile, metadata,
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000335 remote_uploader.add_item)
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000336 uploaded.append((relfile, metadata))
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000337
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000338 logging.info('Waiting for all files to finish zipping')
339 zipping_pool.join()
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000340 zipping_pool.close()
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000341 logging.info('All files zipped.')
342
343 logging.info('Waiting for all files to finish uploading')
maruel@chromium.org13eca0b2013-01-22 16:42:21 +0000344 # Will raise if any exception occurred.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000345 remote_uploader.join()
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000346 remote_uploader.close()
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000347 logging.info('All files are uploaded')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000348
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000349 total = len(infiles)
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000350 total_size = sum(metadata.get('s', 0) for metadata in infiles.itervalues())
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000351 logging.info(
352 'Total: %6d, %9.1fkb',
353 total,
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000354 sum(m.get('s', 0) for m in infiles.itervalues()) / 1024.)
csharp@chromium.org20a888c2013-01-15 15:06:55 +0000355 cache_hit = set(infiles.iterkeys()) - set(x[0] for x in uploaded)
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000356 cache_hit_size = sum(infiles[i].get('s', 0) for i in cache_hit)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000357 logging.info(
358 'cache hit: %6d, %9.1fkb, %6.2f%% files, %6.2f%% size',
359 len(cache_hit),
360 cache_hit_size / 1024.,
361 len(cache_hit) * 100. / total,
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000362 cache_hit_size * 100. / total_size if total_size else 0)
csharp@chromium.org20a888c2013-01-15 15:06:55 +0000363 cache_miss = uploaded
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000364 cache_miss_size = sum(infiles[i[0]].get('s', 0) for i in cache_miss)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000365 logging.info(
366 'cache miss: %6d, %9.1fkb, %6.2f%% files, %6.2f%% size',
367 len(cache_miss),
368 cache_miss_size / 1024.,
369 len(cache_miss) * 100. / total,
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000370 cache_miss_size * 100. / total_size if total_size else 0)
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000371 return 0
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000372
373
maruel@chromium.orgfb78d432013-08-28 21:22:40 +0000374@subcommand.usage('<file1..fileN> or - to read from stdin')
375def CMDarchive(parser, args):
376 """Archives data to the server."""
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000377 options, files = parser.parse_args(args)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000378
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000379 if files == ['-']:
380 files = sys.stdin.readlines()
381
382 if not files:
383 parser.error('Nothing to upload')
maruel@chromium.orgfb78d432013-08-28 21:22:40 +0000384 if not options.isolate_server:
385 parser.error('Nowhere to send. Please specify --isolate-server')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000386
387 # Load the necessary metadata. This is going to be rewritten eventually to be
388 # more efficient.
389 infiles = dict(
390 (
391 f,
392 {
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000393 's': os.stat(f).st_size,
maruel@chromium.org037758d2012-12-10 17:59:46 +0000394 'h': sha1_file(f),
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000395 }
396 )
397 for f in files)
398
vadimsh@chromium.orga4326472013-08-24 02:05:41 +0000399 with tools.Profiler('Archive'):
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000400 return upload_sha1_tree(
maruel@chromium.orgfb78d432013-08-28 21:22:40 +0000401 base_url=options.isolate_server,
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000402 indir=os.getcwd(),
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000403 infiles=infiles,
404 namespace=options.namespace)
maruel@chromium.orgfb78d432013-08-28 21:22:40 +0000405 return 0
406
407
408def CMDdownload(parser, args):
409 """Download data from the server."""
410 _options, args = parser.parse_args(args)
411 parser.error('Sorry, it\'s not really supported.')
412 return 0
413
414
415class OptionParserIsolateServer(tools.OptionParserWithLogging):
416 def __init__(self, **kwargs):
417 tools.OptionParserWithLogging.__init__(self, **kwargs)
418 self.add_option(
419 '-I', '--isolate-server',
420 default=ISOLATE_SERVER,
421 metavar='URL',
422 help='Isolate server where data is stored. default: %default')
423 self.add_option(
424 '--namespace', default='default-gzip',
425 help='The namespace to use on the server.')
426
427 def parse_args(self, *args, **kwargs):
428 options, args = tools.OptionParserWithLogging.parse_args(
429 self, *args, **kwargs)
430 options.isolate_server = options.isolate_server.rstrip('/')
431 if not options.isolate_server:
432 self.error('--isolate-server is required.')
433 return options, args
434
435
436def main(args):
437 dispatcher = subcommand.CommandDispatcher(__name__)
438 try:
439 return dispatcher.execute(
440 OptionParserIsolateServer(version=__version__), args)
441 except (
442 run_isolated.MappingError,
443 run_isolated.ConfigError) as e:
444 sys.stderr.write('\nError: ')
445 sys.stderr.write(str(e))
446 sys.stderr.write('\n')
447 return 1
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000448
449
450if __name__ == '__main__':
maruel@chromium.orgfb78d432013-08-28 21:22:40 +0000451 fix_encoding.fix_encoding()
452 tools.disable_buffering()
453 colorama.init()
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000454 sys.exit(main(sys.argv[1:]))