maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 1 | #!/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 | |
| 8 | import binascii |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 9 | import cStringIO |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 10 | import hashlib |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 11 | import itertools |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 12 | import logging |
| 13 | import optparse |
| 14 | import os |
| 15 | import sys |
| 16 | import time |
maruel@chromium.org | e82112e | 2013-04-24 14:41:55 +0000 | [diff] [blame] | 17 | import urllib |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 18 | import zlib |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 19 | |
| 20 | import run_isolated |
vadimsh@chromium.org | a432647 | 2013-08-24 02:05:41 +0000 | [diff] [blame] | 21 | |
vadimsh@chromium.org | b074b16 | 2013-08-22 17:55:46 +0000 | [diff] [blame] | 22 | from utils import threading_utils |
vadimsh@chromium.org | a432647 | 2013-08-24 02:05:41 +0000 | [diff] [blame] | 23 | from utils import tools |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 24 | |
| 25 | |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 26 | # The minimum size of files to upload directly to the blobstore. |
maruel@chromium.org | aef29f8 | 2012-12-12 15:00:42 +0000 | [diff] [blame] | 27 | MIN_SIZE_FOR_DIRECT_BLOBSTORE = 20 * 1024 |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 28 | |
vadimsh@chromium.org | eea5242 | 2013-08-21 19:35:54 +0000 | [diff] [blame] | 29 | # The number of files to check the isolate server per /contains query. |
| 30 | # All files are sorted by likelihood of a change in the file content |
| 31 | # (currently file size is used to estimate this: larger the file -> larger the |
| 32 | # possibility it has changed). Then first ITEMS_PER_CONTAINS_QUERIES[0] files |
| 33 | # are taken and send to '/contains', then next ITEMS_PER_CONTAINS_QUERIES[1], |
| 34 | # and so on. Numbers here is a trade-off; the more per request, the lower the |
| 35 | # effect of HTTP round trip latency and TCP-level chattiness. On the other hand, |
| 36 | # larger values cause longer lookups, increasing the initial latency to start |
| 37 | # uploading, which is especially an issue for large files. This value is |
| 38 | # optimized for the "few thousands files to look up with minimal number of large |
| 39 | # files missing" case. |
| 40 | ITEMS_PER_CONTAINS_QUERIES = [20, 20, 50, 50, 50, 100] |
csharp@chromium.org | 07fa759 | 2013-01-11 18:19:30 +0000 | [diff] [blame] | 41 | |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 42 | # A list of already compressed extension types that should not receive any |
| 43 | # compression before being uploaded. |
| 44 | ALREADY_COMPRESSED_TYPES = [ |
| 45 | '7z', 'avi', 'cur', 'gif', 'h264', 'jar', 'jpeg', 'jpg', 'pdf', 'png', |
| 46 | 'wav', 'zip' |
| 47 | ] |
| 48 | |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 49 | |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 50 | def randomness(): |
| 51 | """Generates low-entropy randomness for MIME encoding. |
| 52 | |
| 53 | Exists so it can be mocked out in unit tests. |
| 54 | """ |
| 55 | return str(time.time()) |
| 56 | |
| 57 | |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 58 | def encode_multipart_formdata(fields, files, |
| 59 | mime_mapper=lambda _: 'application/octet-stream'): |
| 60 | """Encodes a Multipart form data object. |
| 61 | |
| 62 | Args: |
| 63 | fields: a sequence (name, value) elements for |
| 64 | regular form fields. |
| 65 | files: a sequence of (name, filename, value) elements for data to be |
| 66 | uploaded as files. |
| 67 | mime_mapper: function to return the mime type from the filename. |
| 68 | Returns: |
| 69 | content_type: for httplib.HTTP instance |
| 70 | body: for httplib.HTTP instance |
| 71 | """ |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 72 | boundary = hashlib.md5(randomness()).hexdigest() |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 73 | body_list = [] |
| 74 | for (key, value) in fields: |
| 75 | if isinstance(key, unicode): |
| 76 | value = key.encode('utf-8') |
| 77 | if isinstance(value, unicode): |
| 78 | value = value.encode('utf-8') |
| 79 | body_list.append('--' + boundary) |
| 80 | body_list.append('Content-Disposition: form-data; name="%s"' % key) |
| 81 | body_list.append('') |
| 82 | body_list.append(value) |
| 83 | body_list.append('--' + boundary) |
| 84 | body_list.append('') |
| 85 | for (key, filename, value) in files: |
| 86 | if isinstance(key, unicode): |
| 87 | value = key.encode('utf-8') |
| 88 | if isinstance(filename, unicode): |
| 89 | value = filename.encode('utf-8') |
| 90 | if isinstance(value, unicode): |
| 91 | value = value.encode('utf-8') |
| 92 | body_list.append('--' + boundary) |
| 93 | body_list.append('Content-Disposition: form-data; name="%s"; ' |
| 94 | 'filename="%s"' % (key, filename)) |
| 95 | body_list.append('Content-Type: %s' % mime_mapper(filename)) |
| 96 | body_list.append('') |
| 97 | body_list.append(value) |
| 98 | body_list.append('--' + boundary) |
| 99 | body_list.append('') |
| 100 | if body_list: |
| 101 | body_list[-2] += '--' |
| 102 | body = '\r\n'.join(body_list) |
| 103 | content_type = 'multipart/form-data; boundary=%s' % boundary |
| 104 | return content_type, body |
| 105 | |
| 106 | |
maruel@chromium.org | 037758d | 2012-12-10 17:59:46 +0000 | [diff] [blame] | 107 | def sha1_file(filepath): |
| 108 | """Calculates the SHA-1 of a file without reading it all in memory at once.""" |
| 109 | digest = hashlib.sha1() |
| 110 | with open(filepath, 'rb') as f: |
| 111 | while True: |
| 112 | # Read in 1mb chunks. |
| 113 | chunk = f.read(1024*1024) |
| 114 | if not chunk: |
| 115 | break |
| 116 | digest.update(chunk) |
| 117 | return digest.hexdigest() |
| 118 | |
| 119 | |
vadimsh@chromium.org | 80f7300 | 2013-07-12 14:52:44 +0000 | [diff] [blame] | 120 | def url_read(url, **kwargs): |
| 121 | result = run_isolated.url_read(url, **kwargs) |
| 122 | if result is None: |
maruel@chromium.org | ef33312 | 2013-03-12 20:36:40 +0000 | [diff] [blame] | 123 | # If we get no response from the server, assume it is down and raise an |
| 124 | # exception. |
| 125 | raise run_isolated.MappingError('Unable to connect to server %s' % url) |
| 126 | return result |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 127 | |
| 128 | |
maruel@chromium.org | dc359e6 | 2013-03-14 13:08:55 +0000 | [diff] [blame] | 129 | def upload_hash_content_to_blobstore( |
| 130 | generate_upload_url, data, hash_key, content): |
vadimsh@chromium.org | 80f7300 | 2013-07-12 14:52:44 +0000 | [diff] [blame] | 131 | """Uploads the given hash contents directly to the blobstore via a generated |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 132 | url. |
| 133 | |
| 134 | Arguments: |
| 135 | generate_upload_url: The url to get the new upload url from. |
maruel@chromium.org | dc359e6 | 2013-03-14 13:08:55 +0000 | [diff] [blame] | 136 | data: extra POST data. |
| 137 | hash_key: sha1 of the uncompressed version of content. |
| 138 | content: The contents to upload. Must fit in memory for now. |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 139 | """ |
| 140 | logging.debug('Generating url to directly upload file to blobstore') |
maruel@chromium.org | 92a3d2e | 2012-12-20 16:22:29 +0000 | [diff] [blame] | 141 | assert isinstance(hash_key, str), hash_key |
| 142 | assert isinstance(content, str), (hash_key, content) |
maruel@chromium.org | d58bf5b | 2013-04-26 17:57:42 +0000 | [diff] [blame] | 143 | # TODO(maruel): Support large files. This would require streaming support. |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 144 | content_type, body = encode_multipart_formdata( |
maruel@chromium.org | d58bf5b | 2013-04-26 17:57:42 +0000 | [diff] [blame] | 145 | data, [('content', hash_key, content)]) |
maruel@chromium.org | 2b2139a | 2013-04-30 20:14:58 +0000 | [diff] [blame] | 146 | for attempt in xrange(run_isolated.URL_OPEN_MAX_ATTEMPTS): |
maruel@chromium.org | d58bf5b | 2013-04-26 17:57:42 +0000 | [diff] [blame] | 147 | # Retry HTTP 50x here. |
vadimsh@chromium.org | 80f7300 | 2013-07-12 14:52:44 +0000 | [diff] [blame] | 148 | upload_url = run_isolated.url_read(generate_upload_url, data=data) |
| 149 | if not upload_url: |
maruel@chromium.org | d58bf5b | 2013-04-26 17:57:42 +0000 | [diff] [blame] | 150 | raise run_isolated.MappingError( |
| 151 | 'Unable to connect to server %s' % generate_upload_url) |
maruel@chromium.org | d58bf5b | 2013-04-26 17:57:42 +0000 | [diff] [blame] | 152 | |
| 153 | # Do not retry this request on HTTP 50x. Regenerate an upload url each time |
| 154 | # since uploading "consumes" the upload url. |
vadimsh@chromium.org | 80f7300 | 2013-07-12 14:52:44 +0000 | [diff] [blame] | 155 | result = run_isolated.url_read( |
maruel@chromium.org | d58bf5b | 2013-04-26 17:57:42 +0000 | [diff] [blame] | 156 | upload_url, data=body, content_type=content_type, retry_50x=False) |
vadimsh@chromium.org | 80f7300 | 2013-07-12 14:52:44 +0000 | [diff] [blame] | 157 | if result is not None: |
| 158 | return result |
maruel@chromium.org | 2b2139a | 2013-04-30 20:14:58 +0000 | [diff] [blame] | 159 | if attempt != run_isolated.URL_OPEN_MAX_ATTEMPTS - 1: |
| 160 | run_isolated.HttpService.sleep_before_retry(attempt, None) |
maruel@chromium.org | d58bf5b | 2013-04-26 17:57:42 +0000 | [diff] [blame] | 161 | raise run_isolated.MappingError( |
| 162 | 'Unable to connect to server %s' % generate_upload_url) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 163 | |
| 164 | |
| 165 | class UploadRemote(run_isolated.Remote): |
maruel@chromium.org | 034e396 | 2013-03-13 13:34:25 +0000 | [diff] [blame] | 166 | def __init__(self, namespace, base_url, token): |
maruel@chromium.org | 21243ce | 2012-12-20 17:43:00 +0000 | [diff] [blame] | 167 | self.namespace = str(namespace) |
maruel@chromium.org | 034e396 | 2013-03-13 13:34:25 +0000 | [diff] [blame] | 168 | self._token = token |
| 169 | super(UploadRemote, self).__init__(base_url) |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 170 | |
| 171 | def get_file_handler(self, base_url): |
maruel@chromium.org | 21243ce | 2012-12-20 17:43:00 +0000 | [diff] [blame] | 172 | base_url = str(base_url) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 173 | def upload_file(content, hash_key): |
maruel@chromium.org | 034e396 | 2013-03-13 13:34:25 +0000 | [diff] [blame] | 174 | # TODO(maruel): Detect failures. |
maruel@chromium.org | 21243ce | 2012-12-20 17:43:00 +0000 | [diff] [blame] | 175 | hash_key = str(hash_key) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 176 | content_url = base_url.rstrip('/') + '/content/' |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 177 | if len(content) > MIN_SIZE_FOR_DIRECT_BLOBSTORE: |
maruel@chromium.org | dc359e6 | 2013-03-14 13:08:55 +0000 | [diff] [blame] | 178 | url = '%sgenerate_blobstore_url/%s/%s' % ( |
| 179 | content_url, self.namespace, hash_key) |
maruel@chromium.org | e82112e | 2013-04-24 14:41:55 +0000 | [diff] [blame] | 180 | # self._token is stored already quoted but it is unnecessary here, and |
| 181 | # only here. |
| 182 | data = [('token', urllib.unquote(self._token))] |
maruel@chromium.org | dc359e6 | 2013-03-14 13:08:55 +0000 | [diff] [blame] | 183 | upload_hash_content_to_blobstore(url, data, hash_key, content) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 184 | else: |
maruel@chromium.org | 034e396 | 2013-03-13 13:34:25 +0000 | [diff] [blame] | 185 | url = '%sstore/%s/%s?token=%s' % ( |
| 186 | content_url, self.namespace, hash_key, self._token) |
vadimsh@chromium.org | 80f7300 | 2013-07-12 14:52:44 +0000 | [diff] [blame] | 187 | url_read(url, data=content, content_type='application/octet-stream') |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 188 | return upload_file |
| 189 | |
| 190 | |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 191 | def check_files_exist_on_server(query_url, queries): |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 192 | """Queries the server to see which files from this batch already exist there. |
| 193 | |
| 194 | Arguments: |
| 195 | queries: The hash files to potential upload to the server. |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 196 | Returns: |
| 197 | missing_files: list of files that are missing on the server. |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 198 | """ |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 199 | logging.info('Checking existence of %d files...', len(queries)) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 200 | body = ''.join( |
maruel@chromium.org | e5c1713 | 2012-11-21 18:18:46 +0000 | [diff] [blame] | 201 | (binascii.unhexlify(meta_data['h']) for (_, meta_data) in queries)) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 202 | assert (len(body) % 20) == 0, repr(body) |
| 203 | |
vadimsh@chromium.org | 80f7300 | 2013-07-12 14:52:44 +0000 | [diff] [blame] | 204 | response = url_read( |
| 205 | query_url, data=body, content_type='application/octet-stream') |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 206 | if len(queries) != len(response): |
| 207 | raise run_isolated.MappingError( |
| 208 | 'Got an incorrect number of responses from the server. Expected %d, ' |
| 209 | 'but got %d' % (len(queries), len(response))) |
| 210 | |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 211 | missing_files = [ |
| 212 | queries[i] for i, flag in enumerate(response) if flag == chr(0) |
| 213 | ] |
| 214 | logging.info('Queried %d files, %d cache hit', |
| 215 | len(queries), len(queries) - len(missing_files)) |
| 216 | return missing_files |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 217 | |
| 218 | |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 219 | def compression_level(filename): |
| 220 | """Given a filename calculates the ideal compression level to use.""" |
| 221 | file_ext = os.path.splitext(filename)[1].lower() |
| 222 | # TODO(csharp): Profile to find what compression level works best. |
| 223 | return 0 if file_ext in ALREADY_COMPRESSED_TYPES else 7 |
| 224 | |
| 225 | |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 226 | def read_and_compress(filepath, level): |
| 227 | """Reads a file and returns its content gzip compressed.""" |
| 228 | compressor = zlib.compressobj(level) |
| 229 | compressed_data = cStringIO.StringIO() |
| 230 | with open(filepath, 'rb') as f: |
| 231 | while True: |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 232 | chunk = f.read(run_isolated.ZIPPED_FILE_CHUNK) |
| 233 | if not chunk: |
| 234 | break |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 235 | compressed_data.write(compressor.compress(chunk)) |
| 236 | compressed_data.write(compressor.flush(zlib.Z_FINISH)) |
| 237 | value = compressed_data.getvalue() |
| 238 | compressed_data.close() |
| 239 | return value |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 240 | |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 241 | |
| 242 | def zip_and_trigger_upload(infile, metadata, upload_function): |
| 243 | # TODO(csharp): Fix crbug.com/150823 and enable the touched logic again. |
| 244 | # if not metadata['T']: |
| 245 | compressed_data = read_and_compress(infile, compression_level(infile)) |
| 246 | priority = ( |
| 247 | run_isolated.Remote.HIGH if metadata.get('priority', '1') == '0' |
| 248 | else run_isolated.Remote.MED) |
| 249 | return upload_function(priority, compressed_data, metadata['h'], None) |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 250 | |
| 251 | |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 252 | def batch_files_for_check(infiles): |
| 253 | """Splits list of files to check for existence on the server into batches. |
maruel@chromium.org | 35fc0c8 | 2013-01-17 15:14:14 +0000 | [diff] [blame] | 254 | |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 255 | Each batch corresponds to a single 'exists?' query to the server. |
| 256 | |
| 257 | Yields: |
| 258 | batches: list of batches, each batch is a list of files. |
maruel@chromium.org | 35fc0c8 | 2013-01-17 15:14:14 +0000 | [diff] [blame] | 259 | """ |
vadimsh@chromium.org | eea5242 | 2013-08-21 19:35:54 +0000 | [diff] [blame] | 260 | batch_count = 0 |
| 261 | batch_size_limit = ITEMS_PER_CONTAINS_QUERIES[0] |
maruel@chromium.org | 35fc0c8 | 2013-01-17 15:14:14 +0000 | [diff] [blame] | 262 | next_queries = [] |
csharp@chromium.org | 90c4581 | 2013-01-23 14:27:21 +0000 | [diff] [blame] | 263 | items = ((k, v) for k, v in infiles.iteritems() if 's' in v) |
| 264 | for relfile, metadata in sorted(items, key=lambda x: -x[1]['s']): |
maruel@chromium.org | 35fc0c8 | 2013-01-17 15:14:14 +0000 | [diff] [blame] | 265 | next_queries.append((relfile, metadata)) |
vadimsh@chromium.org | eea5242 | 2013-08-21 19:35:54 +0000 | [diff] [blame] | 266 | if len(next_queries) == batch_size_limit: |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 267 | yield next_queries |
maruel@chromium.org | 35fc0c8 | 2013-01-17 15:14:14 +0000 | [diff] [blame] | 268 | next_queries = [] |
vadimsh@chromium.org | eea5242 | 2013-08-21 19:35:54 +0000 | [diff] [blame] | 269 | batch_count += 1 |
| 270 | batch_size_limit = ITEMS_PER_CONTAINS_QUERIES[ |
| 271 | min(batch_count, len(ITEMS_PER_CONTAINS_QUERIES) - 1)] |
maruel@chromium.org | 35fc0c8 | 2013-01-17 15:14:14 +0000 | [diff] [blame] | 272 | if next_queries: |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 273 | yield next_queries |
| 274 | |
| 275 | |
| 276 | def get_files_to_upload(contains_hash_url, infiles): |
| 277 | """Yields files that are missing on the server.""" |
vadimsh@chromium.org | b074b16 | 2013-08-22 17:55:46 +0000 | [diff] [blame] | 278 | with threading_utils.ThreadPool(1, 16, 0, prefix='get_files_to_upload') as tp: |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 279 | for files in batch_files_for_check(infiles): |
vadimsh@chromium.org | b074b16 | 2013-08-22 17:55:46 +0000 | [diff] [blame] | 280 | tp.add_task(0, check_files_exist_on_server, contains_hash_url, files) |
| 281 | for missing_file in itertools.chain.from_iterable(tp.iter_results()): |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 282 | yield missing_file |
maruel@chromium.org | 35fc0c8 | 2013-01-17 15:14:14 +0000 | [diff] [blame] | 283 | |
| 284 | |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 285 | def upload_sha1_tree(base_url, indir, infiles, namespace): |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 286 | """Uploads the given tree to the given url. |
| 287 | |
| 288 | Arguments: |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 289 | base_url: The base url, it is assume that |base_url|/has/ can be used to |
| 290 | query if an element was already uploaded, and |base_url|/store/ |
| 291 | can be used to upload a new element. |
| 292 | indir: Root directory the infiles are based in. |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 293 | infiles: dict of files to upload files from |indir| to |base_url|. |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 294 | namespace: The namespace to use on the server. |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 295 | """ |
| 296 | logging.info('upload tree(base_url=%s, indir=%s, files=%d)' % |
| 297 | (base_url, indir, len(infiles))) |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 298 | assert base_url.startswith('http'), base_url |
| 299 | base_url = base_url.rstrip('/') |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 300 | |
maruel@chromium.org | 034e396 | 2013-03-13 13:34:25 +0000 | [diff] [blame] | 301 | # TODO(maruel): Make this request much earlier asynchronously while the files |
| 302 | # are being enumerated. |
vadimsh@chromium.org | 80f7300 | 2013-07-12 14:52:44 +0000 | [diff] [blame] | 303 | token = urllib.quote(url_read(base_url + '/content/get_token')) |
maruel@chromium.org | 034e396 | 2013-03-13 13:34:25 +0000 | [diff] [blame] | 304 | |
csharp@chromium.org | 07fa759 | 2013-01-11 18:19:30 +0000 | [diff] [blame] | 305 | # Create a pool of workers to zip and upload any files missing from |
| 306 | # the server. |
vadimsh@chromium.org | b074b16 | 2013-08-22 17:55:46 +0000 | [diff] [blame] | 307 | num_threads = threading_utils.num_processors() |
| 308 | zipping_pool = threading_utils.ThreadPool(min(2, num_threads), |
| 309 | num_threads, 0, 'zip') |
maruel@chromium.org | 034e396 | 2013-03-13 13:34:25 +0000 | [diff] [blame] | 310 | remote_uploader = UploadRemote(namespace, base_url, token) |
csharp@chromium.org | 07fa759 | 2013-01-11 18:19:30 +0000 | [diff] [blame] | 311 | |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 312 | # Starts the zip and upload process for files that are missing |
| 313 | # from the server. |
| 314 | contains_hash_url = '%s/content/contains/%s?token=%s' % ( |
| 315 | base_url, namespace, token) |
csharp@chromium.org | 20a888c | 2013-01-15 15:06:55 +0000 | [diff] [blame] | 316 | uploaded = [] |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 317 | for relfile, metadata in get_files_to_upload(contains_hash_url, infiles): |
csharp@chromium.org | 07fa759 | 2013-01-11 18:19:30 +0000 | [diff] [blame] | 318 | infile = os.path.join(indir, relfile) |
maruel@chromium.org | 831958f | 2013-01-22 15:01:46 +0000 | [diff] [blame] | 319 | zipping_pool.add_task(0, zip_and_trigger_upload, infile, metadata, |
csharp@chromium.org | 07fa759 | 2013-01-11 18:19:30 +0000 | [diff] [blame] | 320 | remote_uploader.add_item) |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 321 | uploaded.append((relfile, metadata)) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 322 | |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 323 | logging.info('Waiting for all files to finish zipping') |
| 324 | zipping_pool.join() |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 325 | zipping_pool.close() |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 326 | logging.info('All files zipped.') |
| 327 | |
| 328 | logging.info('Waiting for all files to finish uploading') |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 329 | # Will raise if any exception occurred. |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 330 | remote_uploader.join() |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 331 | remote_uploader.close() |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 332 | logging.info('All files are uploaded') |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 333 | |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 334 | total = len(infiles) |
maruel@chromium.org | e5c1713 | 2012-11-21 18:18:46 +0000 | [diff] [blame] | 335 | total_size = sum(metadata.get('s', 0) for metadata in infiles.itervalues()) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 336 | logging.info( |
| 337 | 'Total: %6d, %9.1fkb', |
| 338 | total, |
maruel@chromium.org | e5c1713 | 2012-11-21 18:18:46 +0000 | [diff] [blame] | 339 | sum(m.get('s', 0) for m in infiles.itervalues()) / 1024.) |
csharp@chromium.org | 20a888c | 2013-01-15 15:06:55 +0000 | [diff] [blame] | 340 | cache_hit = set(infiles.iterkeys()) - set(x[0] for x in uploaded) |
maruel@chromium.org | e5c1713 | 2012-11-21 18:18:46 +0000 | [diff] [blame] | 341 | cache_hit_size = sum(infiles[i].get('s', 0) for i in cache_hit) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 342 | logging.info( |
| 343 | 'cache hit: %6d, %9.1fkb, %6.2f%% files, %6.2f%% size', |
| 344 | len(cache_hit), |
| 345 | cache_hit_size / 1024., |
| 346 | len(cache_hit) * 100. / total, |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 347 | cache_hit_size * 100. / total_size if total_size else 0) |
csharp@chromium.org | 20a888c | 2013-01-15 15:06:55 +0000 | [diff] [blame] | 348 | cache_miss = uploaded |
maruel@chromium.org | e5c1713 | 2012-11-21 18:18:46 +0000 | [diff] [blame] | 349 | cache_miss_size = sum(infiles[i[0]].get('s', 0) for i in cache_miss) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 350 | logging.info( |
| 351 | 'cache miss: %6d, %9.1fkb, %6.2f%% files, %6.2f%% size', |
| 352 | len(cache_miss), |
| 353 | cache_miss_size / 1024., |
| 354 | len(cache_miss) * 100. / total, |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 355 | cache_miss_size * 100. / total_size if total_size else 0) |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 356 | return 0 |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 357 | |
| 358 | |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 359 | def main(args): |
vadimsh@chromium.org | a432647 | 2013-08-24 02:05:41 +0000 | [diff] [blame] | 360 | tools.disable_buffering() |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 361 | parser = optparse.OptionParser( |
| 362 | usage='%prog [options] <file1..fileN> or - to read from stdin', |
| 363 | description=sys.modules[__name__].__doc__) |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 364 | parser.add_option('-r', '--remote', help='Remote server to archive to') |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 365 | parser.add_option( |
| 366 | '-v', '--verbose', |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 367 | action='count', default=0, |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 368 | help='Use multiple times to increase verbosity') |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 369 | parser.add_option('--namespace', default='default-gzip', |
| 370 | help='The namespace to use on the server.') |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 371 | |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 372 | options, files = parser.parse_args(args) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 373 | |
| 374 | levels = [logging.ERROR, logging.INFO, logging.DEBUG] |
| 375 | logging.basicConfig( |
| 376 | level=levels[min(len(levels)-1, options.verbose)], |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 377 | format='[%(threadName)s] %(asctime)s,%(msecs)03d %(levelname)5s' |
| 378 | ' %(module)15s(%(lineno)3d): %(message)s', |
| 379 | datefmt='%H:%M:%S') |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 380 | if files == ['-']: |
| 381 | files = sys.stdin.readlines() |
| 382 | |
| 383 | if not files: |
| 384 | parser.error('Nothing to upload') |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 385 | if not options.remote: |
| 386 | parser.error('Nowhere to send. Please specify --remote') |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 387 | |
| 388 | # Load the necessary metadata. This is going to be rewritten eventually to be |
| 389 | # more efficient. |
| 390 | infiles = dict( |
| 391 | ( |
| 392 | f, |
| 393 | { |
maruel@chromium.org | e5c1713 | 2012-11-21 18:18:46 +0000 | [diff] [blame] | 394 | 's': os.stat(f).st_size, |
maruel@chromium.org | 037758d | 2012-12-10 17:59:46 +0000 | [diff] [blame] | 395 | 'h': sha1_file(f), |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 396 | } |
| 397 | ) |
| 398 | for f in files) |
| 399 | |
vadimsh@chromium.org | a432647 | 2013-08-24 02:05:41 +0000 | [diff] [blame] | 400 | with tools.Profiler('Archive'): |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 401 | return upload_sha1_tree( |
| 402 | base_url=options.remote, |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 403 | indir=os.getcwd(), |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 404 | infiles=infiles, |
| 405 | namespace=options.namespace) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 406 | |
| 407 | |
| 408 | if __name__ == '__main__': |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 409 | sys.exit(main(sys.argv[1:])) |