maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 2 | # Copyright 2013 The Chromium Authors. All rights reserved. |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 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 | |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 8 | __version__ = '0.1' |
| 9 | |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 10 | import binascii |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 11 | import cStringIO |
maruel@chromium.org | c2bfef4 | 2013-08-30 21:46:26 +0000 | [diff] [blame] | 12 | import functools |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 13 | import hashlib |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 14 | import itertools |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 15 | import logging |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 16 | import os |
| 17 | import sys |
| 18 | import time |
maruel@chromium.org | e82112e | 2013-04-24 14:41:55 +0000 | [diff] [blame] | 19 | import urllib |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 20 | import zlib |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 21 | |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 22 | from third_party import colorama |
| 23 | from third_party.depot_tools import fix_encoding |
| 24 | from third_party.depot_tools import subcommand |
| 25 | |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 26 | import run_isolated |
vadimsh@chromium.org | a432647 | 2013-08-24 02:05:41 +0000 | [diff] [blame] | 27 | |
vadimsh@chromium.org | 6b70621 | 2013-08-28 15:03:46 +0000 | [diff] [blame] | 28 | from utils import net |
vadimsh@chromium.org | b074b16 | 2013-08-22 17:55:46 +0000 | [diff] [blame] | 29 | from utils import threading_utils |
vadimsh@chromium.org | a432647 | 2013-08-24 02:05:41 +0000 | [diff] [blame] | 30 | from utils import tools |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 31 | |
| 32 | |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 33 | # Default server. |
| 34 | # TODO(maruel): Chromium-specific. |
| 35 | ISOLATE_SERVER = 'https://isolateserver-dev.appspot.com/' |
| 36 | |
| 37 | |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 38 | # The minimum size of files to upload directly to the blobstore. |
maruel@chromium.org | aef29f8 | 2012-12-12 15:00:42 +0000 | [diff] [blame] | 39 | MIN_SIZE_FOR_DIRECT_BLOBSTORE = 20 * 1024 |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 40 | |
vadimsh@chromium.org | eea5242 | 2013-08-21 19:35:54 +0000 | [diff] [blame] | 41 | # 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. |
| 52 | ITEMS_PER_CONTAINS_QUERIES = [20, 20, 50, 50, 50, 100] |
csharp@chromium.org | 07fa759 | 2013-01-11 18:19:30 +0000 | [diff] [blame] | 53 | |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 54 | # A list of already compressed extension types that should not receive any |
| 55 | # compression before being uploaded. |
| 56 | ALREADY_COMPRESSED_TYPES = [ |
| 57 | '7z', 'avi', 'cur', 'gif', 'h264', 'jar', 'jpeg', 'jpg', 'pdf', 'png', |
| 58 | 'wav', 'zip' |
| 59 | ] |
| 60 | |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 61 | |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 62 | def 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.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 70 | def 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.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 84 | boundary = hashlib.md5(randomness()).hexdigest() |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 85 | 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.org | 037758d | 2012-12-10 17:59:46 +0000 | [diff] [blame] | 119 | def 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.org | 80f7300 | 2013-07-12 14:52:44 +0000 | [diff] [blame] | 132 | def url_read(url, **kwargs): |
vadimsh@chromium.org | 6b70621 | 2013-08-28 15:03:46 +0000 | [diff] [blame] | 133 | result = net.url_read(url, **kwargs) |
vadimsh@chromium.org | 80f7300 | 2013-07-12 14:52:44 +0000 | [diff] [blame] | 134 | if result is None: |
maruel@chromium.org | ef33312 | 2013-03-12 20:36:40 +0000 | [diff] [blame] | 135 | # 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.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 139 | |
| 140 | |
maruel@chromium.org | dc359e6 | 2013-03-14 13:08:55 +0000 | [diff] [blame] | 141 | def upload_hash_content_to_blobstore( |
| 142 | generate_upload_url, data, hash_key, content): |
vadimsh@chromium.org | 80f7300 | 2013-07-12 14:52:44 +0000 | [diff] [blame] | 143 | """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] | 144 | url. |
| 145 | |
| 146 | Arguments: |
| 147 | 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] | 148 | 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.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 151 | """ |
| 152 | logging.debug('Generating url to directly upload file to blobstore') |
maruel@chromium.org | 92a3d2e | 2012-12-20 16:22:29 +0000 | [diff] [blame] | 153 | assert isinstance(hash_key, str), hash_key |
| 154 | assert isinstance(content, str), (hash_key, content) |
maruel@chromium.org | d58bf5b | 2013-04-26 17:57:42 +0000 | [diff] [blame] | 155 | # TODO(maruel): Support large files. This would require streaming support. |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 156 | content_type, body = encode_multipart_formdata( |
maruel@chromium.org | d58bf5b | 2013-04-26 17:57:42 +0000 | [diff] [blame] | 157 | data, [('content', hash_key, content)]) |
vadimsh@chromium.org | 043b76d | 2013-09-12 16:15:13 +0000 | [diff] [blame^] | 158 | for _ in net.retry_loop(max_attempts=net.URL_OPEN_MAX_ATTEMPTS): |
maruel@chromium.org | d58bf5b | 2013-04-26 17:57:42 +0000 | [diff] [blame] | 159 | # Retry HTTP 50x here. |
vadimsh@chromium.org | 6b70621 | 2013-08-28 15:03:46 +0000 | [diff] [blame] | 160 | upload_url = net.url_read(generate_upload_url, data=data) |
vadimsh@chromium.org | 80f7300 | 2013-07-12 14:52:44 +0000 | [diff] [blame] | 161 | if not upload_url: |
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 | d58bf5b | 2013-04-26 17:57:42 +0000 | [diff] [blame] | 164 | |
| 165 | # Do not retry this request on HTTP 50x. Regenerate an upload url each time |
| 166 | # since uploading "consumes" the upload url. |
vadimsh@chromium.org | 6b70621 | 2013-08-28 15:03:46 +0000 | [diff] [blame] | 167 | result = net.url_read( |
maruel@chromium.org | d58bf5b | 2013-04-26 17:57:42 +0000 | [diff] [blame] | 168 | upload_url, data=body, content_type=content_type, retry_50x=False) |
vadimsh@chromium.org | 80f7300 | 2013-07-12 14:52:44 +0000 | [diff] [blame] | 169 | if result is not None: |
| 170 | return result |
maruel@chromium.org | d58bf5b | 2013-04-26 17:57:42 +0000 | [diff] [blame] | 171 | raise run_isolated.MappingError( |
| 172 | 'Unable to connect to server %s' % generate_upload_url) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 173 | |
| 174 | |
maruel@chromium.org | c2bfef4 | 2013-08-30 21:46:26 +0000 | [diff] [blame] | 175 | def 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.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 192 | class UploadRemote(run_isolated.Remote): |
maruel@chromium.org | 034e396 | 2013-03-13 13:34:25 +0000 | [diff] [blame] | 193 | def __init__(self, namespace, base_url, token): |
maruel@chromium.org | 21243ce | 2012-12-20 17:43:00 +0000 | [diff] [blame] | 194 | self.namespace = str(namespace) |
maruel@chromium.org | 034e396 | 2013-03-13 13:34:25 +0000 | [diff] [blame] | 195 | self._token = token |
| 196 | super(UploadRemote, self).__init__(base_url) |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 197 | |
| 198 | def get_file_handler(self, base_url): |
maruel@chromium.org | 21243ce | 2012-12-20 17:43:00 +0000 | [diff] [blame] | 199 | base_url = str(base_url) |
maruel@chromium.org | c2bfef4 | 2013-08-30 21:46:26 +0000 | [diff] [blame] | 200 | return functools.partial( |
| 201 | upload_file, base_url, self.namespace, token=self._token) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 202 | |
| 203 | |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 204 | def check_files_exist_on_server(query_url, queries): |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 205 | """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.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 209 | Returns: |
| 210 | missing_files: list of files that are missing on the server. |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 211 | """ |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 212 | logging.info('Checking existence of %d files...', len(queries)) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 213 | body = ''.join( |
maruel@chromium.org | e5c1713 | 2012-11-21 18:18:46 +0000 | [diff] [blame] | 214 | (binascii.unhexlify(meta_data['h']) for (_, meta_data) in queries)) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 215 | assert (len(body) % 20) == 0, repr(body) |
| 216 | |
vadimsh@chromium.org | 80f7300 | 2013-07-12 14:52:44 +0000 | [diff] [blame] | 217 | response = url_read( |
| 218 | query_url, data=body, content_type='application/octet-stream') |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 219 | 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.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 224 | 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.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 230 | |
| 231 | |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 232 | def 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.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 239 | def 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.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 245 | chunk = f.read(run_isolated.ZIPPED_FILE_CHUNK) |
| 246 | if not chunk: |
| 247 | break |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 248 | 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.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 253 | |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 254 | |
| 255 | def 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.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 263 | |
| 264 | |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 265 | def batch_files_for_check(infiles): |
| 266 | """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] | 267 | |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 268 | 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.org | 35fc0c8 | 2013-01-17 15:14:14 +0000 | [diff] [blame] | 272 | """ |
vadimsh@chromium.org | eea5242 | 2013-08-21 19:35:54 +0000 | [diff] [blame] | 273 | batch_count = 0 |
| 274 | batch_size_limit = ITEMS_PER_CONTAINS_QUERIES[0] |
maruel@chromium.org | 35fc0c8 | 2013-01-17 15:14:14 +0000 | [diff] [blame] | 275 | next_queries = [] |
csharp@chromium.org | 90c4581 | 2013-01-23 14:27:21 +0000 | [diff] [blame] | 276 | 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.org | 35fc0c8 | 2013-01-17 15:14:14 +0000 | [diff] [blame] | 278 | next_queries.append((relfile, metadata)) |
vadimsh@chromium.org | eea5242 | 2013-08-21 19:35:54 +0000 | [diff] [blame] | 279 | if len(next_queries) == batch_size_limit: |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 280 | yield next_queries |
maruel@chromium.org | 35fc0c8 | 2013-01-17 15:14:14 +0000 | [diff] [blame] | 281 | next_queries = [] |
vadimsh@chromium.org | eea5242 | 2013-08-21 19:35:54 +0000 | [diff] [blame] | 282 | batch_count += 1 |
| 283 | batch_size_limit = ITEMS_PER_CONTAINS_QUERIES[ |
| 284 | min(batch_count, len(ITEMS_PER_CONTAINS_QUERIES) - 1)] |
maruel@chromium.org | 35fc0c8 | 2013-01-17 15:14:14 +0000 | [diff] [blame] | 285 | if next_queries: |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 286 | yield next_queries |
| 287 | |
| 288 | |
| 289 | def get_files_to_upload(contains_hash_url, infiles): |
| 290 | """Yields files that are missing on the server.""" |
vadimsh@chromium.org | b074b16 | 2013-08-22 17:55:46 +0000 | [diff] [blame] | 291 | 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] | 292 | for files in batch_files_for_check(infiles): |
vadimsh@chromium.org | b074b16 | 2013-08-22 17:55:46 +0000 | [diff] [blame] | 293 | 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.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 295 | yield missing_file |
maruel@chromium.org | 35fc0c8 | 2013-01-17 15:14:14 +0000 | [diff] [blame] | 296 | |
| 297 | |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 298 | def upload_sha1_tree(base_url, indir, infiles, namespace): |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 299 | """Uploads the given tree to the given url. |
| 300 | |
| 301 | Arguments: |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 302 | 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.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 306 | 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] | 307 | namespace: The namespace to use on the server. |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 308 | """ |
| 309 | logging.info('upload tree(base_url=%s, indir=%s, files=%d)' % |
| 310 | (base_url, indir, len(infiles))) |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 311 | assert base_url.startswith('http'), base_url |
| 312 | base_url = base_url.rstrip('/') |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 313 | |
maruel@chromium.org | 034e396 | 2013-03-13 13:34:25 +0000 | [diff] [blame] | 314 | # TODO(maruel): Make this request much earlier asynchronously while the files |
| 315 | # are being enumerated. |
vadimsh@chromium.org | 80f7300 | 2013-07-12 14:52:44 +0000 | [diff] [blame] | 316 | token = urllib.quote(url_read(base_url + '/content/get_token')) |
maruel@chromium.org | 034e396 | 2013-03-13 13:34:25 +0000 | [diff] [blame] | 317 | |
csharp@chromium.org | 07fa759 | 2013-01-11 18:19:30 +0000 | [diff] [blame] | 318 | # Create a pool of workers to zip and upload any files missing from |
| 319 | # the server. |
vadimsh@chromium.org | b074b16 | 2013-08-22 17:55:46 +0000 | [diff] [blame] | 320 | num_threads = threading_utils.num_processors() |
| 321 | zipping_pool = threading_utils.ThreadPool(min(2, num_threads), |
| 322 | num_threads, 0, 'zip') |
maruel@chromium.org | 034e396 | 2013-03-13 13:34:25 +0000 | [diff] [blame] | 323 | remote_uploader = UploadRemote(namespace, base_url, token) |
csharp@chromium.org | 07fa759 | 2013-01-11 18:19:30 +0000 | [diff] [blame] | 324 | |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 325 | # 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.org | 20a888c | 2013-01-15 15:06:55 +0000 | [diff] [blame] | 329 | uploaded = [] |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 330 | 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] | 331 | infile = os.path.join(indir, relfile) |
maruel@chromium.org | 831958f | 2013-01-22 15:01:46 +0000 | [diff] [blame] | 332 | zipping_pool.add_task(0, zip_and_trigger_upload, infile, metadata, |
csharp@chromium.org | 07fa759 | 2013-01-11 18:19:30 +0000 | [diff] [blame] | 333 | remote_uploader.add_item) |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 334 | uploaded.append((relfile, metadata)) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 335 | |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 336 | logging.info('Waiting for all files to finish zipping') |
| 337 | zipping_pool.join() |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 338 | zipping_pool.close() |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 339 | logging.info('All files zipped.') |
| 340 | |
| 341 | logging.info('Waiting for all files to finish uploading') |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 342 | # Will raise if any exception occurred. |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 343 | remote_uploader.join() |
vadimsh@chromium.org | 53f8d5a | 2013-06-19 13:03:55 +0000 | [diff] [blame] | 344 | remote_uploader.close() |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 345 | logging.info('All files are uploaded') |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 346 | |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 347 | total = len(infiles) |
maruel@chromium.org | e5c1713 | 2012-11-21 18:18:46 +0000 | [diff] [blame] | 348 | 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] | 349 | logging.info( |
| 350 | 'Total: %6d, %9.1fkb', |
| 351 | total, |
maruel@chromium.org | e5c1713 | 2012-11-21 18:18:46 +0000 | [diff] [blame] | 352 | sum(m.get('s', 0) for m in infiles.itervalues()) / 1024.) |
csharp@chromium.org | 20a888c | 2013-01-15 15:06:55 +0000 | [diff] [blame] | 353 | 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] | 354 | 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] | 355 | 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.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 360 | cache_hit_size * 100. / total_size if total_size else 0) |
csharp@chromium.org | 20a888c | 2013-01-15 15:06:55 +0000 | [diff] [blame] | 361 | cache_miss = uploaded |
maruel@chromium.org | e5c1713 | 2012-11-21 18:18:46 +0000 | [diff] [blame] | 362 | 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] | 363 | 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.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 368 | cache_miss_size * 100. / total_size if total_size else 0) |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 369 | return 0 |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 370 | |
| 371 | |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 372 | @subcommand.usage('<file1..fileN> or - to read from stdin') |
| 373 | def CMDarchive(parser, args): |
| 374 | """Archives data to the server.""" |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 375 | options, files = parser.parse_args(args) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 376 | |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 377 | if files == ['-']: |
| 378 | files = sys.stdin.readlines() |
| 379 | |
| 380 | if not files: |
| 381 | parser.error('Nothing to upload') |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 382 | if not options.isolate_server: |
| 383 | parser.error('Nowhere to send. Please specify --isolate-server') |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 384 | |
| 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.org | e5c1713 | 2012-11-21 18:18:46 +0000 | [diff] [blame] | 391 | 's': os.stat(f).st_size, |
maruel@chromium.org | 037758d | 2012-12-10 17:59:46 +0000 | [diff] [blame] | 392 | 'h': sha1_file(f), |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 393 | } |
| 394 | ) |
| 395 | for f in files) |
| 396 | |
vadimsh@chromium.org | a432647 | 2013-08-24 02:05:41 +0000 | [diff] [blame] | 397 | with tools.Profiler('Archive'): |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 398 | return upload_sha1_tree( |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 399 | base_url=options.isolate_server, |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 400 | indir=os.getcwd(), |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 401 | infiles=infiles, |
| 402 | namespace=options.namespace) |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 403 | return 0 |
| 404 | |
| 405 | |
| 406 | def 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 | |
| 413 | class 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 | |
| 434 | def 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.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 446 | |
| 447 | |
| 448 | if __name__ == '__main__': |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 449 | fix_encoding.fix_encoding() |
| 450 | tools.disable_buffering() |
| 451 | colorama.init() |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 452 | sys.exit(main(sys.argv[1:])) |