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