blob: 3b79907240e9773d28cb919ccea6b9add9fe6579 [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
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +00009import cStringIO
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000010import hashlib
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +000011import itertools
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000012import logging
13import optparse
14import os
15import sys
16import time
maruel@chromium.orge82112e2013-04-24 14:41:55 +000017import urllib
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +000018import zlib
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000019
20import run_isolated
vadimsh@chromium.orgb074b162013-08-22 17:55:46 +000021from utils import threading_utils
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000022
23
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000024# The minimum size of files to upload directly to the blobstore.
maruel@chromium.orgaef29f82012-12-12 15:00:42 +000025MIN_SIZE_FOR_DIRECT_BLOBSTORE = 20 * 1024
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000026
vadimsh@chromium.orgeea52422013-08-21 19:35:54 +000027# The number of files to check the isolate server per /contains query.
28# All files are sorted by likelihood of a change in the file content
29# (currently file size is used to estimate this: larger the file -> larger the
30# possibility it has changed). Then first ITEMS_PER_CONTAINS_QUERIES[0] files
31# are taken and send to '/contains', then next ITEMS_PER_CONTAINS_QUERIES[1],
32# and so on. Numbers here is a trade-off; the more per request, the lower the
33# effect of HTTP round trip latency and TCP-level chattiness. On the other hand,
34# larger values cause longer lookups, increasing the initial latency to start
35# uploading, which is especially an issue for large files. This value is
36# optimized for the "few thousands files to look up with minimal number of large
37# files missing" case.
38ITEMS_PER_CONTAINS_QUERIES = [20, 20, 50, 50, 50, 100]
csharp@chromium.org07fa7592013-01-11 18:19:30 +000039
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +000040# A list of already compressed extension types that should not receive any
41# compression before being uploaded.
42ALREADY_COMPRESSED_TYPES = [
43 '7z', 'avi', 'cur', 'gif', 'h264', 'jar', 'jpeg', 'jpg', 'pdf', 'png',
44 'wav', 'zip'
45]
46
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000047
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +000048def randomness():
49 """Generates low-entropy randomness for MIME encoding.
50
51 Exists so it can be mocked out in unit tests.
52 """
53 return str(time.time())
54
55
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000056def encode_multipart_formdata(fields, files,
57 mime_mapper=lambda _: 'application/octet-stream'):
58 """Encodes a Multipart form data object.
59
60 Args:
61 fields: a sequence (name, value) elements for
62 regular form fields.
63 files: a sequence of (name, filename, value) elements for data to be
64 uploaded as files.
65 mime_mapper: function to return the mime type from the filename.
66 Returns:
67 content_type: for httplib.HTTP instance
68 body: for httplib.HTTP instance
69 """
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +000070 boundary = hashlib.md5(randomness()).hexdigest()
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000071 body_list = []
72 for (key, value) in fields:
73 if isinstance(key, unicode):
74 value = key.encode('utf-8')
75 if isinstance(value, unicode):
76 value = value.encode('utf-8')
77 body_list.append('--' + boundary)
78 body_list.append('Content-Disposition: form-data; name="%s"' % key)
79 body_list.append('')
80 body_list.append(value)
81 body_list.append('--' + boundary)
82 body_list.append('')
83 for (key, filename, value) in files:
84 if isinstance(key, unicode):
85 value = key.encode('utf-8')
86 if isinstance(filename, unicode):
87 value = filename.encode('utf-8')
88 if isinstance(value, unicode):
89 value = value.encode('utf-8')
90 body_list.append('--' + boundary)
91 body_list.append('Content-Disposition: form-data; name="%s"; '
92 'filename="%s"' % (key, filename))
93 body_list.append('Content-Type: %s' % mime_mapper(filename))
94 body_list.append('')
95 body_list.append(value)
96 body_list.append('--' + boundary)
97 body_list.append('')
98 if body_list:
99 body_list[-2] += '--'
100 body = '\r\n'.join(body_list)
101 content_type = 'multipart/form-data; boundary=%s' % boundary
102 return content_type, body
103
104
maruel@chromium.org037758d2012-12-10 17:59:46 +0000105def sha1_file(filepath):
106 """Calculates the SHA-1 of a file without reading it all in memory at once."""
107 digest = hashlib.sha1()
108 with open(filepath, 'rb') as f:
109 while True:
110 # Read in 1mb chunks.
111 chunk = f.read(1024*1024)
112 if not chunk:
113 break
114 digest.update(chunk)
115 return digest.hexdigest()
116
117
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000118def url_read(url, **kwargs):
119 result = run_isolated.url_read(url, **kwargs)
120 if result is None:
maruel@chromium.orgef333122013-03-12 20:36:40 +0000121 # If we get no response from the server, assume it is down and raise an
122 # exception.
123 raise run_isolated.MappingError('Unable to connect to server %s' % url)
124 return result
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000125
126
maruel@chromium.orgdc359e62013-03-14 13:08:55 +0000127def upload_hash_content_to_blobstore(
128 generate_upload_url, data, hash_key, content):
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000129 """Uploads the given hash contents directly to the blobstore via a generated
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000130 url.
131
132 Arguments:
133 generate_upload_url: The url to get the new upload url from.
maruel@chromium.orgdc359e62013-03-14 13:08:55 +0000134 data: extra POST data.
135 hash_key: sha1 of the uncompressed version of content.
136 content: The contents to upload. Must fit in memory for now.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000137 """
138 logging.debug('Generating url to directly upload file to blobstore')
maruel@chromium.org92a3d2e2012-12-20 16:22:29 +0000139 assert isinstance(hash_key, str), hash_key
140 assert isinstance(content, str), (hash_key, content)
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000141 # TODO(maruel): Support large files. This would require streaming support.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000142 content_type, body = encode_multipart_formdata(
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000143 data, [('content', hash_key, content)])
maruel@chromium.org2b2139a2013-04-30 20:14:58 +0000144 for attempt in xrange(run_isolated.URL_OPEN_MAX_ATTEMPTS):
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000145 # Retry HTTP 50x here.
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000146 upload_url = run_isolated.url_read(generate_upload_url, data=data)
147 if not upload_url:
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000148 raise run_isolated.MappingError(
149 'Unable to connect to server %s' % generate_upload_url)
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000150
151 # Do not retry this request on HTTP 50x. Regenerate an upload url each time
152 # since uploading "consumes" the upload url.
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000153 result = run_isolated.url_read(
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000154 upload_url, data=body, content_type=content_type, retry_50x=False)
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000155 if result is not None:
156 return result
maruel@chromium.org2b2139a2013-04-30 20:14:58 +0000157 if attempt != run_isolated.URL_OPEN_MAX_ATTEMPTS - 1:
158 run_isolated.HttpService.sleep_before_retry(attempt, None)
maruel@chromium.orgd58bf5b2013-04-26 17:57:42 +0000159 raise run_isolated.MappingError(
160 'Unable to connect to server %s' % generate_upload_url)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000161
162
163class UploadRemote(run_isolated.Remote):
maruel@chromium.org034e3962013-03-13 13:34:25 +0000164 def __init__(self, namespace, base_url, token):
maruel@chromium.org21243ce2012-12-20 17:43:00 +0000165 self.namespace = str(namespace)
maruel@chromium.org034e3962013-03-13 13:34:25 +0000166 self._token = token
167 super(UploadRemote, self).__init__(base_url)
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000168
169 def get_file_handler(self, base_url):
maruel@chromium.org21243ce2012-12-20 17:43:00 +0000170 base_url = str(base_url)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000171 def upload_file(content, hash_key):
maruel@chromium.org034e3962013-03-13 13:34:25 +0000172 # TODO(maruel): Detect failures.
maruel@chromium.org21243ce2012-12-20 17:43:00 +0000173 hash_key = str(hash_key)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000174 content_url = base_url.rstrip('/') + '/content/'
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000175 if len(content) > MIN_SIZE_FOR_DIRECT_BLOBSTORE:
maruel@chromium.orgdc359e62013-03-14 13:08:55 +0000176 url = '%sgenerate_blobstore_url/%s/%s' % (
177 content_url, self.namespace, hash_key)
maruel@chromium.orge82112e2013-04-24 14:41:55 +0000178 # self._token is stored already quoted but it is unnecessary here, and
179 # only here.
180 data = [('token', urllib.unquote(self._token))]
maruel@chromium.orgdc359e62013-03-14 13:08:55 +0000181 upload_hash_content_to_blobstore(url, data, hash_key, content)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000182 else:
maruel@chromium.org034e3962013-03-13 13:34:25 +0000183 url = '%sstore/%s/%s?token=%s' % (
184 content_url, self.namespace, hash_key, self._token)
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000185 url_read(url, data=content, content_type='application/octet-stream')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000186 return upload_file
187
188
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000189def check_files_exist_on_server(query_url, queries):
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000190 """Queries the server to see which files from this batch already exist there.
191
192 Arguments:
193 queries: The hash files to potential upload to the server.
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000194 Returns:
195 missing_files: list of files that are missing on the server.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000196 """
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000197 logging.info('Checking existence of %d files...', len(queries))
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000198 body = ''.join(
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000199 (binascii.unhexlify(meta_data['h']) for (_, meta_data) in queries))
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000200 assert (len(body) % 20) == 0, repr(body)
201
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000202 response = url_read(
203 query_url, data=body, content_type='application/octet-stream')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000204 if len(queries) != len(response):
205 raise run_isolated.MappingError(
206 'Got an incorrect number of responses from the server. Expected %d, '
207 'but got %d' % (len(queries), len(response)))
208
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000209 missing_files = [
210 queries[i] for i, flag in enumerate(response) if flag == chr(0)
211 ]
212 logging.info('Queried %d files, %d cache hit',
213 len(queries), len(queries) - len(missing_files))
214 return missing_files
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000215
216
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000217def compression_level(filename):
218 """Given a filename calculates the ideal compression level to use."""
219 file_ext = os.path.splitext(filename)[1].lower()
220 # TODO(csharp): Profile to find what compression level works best.
221 return 0 if file_ext in ALREADY_COMPRESSED_TYPES else 7
222
223
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000224def read_and_compress(filepath, level):
225 """Reads a file and returns its content gzip compressed."""
226 compressor = zlib.compressobj(level)
227 compressed_data = cStringIO.StringIO()
228 with open(filepath, 'rb') as f:
229 while True:
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000230 chunk = f.read(run_isolated.ZIPPED_FILE_CHUNK)
231 if not chunk:
232 break
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000233 compressed_data.write(compressor.compress(chunk))
234 compressed_data.write(compressor.flush(zlib.Z_FINISH))
235 value = compressed_data.getvalue()
236 compressed_data.close()
237 return value
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000238
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000239
240def zip_and_trigger_upload(infile, metadata, upload_function):
241 # TODO(csharp): Fix crbug.com/150823 and enable the touched logic again.
242 # if not metadata['T']:
243 compressed_data = read_and_compress(infile, compression_level(infile))
244 priority = (
245 run_isolated.Remote.HIGH if metadata.get('priority', '1') == '0'
246 else run_isolated.Remote.MED)
247 return upload_function(priority, compressed_data, metadata['h'], None)
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000248
249
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000250def batch_files_for_check(infiles):
251 """Splits list of files to check for existence on the server into batches.
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000252
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000253 Each batch corresponds to a single 'exists?' query to the server.
254
255 Yields:
256 batches: list of batches, each batch is a list of files.
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000257 """
vadimsh@chromium.orgeea52422013-08-21 19:35:54 +0000258 batch_count = 0
259 batch_size_limit = ITEMS_PER_CONTAINS_QUERIES[0]
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000260 next_queries = []
csharp@chromium.org90c45812013-01-23 14:27:21 +0000261 items = ((k, v) for k, v in infiles.iteritems() if 's' in v)
262 for relfile, metadata in sorted(items, key=lambda x: -x[1]['s']):
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000263 next_queries.append((relfile, metadata))
vadimsh@chromium.orgeea52422013-08-21 19:35:54 +0000264 if len(next_queries) == batch_size_limit:
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000265 yield next_queries
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000266 next_queries = []
vadimsh@chromium.orgeea52422013-08-21 19:35:54 +0000267 batch_count += 1
268 batch_size_limit = ITEMS_PER_CONTAINS_QUERIES[
269 min(batch_count, len(ITEMS_PER_CONTAINS_QUERIES) - 1)]
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000270 if next_queries:
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000271 yield next_queries
272
273
274def get_files_to_upload(contains_hash_url, infiles):
275 """Yields files that are missing on the server."""
vadimsh@chromium.orgb074b162013-08-22 17:55:46 +0000276 with threading_utils.ThreadPool(1, 16, 0, prefix='get_files_to_upload') as tp:
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000277 for files in batch_files_for_check(infiles):
vadimsh@chromium.orgb074b162013-08-22 17:55:46 +0000278 tp.add_task(0, check_files_exist_on_server, contains_hash_url, files)
279 for missing_file in itertools.chain.from_iterable(tp.iter_results()):
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000280 yield missing_file
maruel@chromium.org35fc0c82013-01-17 15:14:14 +0000281
282
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000283def upload_sha1_tree(base_url, indir, infiles, namespace):
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000284 """Uploads the given tree to the given url.
285
286 Arguments:
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000287 base_url: The base url, it is assume that |base_url|/has/ can be used to
288 query if an element was already uploaded, and |base_url|/store/
289 can be used to upload a new element.
290 indir: Root directory the infiles are based in.
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000291 infiles: dict of files to upload files from |indir| to |base_url|.
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000292 namespace: The namespace to use on the server.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000293 """
294 logging.info('upload tree(base_url=%s, indir=%s, files=%d)' %
295 (base_url, indir, len(infiles)))
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000296 assert base_url.startswith('http'), base_url
297 base_url = base_url.rstrip('/')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000298
maruel@chromium.org034e3962013-03-13 13:34:25 +0000299 # TODO(maruel): Make this request much earlier asynchronously while the files
300 # are being enumerated.
vadimsh@chromium.org80f73002013-07-12 14:52:44 +0000301 token = urllib.quote(url_read(base_url + '/content/get_token'))
maruel@chromium.org034e3962013-03-13 13:34:25 +0000302
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000303 # Create a pool of workers to zip and upload any files missing from
304 # the server.
vadimsh@chromium.orgb074b162013-08-22 17:55:46 +0000305 num_threads = threading_utils.num_processors()
306 zipping_pool = threading_utils.ThreadPool(min(2, num_threads),
307 num_threads, 0, 'zip')
maruel@chromium.org034e3962013-03-13 13:34:25 +0000308 remote_uploader = UploadRemote(namespace, base_url, token)
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000309
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000310 # Starts the zip and upload process for files that are missing
311 # from the server.
312 contains_hash_url = '%s/content/contains/%s?token=%s' % (
313 base_url, namespace, token)
csharp@chromium.org20a888c2013-01-15 15:06:55 +0000314 uploaded = []
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000315 for relfile, metadata in get_files_to_upload(contains_hash_url, infiles):
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000316 infile = os.path.join(indir, relfile)
maruel@chromium.org831958f2013-01-22 15:01:46 +0000317 zipping_pool.add_task(0, zip_and_trigger_upload, infile, metadata,
csharp@chromium.org07fa7592013-01-11 18:19:30 +0000318 remote_uploader.add_item)
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000319 uploaded.append((relfile, metadata))
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000320
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000321 logging.info('Waiting for all files to finish zipping')
322 zipping_pool.join()
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000323 zipping_pool.close()
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000324 logging.info('All files zipped.')
325
326 logging.info('Waiting for all files to finish uploading')
maruel@chromium.org13eca0b2013-01-22 16:42:21 +0000327 # Will raise if any exception occurred.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000328 remote_uploader.join()
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000329 remote_uploader.close()
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000330 logging.info('All files are uploaded')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000331
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000332 total = len(infiles)
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000333 total_size = sum(metadata.get('s', 0) for metadata in infiles.itervalues())
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000334 logging.info(
335 'Total: %6d, %9.1fkb',
336 total,
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000337 sum(m.get('s', 0) for m in infiles.itervalues()) / 1024.)
csharp@chromium.org20a888c2013-01-15 15:06:55 +0000338 cache_hit = set(infiles.iterkeys()) - set(x[0] for x in uploaded)
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000339 cache_hit_size = sum(infiles[i].get('s', 0) for i in cache_hit)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000340 logging.info(
341 'cache hit: %6d, %9.1fkb, %6.2f%% files, %6.2f%% size',
342 len(cache_hit),
343 cache_hit_size / 1024.,
344 len(cache_hit) * 100. / total,
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000345 cache_hit_size * 100. / total_size if total_size else 0)
csharp@chromium.org20a888c2013-01-15 15:06:55 +0000346 cache_miss = uploaded
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000347 cache_miss_size = sum(infiles[i[0]].get('s', 0) for i in cache_miss)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000348 logging.info(
349 'cache miss: %6d, %9.1fkb, %6.2f%% files, %6.2f%% size',
350 len(cache_miss),
351 cache_miss_size / 1024.,
352 len(cache_miss) * 100. / total,
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000353 cache_miss_size * 100. / total_size if total_size else 0)
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000354 return 0
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000355
356
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000357def main(args):
maruel@chromium.org46e61cc2013-03-25 19:55:34 +0000358 run_isolated.disable_buffering()
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000359 parser = optparse.OptionParser(
360 usage='%prog [options] <file1..fileN> or - to read from stdin',
361 description=sys.modules[__name__].__doc__)
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000362 parser.add_option('-r', '--remote', help='Remote server to archive to')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000363 parser.add_option(
364 '-v', '--verbose',
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000365 action='count', default=0,
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000366 help='Use multiple times to increase verbosity')
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000367 parser.add_option('--namespace', default='default-gzip',
368 help='The namespace to use on the server.')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000369
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000370 options, files = parser.parse_args(args)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000371
372 levels = [logging.ERROR, logging.INFO, logging.DEBUG]
373 logging.basicConfig(
374 level=levels[min(len(levels)-1, options.verbose)],
vadimsh@chromium.org53f8d5a2013-06-19 13:03:55 +0000375 format='[%(threadName)s] %(asctime)s,%(msecs)03d %(levelname)5s'
376 ' %(module)15s(%(lineno)3d): %(message)s',
377 datefmt='%H:%M:%S')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000378 if files == ['-']:
379 files = sys.stdin.readlines()
380
381 if not files:
382 parser.error('Nothing to upload')
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000383 if not options.remote:
384 parser.error('Nowhere to send. Please specify --remote')
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000385
386 # Load the necessary metadata. This is going to be rewritten eventually to be
387 # more efficient.
388 infiles = dict(
389 (
390 f,
391 {
maruel@chromium.orge5c17132012-11-21 18:18:46 +0000392 's': os.stat(f).st_size,
maruel@chromium.org037758d2012-12-10 17:59:46 +0000393 'h': sha1_file(f),
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000394 }
395 )
396 for f in files)
397
398 with run_isolated.Profiler('Archive'):
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000399 return upload_sha1_tree(
400 base_url=options.remote,
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000401 indir=os.getcwd(),
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +0000402 infiles=infiles,
403 namespace=options.namespace)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000404
405
406if __name__ == '__main__':
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +0000407 sys.exit(main(sys.argv[1:]))