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