blob: 5e7a25c5f100ce40b4d1c4efa9fe117c315c3ace [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.org043b76d2013-09-12 16:15:13 +0000158 for _ in net.retry_loop(max_attempts=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
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000171 raise run_isolated.MappingError(
172 'Unable to connect to server %s' % generate_upload_url)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000173
174
maruel@chromium.orgc2bfef42013-08-30 21:46:26 +0000175def upload_file(base_url, namespace, content, hash_key, token):
176 # TODO(maruel): Detect failures.
177 hash_key = str(hash_key)
178 content_url = base_url.rstrip('/') + '/content/'
179 if len(content) > MIN_SIZE_FOR_DIRECT_BLOBSTORE:
180 url = '%sgenerate_blobstore_url/%s/%s' % (
181 content_url, namespace, hash_key)
182 # token is guaranteed to be already quoted but it is unnecessary here, and
183 # only here.
184 data = [('token', urllib.unquote(token))]
185 return upload_hash_content_to_blobstore(url, data, hash_key, content)
186 else:
187 url = '%sstore/%s/%s?token=%s' % (
188 content_url, namespace, hash_key, token)
189 return url_read(url, data=content, content_type='application/octet-stream')
190
191
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000192class UploadRemote(run_isolated.Remote):
maruel@chromium.org034e3962013-03-13 13:34:25 +0000193 def __init__(self, namespace, base_url, token):
maruel@chromium.org21243ce2012-12-20 17:43:00 +0000194 self.namespace = str(namespace)
maruel@chromium.org034e3962013-03-13 13:34:25 +0000195 self._token = token
196 super(UploadRemote, self).__init__(base_url)
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000197
198 def get_file_handler(self, base_url):
maruel@chromium.org21243ce2012-12-20 17:43:00 +0000199 base_url = str(base_url)
maruel@chromium.orgc2bfef42013-08-30 21:46:26 +0000200 return functools.partial(
201 upload_file, base_url, self.namespace, token=self._token)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000202
203
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000204def check_files_exist_on_server(query_url, queries):
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000205 """Queries the server to see which files from this batch already exist there.
206
207 Arguments:
208 queries: The hash files to potential upload to the server.
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000209 Returns:
210 missing_files: list of files that are missing on the server.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000211 """
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000212 logging.info('Checking existence of %d files...', len(queries))
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000213 body = ''.join(
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000214 (binascii.unhexlify(meta_data['h']) for (_, meta_data) in queries))
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000215 assert (len(body) % 20) == 0, repr(body)
216
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000217 response = url_read(
218 query_url, data=body, content_type='application/octet-stream')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000219 if len(queries) != len(response):
220 raise run_isolated.MappingError(
221 'Got an incorrect number of responses from the server. Expected %d, '
222 'but got %d' % (len(queries), len(response)))
223
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000224 missing_files = [
225 queries[i] for i, flag in enumerate(response) if flag == chr(0)
226 ]
227 logging.info('Queried %d files, %d cache hit',
228 len(queries), len(queries) - len(missing_files))
229 return missing_files
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000230
231
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000232def compression_level(filename):
233 """Given a filename calculates the ideal compression level to use."""
234 file_ext = os.path.splitext(filename)[1].lower()
235 # TODO(csharp): Profile to find what compression level works best.
236 return 0 if file_ext in ALREADY_COMPRESSED_TYPES else 7
237
238
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000239def read_and_compress(filepath, level):
240 """Reads a file and returns its content gzip compressed."""
241 compressor = zlib.compressobj(level)
242 compressed_data = cStringIO.StringIO()
243 with open(filepath, 'rb') as f:
244 while True:
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000245 chunk = f.read(run_isolated.ZIPPED_FILE_CHUNK)
246 if not chunk:
247 break
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000248 compressed_data.write(compressor.compress(chunk))
249 compressed_data.write(compressor.flush(zlib.Z_FINISH))
250 value = compressed_data.getvalue()
251 compressed_data.close()
252 return value
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000253
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000254
255def zip_and_trigger_upload(infile, metadata, upload_function):
256 # TODO(csharp): Fix crbug.com/150823 and enable the touched logic again.
257 # if not metadata['T']:
258 compressed_data = read_and_compress(infile, compression_level(infile))
259 priority = (
260 run_isolated.Remote.HIGH if metadata.get('priority', '1') == '0'
261 else run_isolated.Remote.MED)
262 return upload_function(priority, compressed_data, metadata['h'], None)
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000263
264
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000265def batch_files_for_check(infiles):
266 """Splits list of files to check for existence on the server into batches.
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000267
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000268 Each batch corresponds to a single 'exists?' query to the server.
269
270 Yields:
271 batches: list of batches, each batch is a list of files.
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000272 """
vadimsh@chromium.orgeea52422013-08-21 19:35:54 +0000273 batch_count = 0
274 batch_size_limit = ITEMS_PER_CONTAINS_QUERIES[0]
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000275 next_queries = []
csharp@chromium.org90c45812013-01-23 14:27:21 +0000276 items = ((k, v) for k, v in infiles.iteritems() if 's' in v)
277 for relfile, metadata in sorted(items, key=lambda x: -x[1]['s']):
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000278 next_queries.append((relfile, metadata))
vadimsh@chromium.orgeea52422013-08-21 19:35:54 +0000279 if len(next_queries) == batch_size_limit:
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000280 yield next_queries
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000281 next_queries = []
vadimsh@chromium.orgeea52422013-08-21 19:35:54 +0000282 batch_count += 1
283 batch_size_limit = ITEMS_PER_CONTAINS_QUERIES[
284 min(batch_count, len(ITEMS_PER_CONTAINS_QUERIES) - 1)]
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000285 if next_queries:
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000286 yield next_queries
287
288
289def get_files_to_upload(contains_hash_url, infiles):
290 """Yields files that are missing on the server."""
vadimsh@chromium.orgb074b162013-08-22 17:55:46 +0000291 with threading_utils.ThreadPool(1, 16, 0, prefix='get_files_to_upload') as tp:
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000292 for files in batch_files_for_check(infiles):
vadimsh@chromium.orgb074b162013-08-22 17:55:46 +0000293 tp.add_task(0, check_files_exist_on_server, contains_hash_url, files)
294 for missing_file in itertools.chain.from_iterable(tp.iter_results()):
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000295 yield missing_file
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000296
297
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000298def upload_sha1_tree(base_url, indir, infiles, namespace):
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000299 """Uploads the given tree to the given url.
300
301 Arguments:
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000302 base_url: The base url, it is assume that |base_url|/has/ can be used to
303 query if an element was already uploaded, and |base_url|/store/
304 can be used to upload a new element.
305 indir: Root directory the infiles are based in.
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000306 infiles: dict of files to upload files from |indir| to |base_url|.
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000307 namespace: The namespace to use on the server.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000308 """
309 logging.info('upload tree(base_url=%s, indir=%s, files=%d)' %
310 (base_url, indir, len(infiles)))
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000311 assert base_url.startswith('http'), base_url
312 base_url = base_url.rstrip('/')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000313
maruel@chromium.org034e3962013-03-13 13:34:25 +0000314 # TODO(maruel): Make this request much earlier asynchronously while the files
315 # are being enumerated.
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000316 token = urllib.quote(url_read(base_url + '/content/get_token'))
maruel@chromium.org034e3962013-03-13 13:34:25 +0000317
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000318 # Create a pool of workers to zip and upload any files missing from
319 # the server.
vadimsh@chromium.orgb074b162013-08-22 17:55:46 +0000320 num_threads = threading_utils.num_processors()
321 zipping_pool = threading_utils.ThreadPool(min(2, num_threads),
322 num_threads, 0, 'zip')
maruel@chromium.org034e3962013-03-13 13:34:25 +0000323 remote_uploader = UploadRemote(namespace, base_url, token)
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000324
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000325 # Starts the zip and upload process for files that are missing
326 # from the server.
327 contains_hash_url = '%s/content/contains/%s?token=%s' % (
328 base_url, namespace, token)
csharp@chromium.org20a888c2013-01-15 15:06:55 +0000329 uploaded = []
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000330 for relfile, metadata in get_files_to_upload(contains_hash_url, infiles):
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000331 infile = os.path.join(indir, relfile)
maruel@chromium.org831958f2013-01-22 15:01:46 +0000332 zipping_pool.add_task(0, zip_and_trigger_upload, infile, metadata,
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000333 remote_uploader.add_item)
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000334 uploaded.append((relfile, metadata))
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000335
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000336 logging.info('Waiting for all files to finish zipping')
337 zipping_pool.join()
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000338 zipping_pool.close()
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000339 logging.info('All files zipped.')
340
341 logging.info('Waiting for all files to finish uploading')
maruel@chromium.org13eca0b2013-01-22 16:42:21 +0000342 # Will raise if any exception occurred.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000343 remote_uploader.join()
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000344 remote_uploader.close()
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000345 logging.info('All files are uploaded')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000346
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000347 total = len(infiles)
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000348 total_size = sum(metadata.get('s', 0) for metadata in infiles.itervalues())
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000349 logging.info(
350 'Total: %6d, %9.1fkb',
351 total,
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000352 sum(m.get('s', 0) for m in infiles.itervalues()) / 1024.)
csharp@chromium.org20a888c2013-01-15 15:06:55 +0000353 cache_hit = set(infiles.iterkeys()) - set(x[0] for x in uploaded)
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000354 cache_hit_size = sum(infiles[i].get('s', 0) for i in cache_hit)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000355 logging.info(
356 'cache hit: %6d, %9.1fkb, %6.2f%% files, %6.2f%% size',
357 len(cache_hit),
358 cache_hit_size / 1024.,
359 len(cache_hit) * 100. / total,
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000360 cache_hit_size * 100. / total_size if total_size else 0)
csharp@chromium.org20a888c2013-01-15 15:06:55 +0000361 cache_miss = uploaded
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000362 cache_miss_size = sum(infiles[i[0]].get('s', 0) for i in cache_miss)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000363 logging.info(
364 'cache miss: %6d, %9.1fkb, %6.2f%% files, %6.2f%% size',
365 len(cache_miss),
366 cache_miss_size / 1024.,
367 len(cache_miss) * 100. / total,
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000368 cache_miss_size * 100. / total_size if total_size else 0)
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000369 return 0
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000370
371
maruel@chromium.orgfb78d432013-08-28 21:22:40 +0000372@subcommand.usage('<file1..fileN> or - to read from stdin')
373def CMDarchive(parser, args):
374 """Archives data to the server."""
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000375 options, files = parser.parse_args(args)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000376
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000377 if files == ['-']:
378 files = sys.stdin.readlines()
379
380 if not files:
381 parser.error('Nothing to upload')
maruel@chromium.orgfb78d432013-08-28 21:22:40 +0000382 if not options.isolate_server:
383 parser.error('Nowhere to send. Please specify --isolate-server')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000384
385 # Load the necessary metadata. This is going to be rewritten eventually to be
386 # more efficient.
387 infiles = dict(
388 (
389 f,
390 {
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000391 's': os.stat(f).st_size,
maruel@chromium.org037758d2012-12-10 17:59:46 +0000392 'h': sha1_file(f),
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000393 }
394 )
395 for f in files)
396
vadimsh@chromium.orga4326472013-08-24 02:05:41 +0000397 with tools.Profiler('Archive'):
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000398 return upload_sha1_tree(
maruel@chromium.orgfb78d432013-08-28 21:22:40 +0000399 base_url=options.isolate_server,
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000400 indir=os.getcwd(),
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000401 infiles=infiles,
402 namespace=options.namespace)
maruel@chromium.orgfb78d432013-08-28 21:22:40 +0000403 return 0
404
405
406def CMDdownload(parser, args):
407 """Download data from the server."""
408 _options, args = parser.parse_args(args)
409 parser.error('Sorry, it\'s not really supported.')
410 return 0
411
412
413class OptionParserIsolateServer(tools.OptionParserWithLogging):
414 def __init__(self, **kwargs):
415 tools.OptionParserWithLogging.__init__(self, **kwargs)
416 self.add_option(
417 '-I', '--isolate-server',
418 default=ISOLATE_SERVER,
419 metavar='URL',
420 help='Isolate server where data is stored. default: %default')
421 self.add_option(
422 '--namespace', default='default-gzip',
423 help='The namespace to use on the server.')
424
425 def parse_args(self, *args, **kwargs):
426 options, args = tools.OptionParserWithLogging.parse_args(
427 self, *args, **kwargs)
428 options.isolate_server = options.isolate_server.rstrip('/')
429 if not options.isolate_server:
430 self.error('--isolate-server is required.')
431 return options, args
432
433
434def main(args):
435 dispatcher = subcommand.CommandDispatcher(__name__)
436 try:
437 return dispatcher.execute(
438 OptionParserIsolateServer(version=__version__), args)
439 except (
440 run_isolated.MappingError,
441 run_isolated.ConfigError) as e:
442 sys.stderr.write('\nError: ')
443 sys.stderr.write(str(e))
444 sys.stderr.write('\n')
445 return 1
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000446
447
448if __name__ == '__main__':
maruel@chromium.orgfb78d432013-08-28 21:22:40 +0000449 fix_encoding.fix_encoding()
450 tools.disable_buffering()
451 colorama.init()
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000452 sys.exit(main(sys.argv[1:]))