maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python |
Marc-Antoine Ruel | 8add124 | 2013-11-05 17:28:27 -0500 | [diff] [blame] | 2 | # Copyright 2013 The Swarming Authors. All rights reserved. |
Marc-Antoine Ruel | e98b112 | 2013-11-05 20:27:57 -0500 | [diff] [blame] | 3 | # Use of this source code is governed under the Apache License, Version 2.0 that |
| 4 | # can be found in the LICENSE file. |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 5 | |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 6 | """Archives a set of files or directories to a server.""" |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 7 | |
Marc-Antoine Ruel | cfb6085 | 2014-07-02 15:22:00 -0400 | [diff] [blame] | 8 | __version__ = '0.3.4' |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 9 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 10 | import functools |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 11 | import hashlib |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 12 | import json |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 13 | import logging |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 14 | import os |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 15 | import re |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 16 | import shutil |
| 17 | import stat |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 18 | import sys |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 19 | import tempfile |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 20 | import threading |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 21 | import time |
maruel@chromium.org | e82112e | 2013-04-24 14:41:55 +0000 | [diff] [blame] | 22 | import urllib |
Marc-Antoine Ruel | 1687b5e | 2014-02-06 17:47:53 -0500 | [diff] [blame] | 23 | import urlparse |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 24 | import zlib |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 25 | |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 26 | from third_party import colorama |
| 27 | from third_party.depot_tools import fix_encoding |
| 28 | from third_party.depot_tools import subcommand |
| 29 | |
Marc-Antoine Ruel | 3798993 | 2013-11-19 16:28:08 -0500 | [diff] [blame] | 30 | from utils import file_path |
vadimsh@chromium.org | 6b70621 | 2013-08-28 15:03:46 +0000 | [diff] [blame] | 31 | from utils import net |
Marc-Antoine Ruel | cfb6085 | 2014-07-02 15:22:00 -0400 | [diff] [blame] | 32 | from utils import on_error |
vadimsh@chromium.org | b074b16 | 2013-08-22 17:55:46 +0000 | [diff] [blame] | 33 | from utils import threading_utils |
vadimsh@chromium.org | a432647 | 2013-08-24 02:05:41 +0000 | [diff] [blame] | 34 | from utils import tools |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 35 | |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 36 | import auth |
| 37 | |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 38 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 39 | # Version of isolate protocol passed to the server in /handshake request. |
| 40 | ISOLATE_PROTOCOL_VERSION = '1.0' |
Marc-Antoine Ruel | 1c1edd6 | 2013-12-06 09:13:13 -0500 | [diff] [blame] | 41 | # Version stored and expected in .isolated files. |
Marc-Antoine Ruel | 0519946 | 2014-03-13 15:40:48 -0400 | [diff] [blame] | 42 | ISOLATED_FILE_VERSION = '1.4' |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 43 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 44 | |
| 45 | # The number of files to check the isolate server per /pre-upload query. |
vadimsh@chromium.org | eea5242 | 2013-08-21 19:35:54 +0000 | [diff] [blame] | 46 | # All files are sorted by likelihood of a change in the file content |
| 47 | # (currently file size is used to estimate this: larger the file -> larger the |
| 48 | # possibility it has changed). Then first ITEMS_PER_CONTAINS_QUERIES[0] files |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 49 | # are taken and send to '/pre-upload', then next ITEMS_PER_CONTAINS_QUERIES[1], |
vadimsh@chromium.org | eea5242 | 2013-08-21 19:35:54 +0000 | [diff] [blame] | 50 | # and so on. Numbers here is a trade-off; the more per request, the lower the |
| 51 | # effect of HTTP round trip latency and TCP-level chattiness. On the other hand, |
| 52 | # larger values cause longer lookups, increasing the initial latency to start |
| 53 | # uploading, which is especially an issue for large files. This value is |
| 54 | # optimized for the "few thousands files to look up with minimal number of large |
| 55 | # files missing" case. |
| 56 | ITEMS_PER_CONTAINS_QUERIES = [20, 20, 50, 50, 50, 100] |
csharp@chromium.org | 07fa759 | 2013-01-11 18:19:30 +0000 | [diff] [blame] | 57 | |
maruel@chromium.org | 9958e4a | 2013-09-17 00:01:48 +0000 | [diff] [blame] | 58 | |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 59 | # A list of already compressed extension types that should not receive any |
| 60 | # compression before being uploaded. |
| 61 | ALREADY_COMPRESSED_TYPES = [ |
Marc-Antoine Ruel | 7f234c8 | 2014-08-06 21:55:18 -0400 | [diff] [blame] | 62 | '7z', 'avi', 'cur', 'gif', 'h264', 'jar', 'jpeg', 'jpg', 'mp4', 'pdf', |
| 63 | 'png', 'wav', 'zip', |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 64 | ] |
| 65 | |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 66 | |
maruel@chromium.org | dedbf49 | 2013-09-12 20:42:11 +0000 | [diff] [blame] | 67 | # The file size to be used when we don't know the correct file size, |
| 68 | # generally used for .isolated files. |
| 69 | UNKNOWN_FILE_SIZE = None |
| 70 | |
| 71 | |
maruel@chromium.org | 8750e4b | 2013-09-18 02:37:57 +0000 | [diff] [blame] | 72 | # Chunk size to use when doing disk I/O. |
| 73 | DISK_FILE_CHUNK = 1024 * 1024 |
| 74 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 75 | # Chunk size to use when reading from network stream. |
| 76 | NET_IO_FILE_CHUNK = 16 * 1024 |
| 77 | |
maruel@chromium.org | 8750e4b | 2013-09-18 02:37:57 +0000 | [diff] [blame] | 78 | |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 79 | # Read timeout in seconds for downloads from isolate storage. If there's no |
| 80 | # response from the server within this timeout whole download will be aborted. |
| 81 | DOWNLOAD_READ_TIMEOUT = 60 |
| 82 | |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 83 | # Maximum expected delay (in seconds) between successive file fetches |
| 84 | # in run_tha_test. If it takes longer than that, a deadlock might be happening |
| 85 | # and all stack frames for all threads are dumped to log. |
| 86 | DEADLOCK_TIMEOUT = 5 * 60 |
| 87 | |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 88 | |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 89 | # The delay (in seconds) to wait between logging statements when retrieving |
| 90 | # the required files. This is intended to let the user (or buildbot) know that |
| 91 | # the program is still running. |
| 92 | DELAY_BETWEEN_UPDATES_IN_SECS = 30 |
| 93 | |
| 94 | |
maruel@chromium.org | 385d73d | 2013-09-19 18:33:21 +0000 | [diff] [blame] | 95 | # Sadly, hashlib uses 'sha1' instead of the standard 'sha-1' so explicitly |
| 96 | # specify the names here. |
| 97 | SUPPORTED_ALGOS = { |
| 98 | 'md5': hashlib.md5, |
| 99 | 'sha-1': hashlib.sha1, |
| 100 | 'sha-512': hashlib.sha512, |
| 101 | } |
| 102 | |
| 103 | |
| 104 | # Used for serialization. |
| 105 | SUPPORTED_ALGOS_REVERSE = dict((v, k) for k, v in SUPPORTED_ALGOS.iteritems()) |
| 106 | |
| 107 | |
Marc-Antoine Ruel | ac54cb4 | 2013-11-18 14:05:35 -0500 | [diff] [blame] | 108 | DEFAULT_BLACKLIST = ( |
| 109 | # Temporary vim or python files. |
| 110 | r'^.+\.(?:pyc|swp)$', |
| 111 | # .git or .svn directory. |
| 112 | r'^(?:.+' + re.escape(os.path.sep) + r'|)\.(?:git|svn)$', |
| 113 | ) |
| 114 | |
| 115 | |
| 116 | # Chromium-specific. |
| 117 | DEFAULT_BLACKLIST += ( |
| 118 | r'^.+\.(?:run_test_cases)$', |
| 119 | r'^(?:.+' + re.escape(os.path.sep) + r'|)testserver\.log$', |
| 120 | ) |
| 121 | |
| 122 | |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 123 | class Error(Exception): |
| 124 | """Generic runtime error.""" |
| 125 | pass |
| 126 | |
| 127 | |
maruel@chromium.org | dedbf49 | 2013-09-12 20:42:11 +0000 | [diff] [blame] | 128 | class ConfigError(ValueError): |
| 129 | """Generic failure to load a .isolated file.""" |
| 130 | pass |
| 131 | |
| 132 | |
| 133 | class MappingError(OSError): |
| 134 | """Failed to recreate the tree.""" |
| 135 | pass |
| 136 | |
| 137 | |
maruel@chromium.org | 7b844a6 | 2013-09-17 13:04:59 +0000 | [diff] [blame] | 138 | def is_valid_hash(value, algo): |
| 139 | """Returns if the value is a valid hash for the corresponding algorithm.""" |
| 140 | size = 2 * algo().digest_size |
| 141 | return bool(re.match(r'^[a-fA-F0-9]{%d}$' % size, value)) |
| 142 | |
| 143 | |
| 144 | def hash_file(filepath, algo): |
| 145 | """Calculates the hash of a file without reading it all in memory at once. |
| 146 | |
| 147 | |algo| should be one of hashlib hashing algorithm. |
| 148 | """ |
| 149 | digest = algo() |
maruel@chromium.org | 037758d | 2012-12-10 17:59:46 +0000 | [diff] [blame] | 150 | with open(filepath, 'rb') as f: |
| 151 | while True: |
maruel@chromium.org | 8750e4b | 2013-09-18 02:37:57 +0000 | [diff] [blame] | 152 | chunk = f.read(DISK_FILE_CHUNK) |
maruel@chromium.org | 037758d | 2012-12-10 17:59:46 +0000 | [diff] [blame] | 153 | if not chunk: |
| 154 | break |
| 155 | digest.update(chunk) |
| 156 | return digest.hexdigest() |
| 157 | |
| 158 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 159 | def stream_read(stream, chunk_size): |
| 160 | """Reads chunks from |stream| and yields them.""" |
| 161 | while True: |
| 162 | data = stream.read(chunk_size) |
| 163 | if not data: |
| 164 | break |
| 165 | yield data |
| 166 | |
| 167 | |
Vadim Shtayura | f0cb97a | 2013-12-05 13:57:49 -0800 | [diff] [blame] | 168 | def file_read(filepath, chunk_size=DISK_FILE_CHUNK, offset=0): |
| 169 | """Yields file content in chunks of |chunk_size| starting from |offset|.""" |
maruel@chromium.org | 8750e4b | 2013-09-18 02:37:57 +0000 | [diff] [blame] | 170 | with open(filepath, 'rb') as f: |
Vadim Shtayura | f0cb97a | 2013-12-05 13:57:49 -0800 | [diff] [blame] | 171 | if offset: |
| 172 | f.seek(offset) |
maruel@chromium.org | 8750e4b | 2013-09-18 02:37:57 +0000 | [diff] [blame] | 173 | while True: |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 174 | data = f.read(chunk_size) |
maruel@chromium.org | 8750e4b | 2013-09-18 02:37:57 +0000 | [diff] [blame] | 175 | if not data: |
| 176 | break |
| 177 | yield data |
| 178 | |
| 179 | |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 180 | def file_write(filepath, content_generator): |
| 181 | """Writes file content as generated by content_generator. |
| 182 | |
maruel@chromium.org | 8750e4b | 2013-09-18 02:37:57 +0000 | [diff] [blame] | 183 | Creates the intermediary directory as needed. |
| 184 | |
| 185 | Returns the number of bytes written. |
| 186 | |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 187 | Meant to be mocked out in unit tests. |
| 188 | """ |
| 189 | filedir = os.path.dirname(filepath) |
| 190 | if not os.path.isdir(filedir): |
| 191 | os.makedirs(filedir) |
maruel@chromium.org | 8750e4b | 2013-09-18 02:37:57 +0000 | [diff] [blame] | 192 | total = 0 |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 193 | with open(filepath, 'wb') as f: |
| 194 | for d in content_generator: |
maruel@chromium.org | 8750e4b | 2013-09-18 02:37:57 +0000 | [diff] [blame] | 195 | total += len(d) |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 196 | f.write(d) |
maruel@chromium.org | 8750e4b | 2013-09-18 02:37:57 +0000 | [diff] [blame] | 197 | return total |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 198 | |
| 199 | |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 200 | def zip_compress(content_generator, level=7): |
| 201 | """Reads chunks from |content_generator| and yields zip compressed chunks.""" |
| 202 | compressor = zlib.compressobj(level) |
| 203 | for chunk in content_generator: |
| 204 | compressed = compressor.compress(chunk) |
| 205 | if compressed: |
| 206 | yield compressed |
| 207 | tail = compressor.flush(zlib.Z_FINISH) |
| 208 | if tail: |
| 209 | yield tail |
| 210 | |
| 211 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 212 | def zip_decompress(content_generator, chunk_size=DISK_FILE_CHUNK): |
| 213 | """Reads zipped data from |content_generator| and yields decompressed data. |
| 214 | |
| 215 | Decompresses data in small chunks (no larger than |chunk_size|) so that |
| 216 | zip bomb file doesn't cause zlib to preallocate huge amount of memory. |
| 217 | |
| 218 | Raises IOError if data is corrupted or incomplete. |
| 219 | """ |
| 220 | decompressor = zlib.decompressobj() |
| 221 | compressed_size = 0 |
| 222 | try: |
| 223 | for chunk in content_generator: |
| 224 | compressed_size += len(chunk) |
| 225 | data = decompressor.decompress(chunk, chunk_size) |
| 226 | if data: |
| 227 | yield data |
| 228 | while decompressor.unconsumed_tail: |
| 229 | data = decompressor.decompress(decompressor.unconsumed_tail, chunk_size) |
| 230 | if data: |
| 231 | yield data |
| 232 | tail = decompressor.flush() |
| 233 | if tail: |
| 234 | yield tail |
| 235 | except zlib.error as e: |
| 236 | raise IOError( |
| 237 | 'Corrupted zip stream (read %d bytes) - %s' % (compressed_size, e)) |
| 238 | # Ensure all data was read and decompressed. |
| 239 | if decompressor.unused_data or decompressor.unconsumed_tail: |
| 240 | raise IOError('Not all data was decompressed') |
| 241 | |
| 242 | |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 243 | def get_zip_compression_level(filename): |
| 244 | """Given a filename calculates the ideal zip compression level to use.""" |
| 245 | file_ext = os.path.splitext(filename)[1].lower() |
| 246 | # TODO(csharp): Profile to find what compression level works best. |
| 247 | return 0 if file_ext in ALREADY_COMPRESSED_TYPES else 7 |
| 248 | |
| 249 | |
maruel@chromium.org | af25485 | 2013-09-17 17:48:14 +0000 | [diff] [blame] | 250 | def create_directories(base_directory, files): |
| 251 | """Creates the directory structure needed by the given list of files.""" |
| 252 | logging.debug('create_directories(%s, %d)', base_directory, len(files)) |
| 253 | # Creates the tree of directories to create. |
| 254 | directories = set(os.path.dirname(f) for f in files) |
| 255 | for item in list(directories): |
| 256 | while item: |
| 257 | directories.add(item) |
| 258 | item = os.path.dirname(item) |
| 259 | for d in sorted(directories): |
| 260 | if d: |
| 261 | os.mkdir(os.path.join(base_directory, d)) |
| 262 | |
| 263 | |
Marc-Antoine Ruel | ccafe0e | 2013-11-08 16:15:36 -0500 | [diff] [blame] | 264 | def create_symlinks(base_directory, files): |
| 265 | """Creates any symlinks needed by the given set of files.""" |
maruel@chromium.org | af25485 | 2013-09-17 17:48:14 +0000 | [diff] [blame] | 266 | for filepath, properties in files: |
| 267 | if 'l' not in properties: |
| 268 | continue |
| 269 | if sys.platform == 'win32': |
Marc-Antoine Ruel | ccafe0e | 2013-11-08 16:15:36 -0500 | [diff] [blame] | 270 | # TODO(maruel): Create symlink via the win32 api. |
maruel@chromium.org | af25485 | 2013-09-17 17:48:14 +0000 | [diff] [blame] | 271 | logging.warning('Ignoring symlink %s', filepath) |
| 272 | continue |
| 273 | outfile = os.path.join(base_directory, filepath) |
Marc-Antoine Ruel | ccafe0e | 2013-11-08 16:15:36 -0500 | [diff] [blame] | 274 | # os.symlink() doesn't exist on Windows. |
maruel@chromium.org | af25485 | 2013-09-17 17:48:14 +0000 | [diff] [blame] | 275 | os.symlink(properties['l'], outfile) # pylint: disable=E1101 |
maruel@chromium.org | af25485 | 2013-09-17 17:48:14 +0000 | [diff] [blame] | 276 | |
| 277 | |
maruel@chromium.org | e45728d | 2013-09-16 23:23:22 +0000 | [diff] [blame] | 278 | def is_valid_file(filepath, size): |
maruel@chromium.org | dedbf49 | 2013-09-12 20:42:11 +0000 | [diff] [blame] | 279 | """Determines if the given files appears valid. |
| 280 | |
| 281 | Currently it just checks the file's size. |
| 282 | """ |
| 283 | if size == UNKNOWN_FILE_SIZE: |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 284 | return os.path.isfile(filepath) |
maruel@chromium.org | dedbf49 | 2013-09-12 20:42:11 +0000 | [diff] [blame] | 285 | actual_size = os.stat(filepath).st_size |
| 286 | if size != actual_size: |
| 287 | logging.warning( |
| 288 | 'Found invalid item %s; %d != %d', |
| 289 | os.path.basename(filepath), actual_size, size) |
| 290 | return False |
| 291 | return True |
| 292 | |
| 293 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 294 | class WorkerPool(threading_utils.AutoRetryThreadPool): |
| 295 | """Thread pool that automatically retries on IOError and runs a preconfigured |
| 296 | function. |
| 297 | """ |
| 298 | # Initial and maximum number of worker threads. |
| 299 | INITIAL_WORKERS = 2 |
| 300 | MAX_WORKERS = 16 |
| 301 | RETRIES = 5 |
| 302 | |
| 303 | def __init__(self): |
| 304 | super(WorkerPool, self).__init__( |
| 305 | [IOError], |
| 306 | self.RETRIES, |
| 307 | self.INITIAL_WORKERS, |
| 308 | self.MAX_WORKERS, |
| 309 | 0, |
| 310 | 'remote') |
maruel@chromium.org | e45728d | 2013-09-16 23:23:22 +0000 | [diff] [blame] | 311 | |
| 312 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 313 | class Item(object): |
| 314 | """An item to push to Storage. |
| 315 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 316 | Its digest and size may be provided in advance, if known. Otherwise they will |
| 317 | be derived from content(). If digest is provided, it MUST correspond to |
| 318 | hash algorithm used by Storage. |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 319 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 320 | When used with Storage, Item starts its life in a main thread, travels |
| 321 | to 'contains' thread, then to 'push' thread and then finally back to |
| 322 | the main thread. It is never used concurrently from multiple threads. |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 323 | """ |
| 324 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 325 | def __init__(self, digest=None, size=None, high_priority=False): |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 326 | self.digest = digest |
| 327 | self.size = size |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 328 | self.high_priority = high_priority |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 329 | self.compression_level = 6 |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 330 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 331 | def content(self): |
| 332 | """Iterable with content of this item as byte string (str) chunks.""" |
| 333 | raise NotImplementedError() |
| 334 | |
| 335 | def prepare(self, hash_algo): |
| 336 | """Ensures self.digest and self.size are set. |
| 337 | |
| 338 | Uses content() as a source of data to calculate them. Does nothing if digest |
| 339 | and size is already known. |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 340 | |
| 341 | Arguments: |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 342 | hash_algo: hash algorithm to use to calculate digest. |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 343 | """ |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 344 | if self.digest is None or self.size is None: |
| 345 | digest = hash_algo() |
| 346 | total = 0 |
| 347 | for chunk in self.content(): |
| 348 | digest.update(chunk) |
| 349 | total += len(chunk) |
| 350 | self.digest = digest.hexdigest() |
| 351 | self.size = total |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 352 | |
| 353 | |
| 354 | class FileItem(Item): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 355 | """A file to push to Storage. |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 356 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 357 | Its digest and size may be provided in advance, if known. Otherwise they will |
| 358 | be derived from the file content. |
| 359 | """ |
| 360 | |
| 361 | def __init__(self, path, digest=None, size=None, high_priority=False): |
| 362 | super(FileItem, self).__init__( |
| 363 | digest, |
| 364 | size if size is not None else os.stat(path).st_size, |
| 365 | high_priority) |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 366 | self.path = path |
| 367 | self.compression_level = get_zip_compression_level(path) |
| 368 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 369 | def content(self): |
| 370 | return file_read(self.path) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 371 | |
| 372 | |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 373 | class BufferItem(Item): |
| 374 | """A byte buffer to push to Storage.""" |
| 375 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 376 | def __init__(self, buf, high_priority=False): |
| 377 | super(BufferItem, self).__init__(None, len(buf), high_priority) |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 378 | self.buffer = buf |
| 379 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 380 | def content(self): |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 381 | return [self.buffer] |
| 382 | |
| 383 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 384 | class Storage(object): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 385 | """Efficiently downloads or uploads large set of files via StorageApi. |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 386 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 387 | Implements compression support, parallel 'contains' checks, parallel uploads |
| 388 | and more. |
| 389 | |
| 390 | Works only within single namespace (and thus hashing algorithm and compression |
| 391 | scheme are fixed). |
| 392 | |
| 393 | Spawns multiple internal threads. Thread safe, but not fork safe. |
| 394 | """ |
| 395 | |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 396 | def __init__(self, storage_api): |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 397 | self._storage_api = storage_api |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 398 | self._use_zip = is_namespace_with_compression(storage_api.namespace) |
| 399 | self._hash_algo = get_hash_algo(storage_api.namespace) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 400 | self._cpu_thread_pool = None |
| 401 | self._net_thread_pool = None |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 402 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 403 | @property |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 404 | def hash_algo(self): |
| 405 | """Hashing algorithm used to name files in storage based on their content. |
| 406 | |
| 407 | Defined by |namespace|. See also 'get_hash_algo'. |
| 408 | """ |
| 409 | return self._hash_algo |
| 410 | |
| 411 | @property |
| 412 | def location(self): |
| 413 | """Location of a backing store that this class is using. |
| 414 | |
| 415 | Exact meaning depends on the storage_api type. For IsolateServer it is |
| 416 | an URL of isolate server, for FileSystem is it a path in file system. |
| 417 | """ |
| 418 | return self._storage_api.location |
| 419 | |
| 420 | @property |
| 421 | def namespace(self): |
| 422 | """Isolate namespace used by this storage. |
| 423 | |
| 424 | Indirectly defines hashing scheme and compression method used. |
| 425 | """ |
| 426 | return self._storage_api.namespace |
| 427 | |
| 428 | @property |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 429 | def cpu_thread_pool(self): |
| 430 | """ThreadPool for CPU-bound tasks like zipping.""" |
| 431 | if self._cpu_thread_pool is None: |
| 432 | self._cpu_thread_pool = threading_utils.ThreadPool( |
| 433 | 2, max(threading_utils.num_processors(), 2), 0, 'zip') |
| 434 | return self._cpu_thread_pool |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 435 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 436 | @property |
| 437 | def net_thread_pool(self): |
| 438 | """AutoRetryThreadPool for IO-bound tasks, retries IOError.""" |
| 439 | if self._net_thread_pool is None: |
| 440 | self._net_thread_pool = WorkerPool() |
| 441 | return self._net_thread_pool |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 442 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 443 | def close(self): |
| 444 | """Waits for all pending tasks to finish.""" |
| 445 | if self._cpu_thread_pool: |
| 446 | self._cpu_thread_pool.join() |
| 447 | self._cpu_thread_pool.close() |
| 448 | self._cpu_thread_pool = None |
| 449 | if self._net_thread_pool: |
| 450 | self._net_thread_pool.join() |
| 451 | self._net_thread_pool.close() |
| 452 | self._net_thread_pool = None |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 453 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 454 | def __enter__(self): |
| 455 | """Context manager interface.""" |
| 456 | return self |
| 457 | |
| 458 | def __exit__(self, _exc_type, _exc_value, _traceback): |
| 459 | """Context manager interface.""" |
| 460 | self.close() |
| 461 | return False |
| 462 | |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 463 | def upload_items(self, items): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 464 | """Uploads a bunch of items to the isolate server. |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 465 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 466 | It figures out what items are missing from the server and uploads only them. |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 467 | |
| 468 | Arguments: |
| 469 | items: list of Item instances that represents data to upload. |
| 470 | |
| 471 | Returns: |
| 472 | List of items that were uploaded. All other items are already there. |
| 473 | """ |
| 474 | # TODO(vadimsh): Optimize special case of len(items) == 1 that is frequently |
| 475 | # used by swarming.py. There's no need to spawn multiple threads and try to |
| 476 | # do stuff in parallel: there's nothing to parallelize. 'contains' check and |
| 477 | # 'push' should be performed sequentially in the context of current thread. |
| 478 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 479 | # Ensure all digests are calculated. |
| 480 | for item in items: |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 481 | item.prepare(self._hash_algo) |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 482 | |
vadimsh@chromium.org | 672cd2b | 2013-10-08 17:49:33 +0000 | [diff] [blame] | 483 | # For each digest keep only first Item that matches it. All other items |
| 484 | # are just indistinguishable copies from the point of view of isolate |
| 485 | # server (it doesn't care about paths at all, only content and digests). |
| 486 | seen = {} |
| 487 | duplicates = 0 |
| 488 | for item in items: |
| 489 | if seen.setdefault(item.digest, item) is not item: |
| 490 | duplicates += 1 |
| 491 | items = seen.values() |
| 492 | if duplicates: |
| 493 | logging.info('Skipped %d duplicated files', duplicates) |
| 494 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 495 | # Enqueue all upload tasks. |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 496 | missing = set() |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 497 | uploaded = [] |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 498 | channel = threading_utils.TaskChannel() |
| 499 | for missing_item, push_state in self.get_missing_items(items): |
| 500 | missing.add(missing_item) |
| 501 | self.async_push(channel, missing_item, push_state) |
| 502 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 503 | # No need to spawn deadlock detector thread if there's nothing to upload. |
| 504 | if missing: |
| 505 | with threading_utils.DeadlockDetector(DEADLOCK_TIMEOUT) as detector: |
| 506 | # Wait for all started uploads to finish. |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 507 | while len(uploaded) != len(missing): |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 508 | detector.ping() |
| 509 | item = channel.pull() |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 510 | uploaded.append(item) |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 511 | logging.debug( |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 512 | 'Uploaded %d / %d: %s', len(uploaded), len(missing), item.digest) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 513 | logging.info('All files are uploaded') |
| 514 | |
| 515 | # Print stats. |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 516 | total = len(items) |
| 517 | total_size = sum(f.size for f in items) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 518 | logging.info( |
| 519 | 'Total: %6d, %9.1fkb', |
| 520 | total, |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 521 | total_size / 1024.) |
| 522 | cache_hit = set(items) - missing |
| 523 | cache_hit_size = sum(f.size for f in cache_hit) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 524 | logging.info( |
| 525 | 'cache hit: %6d, %9.1fkb, %6.2f%% files, %6.2f%% size', |
| 526 | len(cache_hit), |
| 527 | cache_hit_size / 1024., |
| 528 | len(cache_hit) * 100. / total, |
| 529 | cache_hit_size * 100. / total_size if total_size else 0) |
| 530 | cache_miss = missing |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 531 | cache_miss_size = sum(f.size for f in cache_miss) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 532 | logging.info( |
| 533 | 'cache miss: %6d, %9.1fkb, %6.2f%% files, %6.2f%% size', |
| 534 | len(cache_miss), |
| 535 | cache_miss_size / 1024., |
| 536 | len(cache_miss) * 100. / total, |
| 537 | cache_miss_size * 100. / total_size if total_size else 0) |
| 538 | |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 539 | return uploaded |
| 540 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 541 | def get_fetch_url(self, item): |
| 542 | """Returns an URL that can be used to fetch given item once it's uploaded. |
| 543 | |
| 544 | Note that if namespace uses compression, data at given URL is compressed. |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 545 | |
| 546 | Arguments: |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 547 | item: Item to get fetch URL for. |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 548 | |
| 549 | Returns: |
| 550 | An URL or None if underlying protocol doesn't support this. |
| 551 | """ |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 552 | item.prepare(self._hash_algo) |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 553 | return self._storage_api.get_fetch_url(item.digest) |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 554 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 555 | def async_push(self, channel, item, push_state): |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 556 | """Starts asynchronous push to the server in a parallel thread. |
| 557 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 558 | Can be used only after |item| was checked for presence on a server with |
| 559 | 'get_missing_items' call. 'get_missing_items' returns |push_state| object |
| 560 | that contains storage specific information describing how to upload |
| 561 | the item (for example in case of cloud storage, it is signed upload URLs). |
| 562 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 563 | Arguments: |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 564 | channel: TaskChannel that receives back |item| when upload ends. |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 565 | item: item to upload as instance of Item class. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 566 | push_state: push state returned by 'get_missing_items' call for |item|. |
| 567 | |
| 568 | Returns: |
| 569 | None, but |channel| later receives back |item| when upload ends. |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 570 | """ |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 571 | # Thread pool task priority. |
| 572 | priority = WorkerPool.HIGH if item.high_priority else WorkerPool.MED |
| 573 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 574 | def push(content): |
Marc-Antoine Ruel | 095a8be | 2014-03-21 14:58:19 -0400 | [diff] [blame] | 575 | """Pushes an Item and returns it to |channel|.""" |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 576 | item.prepare(self._hash_algo) |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 577 | self._storage_api.push(item, push_state, content) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 578 | return item |
| 579 | |
| 580 | # If zipping is not required, just start a push task. |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 581 | if not self._use_zip: |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 582 | self.net_thread_pool.add_task_with_channel( |
| 583 | channel, priority, push, item.content()) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 584 | return |
| 585 | |
| 586 | # If zipping is enabled, zip in a separate thread. |
| 587 | def zip_and_push(): |
| 588 | # TODO(vadimsh): Implement streaming uploads. Before it's done, assemble |
| 589 | # content right here. It will block until all file is zipped. |
| 590 | try: |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 591 | stream = zip_compress(item.content(), item.compression_level) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 592 | data = ''.join(stream) |
| 593 | except Exception as exc: |
| 594 | logging.error('Failed to zip \'%s\': %s', item, exc) |
Vadim Shtayura | 0ffc409 | 2013-11-20 17:49:52 -0800 | [diff] [blame] | 595 | channel.send_exception() |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 596 | return |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 597 | self.net_thread_pool.add_task_with_channel( |
| 598 | channel, priority, push, [data]) |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 599 | self.cpu_thread_pool.add_task(priority, zip_and_push) |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 600 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 601 | def push(self, item, push_state): |
| 602 | """Synchronously pushes a single item to the server. |
| 603 | |
| 604 | If you need to push many items at once, consider using 'upload_items' or |
| 605 | 'async_push' with instance of TaskChannel. |
| 606 | |
| 607 | Arguments: |
| 608 | item: item to upload as instance of Item class. |
| 609 | push_state: push state returned by 'get_missing_items' call for |item|. |
| 610 | |
| 611 | Returns: |
| 612 | Pushed item (same object as |item|). |
| 613 | """ |
| 614 | channel = threading_utils.TaskChannel() |
| 615 | with threading_utils.DeadlockDetector(DEADLOCK_TIMEOUT): |
| 616 | self.async_push(channel, item, push_state) |
| 617 | pushed = channel.pull() |
| 618 | assert pushed is item |
| 619 | return item |
| 620 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 621 | def async_fetch(self, channel, priority, digest, size, sink): |
| 622 | """Starts asynchronous fetch from the server in a parallel thread. |
| 623 | |
| 624 | Arguments: |
| 625 | channel: TaskChannel that receives back |digest| when download ends. |
| 626 | priority: thread pool task priority for the fetch. |
| 627 | digest: hex digest of an item to download. |
| 628 | size: expected size of the item (after decompression). |
| 629 | sink: function that will be called as sink(generator). |
| 630 | """ |
| 631 | def fetch(): |
| 632 | try: |
| 633 | # Prepare reading pipeline. |
| 634 | stream = self._storage_api.fetch(digest) |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 635 | if self._use_zip: |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 636 | stream = zip_decompress(stream, DISK_FILE_CHUNK) |
| 637 | # Run |stream| through verifier that will assert its size. |
| 638 | verifier = FetchStreamVerifier(stream, size) |
| 639 | # Verified stream goes to |sink|. |
| 640 | sink(verifier.run()) |
| 641 | except Exception as err: |
Vadim Shtayura | 0ffc409 | 2013-11-20 17:49:52 -0800 | [diff] [blame] | 642 | logging.error('Failed to fetch %s: %s', digest, err) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 643 | raise |
| 644 | return digest |
| 645 | |
| 646 | # Don't bother with zip_thread_pool for decompression. Decompression is |
| 647 | # really fast and most probably IO bound anyway. |
| 648 | self.net_thread_pool.add_task_with_channel(channel, priority, fetch) |
| 649 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 650 | def get_missing_items(self, items): |
| 651 | """Yields items that are missing from the server. |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 652 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 653 | Issues multiple parallel queries via StorageApi's 'contains' method. |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 654 | |
| 655 | Arguments: |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 656 | items: a list of Item objects to check. |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 657 | |
| 658 | Yields: |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 659 | For each missing item it yields a pair (item, push_state), where: |
| 660 | * item - Item object that is missing (one of |items|). |
| 661 | * push_state - opaque object that contains storage specific information |
| 662 | describing how to upload the item (for example in case of cloud |
| 663 | storage, it is signed upload URLs). It can later be passed to |
| 664 | 'async_push'. |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 665 | """ |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 666 | channel = threading_utils.TaskChannel() |
| 667 | pending = 0 |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 668 | |
| 669 | # Ensure all digests are calculated. |
| 670 | for item in items: |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 671 | item.prepare(self._hash_algo) |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 672 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 673 | # Enqueue all requests. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 674 | for batch in batch_items_for_check(items): |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 675 | self.net_thread_pool.add_task_with_channel(channel, WorkerPool.HIGH, |
| 676 | self._storage_api.contains, batch) |
| 677 | pending += 1 |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 678 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 679 | # Yield results as they come in. |
| 680 | for _ in xrange(pending): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 681 | for missing_item, push_state in channel.pull().iteritems(): |
| 682 | yield missing_item, push_state |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 683 | |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 684 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 685 | def batch_items_for_check(items): |
| 686 | """Splits list of items to check for existence on the server into batches. |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 687 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 688 | Each batch corresponds to a single 'exists?' query to the server via a call |
| 689 | to StorageApi's 'contains' method. |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 690 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 691 | Arguments: |
| 692 | items: a list of Item objects. |
| 693 | |
| 694 | Yields: |
| 695 | Batches of items to query for existence in a single operation, |
| 696 | each batch is a list of Item objects. |
| 697 | """ |
| 698 | batch_count = 0 |
| 699 | batch_size_limit = ITEMS_PER_CONTAINS_QUERIES[0] |
| 700 | next_queries = [] |
| 701 | for item in sorted(items, key=lambda x: x.size, reverse=True): |
| 702 | next_queries.append(item) |
| 703 | if len(next_queries) == batch_size_limit: |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 704 | yield next_queries |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 705 | next_queries = [] |
| 706 | batch_count += 1 |
| 707 | batch_size_limit = ITEMS_PER_CONTAINS_QUERIES[ |
| 708 | min(batch_count, len(ITEMS_PER_CONTAINS_QUERIES) - 1)] |
| 709 | if next_queries: |
| 710 | yield next_queries |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 711 | |
| 712 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 713 | class FetchQueue(object): |
| 714 | """Fetches items from Storage and places them into LocalCache. |
| 715 | |
| 716 | It manages multiple concurrent fetch operations. Acts as a bridge between |
| 717 | Storage and LocalCache so that Storage and LocalCache don't depend on each |
| 718 | other at all. |
| 719 | """ |
| 720 | |
| 721 | def __init__(self, storage, cache): |
| 722 | self.storage = storage |
| 723 | self.cache = cache |
| 724 | self._channel = threading_utils.TaskChannel() |
| 725 | self._pending = set() |
| 726 | self._accessed = set() |
| 727 | self._fetched = cache.cached_set() |
| 728 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 729 | def add(self, digest, size=UNKNOWN_FILE_SIZE, priority=WorkerPool.MED): |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 730 | """Starts asynchronous fetch of item |digest|.""" |
| 731 | # Fetching it now? |
| 732 | if digest in self._pending: |
| 733 | return |
| 734 | |
| 735 | # Mark this file as in use, verify_all_cached will later ensure it is still |
| 736 | # in cache. |
| 737 | self._accessed.add(digest) |
| 738 | |
| 739 | # Already fetched? Notify cache to update item's LRU position. |
| 740 | if digest in self._fetched: |
| 741 | # 'touch' returns True if item is in cache and not corrupted. |
| 742 | if self.cache.touch(digest, size): |
| 743 | return |
| 744 | # Item is corrupted, remove it from cache and fetch it again. |
| 745 | self._fetched.remove(digest) |
| 746 | self.cache.evict(digest) |
| 747 | |
| 748 | # TODO(maruel): It should look at the free disk space, the current cache |
| 749 | # size and the size of the new item on every new item: |
| 750 | # - Trim the cache as more entries are listed when free disk space is low, |
| 751 | # otherwise if the amount of data downloaded during the run > free disk |
| 752 | # space, it'll crash. |
| 753 | # - Make sure there's enough free disk space to fit all dependencies of |
| 754 | # this run! If not, abort early. |
| 755 | |
| 756 | # Start fetching. |
| 757 | self._pending.add(digest) |
| 758 | self.storage.async_fetch( |
| 759 | self._channel, priority, digest, size, |
| 760 | functools.partial(self.cache.write, digest)) |
| 761 | |
| 762 | def wait(self, digests): |
| 763 | """Starts a loop that waits for at least one of |digests| to be retrieved. |
| 764 | |
| 765 | Returns the first digest retrieved. |
| 766 | """ |
| 767 | # Flush any already fetched items. |
| 768 | for digest in digests: |
| 769 | if digest in self._fetched: |
| 770 | return digest |
| 771 | |
| 772 | # Ensure all requested items are being fetched now. |
| 773 | assert all(digest in self._pending for digest in digests), ( |
| 774 | digests, self._pending) |
| 775 | |
| 776 | # Wait for some requested item to finish fetching. |
| 777 | while self._pending: |
| 778 | digest = self._channel.pull() |
| 779 | self._pending.remove(digest) |
| 780 | self._fetched.add(digest) |
| 781 | if digest in digests: |
| 782 | return digest |
| 783 | |
| 784 | # Should never reach this point due to assert above. |
| 785 | raise RuntimeError('Impossible state') |
| 786 | |
| 787 | def inject_local_file(self, path, algo): |
| 788 | """Adds local file to the cache as if it was fetched from storage.""" |
| 789 | with open(path, 'rb') as f: |
| 790 | data = f.read() |
| 791 | digest = algo(data).hexdigest() |
| 792 | self.cache.write(digest, [data]) |
| 793 | self._fetched.add(digest) |
| 794 | return digest |
| 795 | |
| 796 | @property |
| 797 | def pending_count(self): |
| 798 | """Returns number of items to be fetched.""" |
| 799 | return len(self._pending) |
| 800 | |
| 801 | def verify_all_cached(self): |
| 802 | """True if all accessed items are in cache.""" |
| 803 | return self._accessed.issubset(self.cache.cached_set()) |
| 804 | |
| 805 | |
| 806 | class FetchStreamVerifier(object): |
| 807 | """Verifies that fetched file is valid before passing it to the LocalCache.""" |
| 808 | |
| 809 | def __init__(self, stream, expected_size): |
| 810 | self.stream = stream |
| 811 | self.expected_size = expected_size |
| 812 | self.current_size = 0 |
| 813 | |
| 814 | def run(self): |
| 815 | """Generator that yields same items as |stream|. |
| 816 | |
| 817 | Verifies |stream| is complete before yielding a last chunk to consumer. |
| 818 | |
| 819 | Also wraps IOError produced by consumer into MappingError exceptions since |
| 820 | otherwise Storage will retry fetch on unrelated local cache errors. |
| 821 | """ |
| 822 | # Read one chunk ahead, keep it in |stored|. |
| 823 | # That way a complete stream can be verified before pushing last chunk |
| 824 | # to consumer. |
| 825 | stored = None |
| 826 | for chunk in self.stream: |
| 827 | assert chunk is not None |
| 828 | if stored is not None: |
| 829 | self._inspect_chunk(stored, is_last=False) |
| 830 | try: |
| 831 | yield stored |
| 832 | except IOError as exc: |
| 833 | raise MappingError('Failed to store an item in cache: %s' % exc) |
| 834 | stored = chunk |
| 835 | if stored is not None: |
| 836 | self._inspect_chunk(stored, is_last=True) |
| 837 | try: |
| 838 | yield stored |
| 839 | except IOError as exc: |
| 840 | raise MappingError('Failed to store an item in cache: %s' % exc) |
| 841 | |
| 842 | def _inspect_chunk(self, chunk, is_last): |
| 843 | """Called for each fetched chunk before passing it to consumer.""" |
| 844 | self.current_size += len(chunk) |
| 845 | if (is_last and (self.expected_size != UNKNOWN_FILE_SIZE) and |
| 846 | (self.expected_size != self.current_size)): |
| 847 | raise IOError('Incorrect file size: expected %d, got %d' % ( |
| 848 | self.expected_size, self.current_size)) |
| 849 | |
| 850 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 851 | class StorageApi(object): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 852 | """Interface for classes that implement low-level storage operations. |
| 853 | |
| 854 | StorageApi is oblivious of compression and hashing scheme used. This details |
| 855 | are handled in higher level Storage class. |
| 856 | |
| 857 | Clients should generally not use StorageApi directly. Storage class is |
| 858 | preferred since it implements compression and upload optimizations. |
| 859 | """ |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 860 | |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 861 | @property |
| 862 | def location(self): |
| 863 | """Location of a backing store that this class is using. |
| 864 | |
| 865 | Exact meaning depends on the type. For IsolateServer it is an URL of isolate |
| 866 | server, for FileSystem is it a path in file system. |
| 867 | """ |
| 868 | raise NotImplementedError() |
| 869 | |
| 870 | @property |
| 871 | def namespace(self): |
| 872 | """Isolate namespace used by this storage. |
| 873 | |
| 874 | Indirectly defines hashing scheme and compression method used. |
| 875 | """ |
| 876 | raise NotImplementedError() |
| 877 | |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 878 | def get_fetch_url(self, digest): |
| 879 | """Returns an URL that can be used to fetch an item with given digest. |
| 880 | |
| 881 | Arguments: |
| 882 | digest: hex digest of item to fetch. |
| 883 | |
| 884 | Returns: |
| 885 | An URL or None if the protocol doesn't support this. |
| 886 | """ |
| 887 | raise NotImplementedError() |
| 888 | |
Vadim Shtayura | f0cb97a | 2013-12-05 13:57:49 -0800 | [diff] [blame] | 889 | def fetch(self, digest, offset=0): |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 890 | """Fetches an object and yields its content. |
| 891 | |
| 892 | Arguments: |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 893 | digest: hash digest of item to download. |
Vadim Shtayura | f0cb97a | 2013-12-05 13:57:49 -0800 | [diff] [blame] | 894 | offset: offset (in bytes) from the start of the file to resume fetch from. |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 895 | |
| 896 | Yields: |
| 897 | Chunks of downloaded item (as str objects). |
| 898 | """ |
| 899 | raise NotImplementedError() |
| 900 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 901 | def push(self, item, push_state, content=None): |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 902 | """Uploads an |item| with content generated by |content| generator. |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 903 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 904 | |item| MUST go through 'contains' call to get |push_state| before it can |
| 905 | be pushed to the storage. |
| 906 | |
| 907 | To be clear, here is one possible usage: |
| 908 | all_items = [... all items to push as Item subclasses ...] |
| 909 | for missing_item, push_state in storage_api.contains(all_items).items(): |
| 910 | storage_api.push(missing_item, push_state) |
| 911 | |
| 912 | When pushing to a namespace with compression, data that should be pushed |
| 913 | and data provided by the item is not the same. In that case |content| is |
| 914 | not None and it yields chunks of compressed data (using item.content() as |
| 915 | a source of original uncompressed data). This is implemented by Storage |
| 916 | class. |
| 917 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 918 | Arguments: |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 919 | item: Item object that holds information about an item being pushed. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 920 | push_state: push state object as returned by 'contains' call. |
| 921 | content: a generator that yields chunks to push, item.content() if None. |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 922 | |
| 923 | Returns: |
| 924 | None. |
| 925 | """ |
| 926 | raise NotImplementedError() |
| 927 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 928 | def contains(self, items): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 929 | """Checks for |items| on the server, prepares missing ones for upload. |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 930 | |
| 931 | Arguments: |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 932 | items: list of Item objects to check for presence. |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 933 | |
| 934 | Returns: |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 935 | A dict missing Item -> opaque push state object to be passed to 'push'. |
| 936 | See doc string for 'push'. |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 937 | """ |
| 938 | raise NotImplementedError() |
| 939 | |
| 940 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 941 | class _IsolateServerPushState(object): |
| 942 | """Per-item state passed from IsolateServer.contains to IsolateServer.push. |
Mike Frysinger | 27f03da | 2014-02-12 16:47:01 -0500 | [diff] [blame] | 943 | |
| 944 | Note this needs to be a global class to support pickling. |
| 945 | """ |
| 946 | |
| 947 | def __init__(self, upload_url, finalize_url): |
| 948 | self.upload_url = upload_url |
| 949 | self.finalize_url = finalize_url |
| 950 | self.uploaded = False |
| 951 | self.finalized = False |
| 952 | |
| 953 | |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 954 | class IsolateServer(StorageApi): |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 955 | """StorageApi implementation that downloads and uploads to Isolate Server. |
| 956 | |
| 957 | It uploads and downloads directly from Google Storage whenever appropriate. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 958 | Works only within single namespace. |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 959 | """ |
| 960 | |
maruel@chromium.org | 3e42ce8 | 2013-09-12 18:36:59 +0000 | [diff] [blame] | 961 | def __init__(self, base_url, namespace): |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 962 | super(IsolateServer, self).__init__() |
maruel@chromium.org | 3e42ce8 | 2013-09-12 18:36:59 +0000 | [diff] [blame] | 963 | assert base_url.startswith('http'), base_url |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 964 | self._base_url = base_url.rstrip('/') |
| 965 | self._namespace = namespace |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 966 | self._lock = threading.Lock() |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 967 | self._server_caps = None |
| 968 | |
| 969 | @staticmethod |
| 970 | def _generate_handshake_request(): |
| 971 | """Returns a dict to be sent as handshake request body.""" |
| 972 | # TODO(vadimsh): Set 'pusher' and 'fetcher' according to intended usage. |
| 973 | return { |
| 974 | 'client_app_version': __version__, |
| 975 | 'fetcher': True, |
| 976 | 'protocol_version': ISOLATE_PROTOCOL_VERSION, |
| 977 | 'pusher': True, |
| 978 | } |
| 979 | |
| 980 | @staticmethod |
| 981 | def _validate_handshake_response(caps): |
| 982 | """Validates and normalizes handshake response.""" |
| 983 | logging.info('Protocol version: %s', caps['protocol_version']) |
| 984 | logging.info('Server version: %s', caps['server_app_version']) |
| 985 | if caps.get('error'): |
| 986 | raise MappingError(caps['error']) |
| 987 | if not caps['access_token']: |
| 988 | raise ValueError('access_token is missing') |
| 989 | return caps |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 990 | |
| 991 | @property |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 992 | def _server_capabilities(self): |
| 993 | """Performs handshake with the server if not yet done. |
| 994 | |
| 995 | Returns: |
| 996 | Server capabilities dictionary as returned by /handshake endpoint. |
| 997 | |
| 998 | Raises: |
| 999 | MappingError if server rejects the handshake. |
| 1000 | """ |
maruel@chromium.org | 3e42ce8 | 2013-09-12 18:36:59 +0000 | [diff] [blame] | 1001 | # TODO(maruel): Make this request much earlier asynchronously while the |
| 1002 | # files are being enumerated. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1003 | |
| 1004 | # TODO(vadimsh): Put |namespace| in the URL so that server can apply |
| 1005 | # namespace-level ACLs to this call. |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 1006 | with self._lock: |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1007 | if self._server_caps is None: |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1008 | try: |
Marc-Antoine Ruel | 0a62061 | 2014-08-13 15:47:07 -0400 | [diff] [blame^] | 1009 | caps = net.url_read_json( |
| 1010 | url=self._base_url + '/content-gs/handshake', |
| 1011 | data=self._generate_handshake_request()) |
| 1012 | if caps is None: |
| 1013 | raise MappingError('Failed to perform handshake.') |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1014 | if not isinstance(caps, dict): |
| 1015 | raise ValueError('Expecting JSON dict') |
| 1016 | self._server_caps = self._validate_handshake_response(caps) |
| 1017 | except (ValueError, KeyError, TypeError) as exc: |
| 1018 | # KeyError exception has very confusing str conversion: it's just a |
| 1019 | # missing key value and nothing else. So print exception class name |
| 1020 | # as well. |
| 1021 | raise MappingError('Invalid handshake response (%s): %s' % ( |
| 1022 | exc.__class__.__name__, exc)) |
| 1023 | return self._server_caps |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 1024 | |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 1025 | @property |
| 1026 | def location(self): |
| 1027 | return self._base_url |
| 1028 | |
| 1029 | @property |
| 1030 | def namespace(self): |
| 1031 | return self._namespace |
| 1032 | |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 1033 | def get_fetch_url(self, digest): |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1034 | assert isinstance(digest, basestring) |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 1035 | return '%s/content-gs/retrieve/%s/%s' % ( |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 1036 | self._base_url, self._namespace, digest) |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 1037 | |
Vadim Shtayura | f0cb97a | 2013-12-05 13:57:49 -0800 | [diff] [blame] | 1038 | def fetch(self, digest, offset=0): |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 1039 | source_url = self.get_fetch_url(digest) |
Vadim Shtayura | f0cb97a | 2013-12-05 13:57:49 -0800 | [diff] [blame] | 1040 | logging.debug('download_file(%s, %d)', source_url, offset) |
maruel@chromium.org | e45728d | 2013-09-16 23:23:22 +0000 | [diff] [blame] | 1041 | |
maruel@chromium.org | e45728d | 2013-09-16 23:23:22 +0000 | [diff] [blame] | 1042 | connection = net.url_open( |
Vadim Shtayura | f0cb97a | 2013-12-05 13:57:49 -0800 | [diff] [blame] | 1043 | source_url, |
Vadim Shtayura | f0cb97a | 2013-12-05 13:57:49 -0800 | [diff] [blame] | 1044 | read_timeout=DOWNLOAD_READ_TIMEOUT, |
| 1045 | headers={'Range': 'bytes=%d-' % offset} if offset else None) |
| 1046 | |
maruel@chromium.org | e45728d | 2013-09-16 23:23:22 +0000 | [diff] [blame] | 1047 | if not connection: |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 1048 | raise IOError('Request failed - %s' % source_url) |
Vadim Shtayura | f0cb97a | 2013-12-05 13:57:49 -0800 | [diff] [blame] | 1049 | |
| 1050 | # If |offset| is used, verify server respects it by checking Content-Range. |
| 1051 | if offset: |
| 1052 | content_range = connection.get_header('Content-Range') |
| 1053 | if not content_range: |
| 1054 | raise IOError('Missing Content-Range header') |
| 1055 | |
| 1056 | # 'Content-Range' format is 'bytes <offset>-<last_byte_index>/<size>'. |
| 1057 | # According to a spec, <size> can be '*' meaning "Total size of the file |
| 1058 | # is not known in advance". |
| 1059 | try: |
| 1060 | match = re.match(r'bytes (\d+)-(\d+)/(\d+|\*)', content_range) |
| 1061 | if not match: |
| 1062 | raise ValueError() |
| 1063 | content_offset = int(match.group(1)) |
| 1064 | last_byte_index = int(match.group(2)) |
| 1065 | size = None if match.group(3) == '*' else int(match.group(3)) |
| 1066 | except ValueError: |
| 1067 | raise IOError('Invalid Content-Range header: %s' % content_range) |
| 1068 | |
| 1069 | # Ensure returned offset equals requested one. |
| 1070 | if offset != content_offset: |
| 1071 | raise IOError('Expecting offset %d, got %d (Content-Range is %s)' % ( |
| 1072 | offset, content_offset, content_range)) |
| 1073 | |
| 1074 | # Ensure entire tail of the file is returned. |
| 1075 | if size is not None and last_byte_index + 1 != size: |
| 1076 | raise IOError('Incomplete response. Content-Range: %s' % content_range) |
| 1077 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1078 | return stream_read(connection, NET_IO_FILE_CHUNK) |
maruel@chromium.org | e45728d | 2013-09-16 23:23:22 +0000 | [diff] [blame] | 1079 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1080 | def push(self, item, push_state, content=None): |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1081 | assert isinstance(item, Item) |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1082 | assert item.digest is not None |
| 1083 | assert item.size is not None |
| 1084 | assert isinstance(push_state, _IsolateServerPushState) |
| 1085 | assert not push_state.finalized |
| 1086 | |
| 1087 | # Default to item.content(). |
| 1088 | content = item.content() if content is None else content |
| 1089 | |
| 1090 | # Do not iterate byte by byte over 'str'. Push it all as a single chunk. |
| 1091 | if isinstance(content, basestring): |
| 1092 | assert not isinstance(content, unicode), 'Unicode string is not allowed' |
| 1093 | content = [content] |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 1094 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1095 | # TODO(vadimsh): Do not read from |content| generator when retrying push. |
| 1096 | # If |content| is indeed a generator, it can not be re-winded back |
| 1097 | # to the beginning of the stream. A retry will find it exhausted. A possible |
| 1098 | # solution is to wrap |content| generator with some sort of caching |
| 1099 | # restartable generator. It should be done alongside streaming support |
| 1100 | # implementation. |
| 1101 | |
| 1102 | # This push operation may be a retry after failed finalization call below, |
| 1103 | # no need to reupload contents in that case. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1104 | if not push_state.uploaded: |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1105 | # A cheezy way to avoid memcpy of (possibly huge) file, until streaming |
| 1106 | # upload support is implemented. |
| 1107 | if isinstance(content, list) and len(content) == 1: |
| 1108 | content = content[0] |
| 1109 | else: |
| 1110 | content = ''.join(content) |
| 1111 | # PUT file to |upload_url|. |
| 1112 | response = net.url_read( |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1113 | url=push_state.upload_url, |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1114 | data=content, |
| 1115 | content_type='application/octet-stream', |
| 1116 | method='PUT') |
| 1117 | if response is None: |
| 1118 | raise IOError('Failed to upload a file %s to %s' % ( |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1119 | item.digest, push_state.upload_url)) |
| 1120 | push_state.uploaded = True |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 1121 | else: |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1122 | logging.info( |
| 1123 | 'A file %s already uploaded, retrying finalization only', item.digest) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 1124 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1125 | # Optionally notify the server that it's done. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1126 | if push_state.finalize_url: |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1127 | # TODO(vadimsh): Calculate MD5 or CRC32C sum while uploading a file and |
| 1128 | # send it to isolated server. That way isolate server can verify that |
| 1129 | # the data safely reached Google Storage (GS provides MD5 and CRC32C of |
| 1130 | # stored files). |
Marc-Antoine Ruel | 0a62061 | 2014-08-13 15:47:07 -0400 | [diff] [blame^] | 1131 | response = net.url_read_json(url=push_state.finalize_url, data={}) |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1132 | if response is None: |
| 1133 | raise IOError('Failed to finalize an upload of %s' % item.digest) |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1134 | push_state.finalized = True |
maruel@chromium.org | d1e20c9 | 2013-09-17 20:54:26 +0000 | [diff] [blame] | 1135 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1136 | def contains(self, items): |
| 1137 | logging.info('Checking existence of %d files...', len(items)) |
maruel@chromium.org | d1e20c9 | 2013-09-17 20:54:26 +0000 | [diff] [blame] | 1138 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1139 | # Ensure all items were initialized with 'prepare' call. Storage does that. |
| 1140 | assert all(i.digest is not None and i.size is not None for i in items) |
| 1141 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1142 | # Request body is a json encoded list of dicts. |
| 1143 | body = [ |
| 1144 | { |
| 1145 | 'h': item.digest, |
| 1146 | 's': item.size, |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1147 | 'i': int(item.high_priority), |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1148 | } for item in items |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 1149 | ] |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1150 | |
| 1151 | query_url = '%s/content-gs/pre-upload/%s?token=%s' % ( |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 1152 | self._base_url, |
| 1153 | self._namespace, |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1154 | urllib.quote(self._server_capabilities['access_token'])) |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1155 | |
| 1156 | # Response body is a list of push_urls (or null if file is already present). |
Marc-Antoine Ruel | 0a62061 | 2014-08-13 15:47:07 -0400 | [diff] [blame^] | 1157 | response = None |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1158 | try: |
Marc-Antoine Ruel | 0a62061 | 2014-08-13 15:47:07 -0400 | [diff] [blame^] | 1159 | response = net.url_read_json(url=query_url, data=body) |
| 1160 | if response is None: |
| 1161 | raise MappingError('Failed to execute /pre-upload query') |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1162 | if not isinstance(response, list): |
| 1163 | raise ValueError('Expecting response with json-encoded list') |
| 1164 | if len(response) != len(items): |
| 1165 | raise ValueError( |
| 1166 | 'Incorrect number of items in the list, expected %d, ' |
| 1167 | 'but got %d' % (len(items), len(response))) |
| 1168 | except ValueError as err: |
| 1169 | raise MappingError( |
Marc-Antoine Ruel | 0a62061 | 2014-08-13 15:47:07 -0400 | [diff] [blame^] | 1170 | 'Invalid response from server: %s, body is %s' % (err, response)) |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1171 | |
| 1172 | # Pick Items that are missing, attach _PushState to them. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1173 | missing_items = {} |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1174 | for i, push_urls in enumerate(response): |
| 1175 | if push_urls: |
| 1176 | assert len(push_urls) == 2, str(push_urls) |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1177 | missing_items[items[i]] = _IsolateServerPushState( |
| 1178 | push_urls[0], push_urls[1]) |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 1179 | logging.info('Queried %d files, %d cache hit', |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1180 | len(items), len(items) - len(missing_items)) |
| 1181 | return missing_items |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 1182 | |
| 1183 | |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 1184 | class FileSystem(StorageApi): |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 1185 | """StorageApi implementation that fetches data from the file system. |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 1186 | |
| 1187 | The common use case is a NFS/CIFS file server that is mounted locally that is |
| 1188 | used to fetch the file on a local partition. |
| 1189 | """ |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1190 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1191 | # Used for push_state instead of None. That way caller is forced to |
| 1192 | # call 'contains' before 'push'. Naively passing None in 'push' will not work. |
| 1193 | _DUMMY_PUSH_STATE = object() |
| 1194 | |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 1195 | def __init__(self, base_path, namespace): |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 1196 | super(FileSystem, self).__init__() |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 1197 | self._base_path = base_path |
| 1198 | self._namespace = namespace |
| 1199 | |
| 1200 | @property |
| 1201 | def location(self): |
| 1202 | return self._base_path |
| 1203 | |
| 1204 | @property |
| 1205 | def namespace(self): |
| 1206 | return self._namespace |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 1207 | |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 1208 | def get_fetch_url(self, digest): |
| 1209 | return None |
| 1210 | |
Vadim Shtayura | f0cb97a | 2013-12-05 13:57:49 -0800 | [diff] [blame] | 1211 | def fetch(self, digest, offset=0): |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1212 | assert isinstance(digest, basestring) |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 1213 | return file_read(os.path.join(self._base_path, digest), offset=offset) |
maruel@chromium.org | e45728d | 2013-09-16 23:23:22 +0000 | [diff] [blame] | 1214 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1215 | def push(self, item, push_state, content=None): |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1216 | assert isinstance(item, Item) |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1217 | assert item.digest is not None |
| 1218 | assert item.size is not None |
| 1219 | assert push_state is self._DUMMY_PUSH_STATE |
| 1220 | content = item.content() if content is None else content |
| 1221 | if isinstance(content, basestring): |
| 1222 | assert not isinstance(content, unicode), 'Unicode string is not allowed' |
| 1223 | content = [content] |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 1224 | file_write(os.path.join(self._base_path, item.digest), content) |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 1225 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1226 | def contains(self, items): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1227 | assert all(i.digest is not None and i.size is not None for i in items) |
| 1228 | return dict( |
| 1229 | (item, self._DUMMY_PUSH_STATE) for item in items |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 1230 | if not os.path.exists(os.path.join(self._base_path, item.digest)) |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1231 | ) |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 1232 | |
| 1233 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1234 | class LocalCache(object): |
| 1235 | """Local cache that stores objects fetched via Storage. |
| 1236 | |
| 1237 | It can be accessed concurrently from multiple threads, so it should protect |
| 1238 | its internal state with some lock. |
| 1239 | """ |
Marc-Antoine Ruel | 2283ad1 | 2014-02-09 11:14:57 -0500 | [diff] [blame] | 1240 | cache_dir = None |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1241 | |
| 1242 | def __enter__(self): |
| 1243 | """Context manager interface.""" |
| 1244 | return self |
| 1245 | |
| 1246 | def __exit__(self, _exc_type, _exec_value, _traceback): |
| 1247 | """Context manager interface.""" |
| 1248 | return False |
| 1249 | |
| 1250 | def cached_set(self): |
| 1251 | """Returns a set of all cached digests (always a new object).""" |
| 1252 | raise NotImplementedError() |
| 1253 | |
| 1254 | def touch(self, digest, size): |
| 1255 | """Ensures item is not corrupted and updates its LRU position. |
| 1256 | |
| 1257 | Arguments: |
| 1258 | digest: hash digest of item to check. |
| 1259 | size: expected size of this item. |
| 1260 | |
| 1261 | Returns: |
| 1262 | True if item is in cache and not corrupted. |
| 1263 | """ |
| 1264 | raise NotImplementedError() |
| 1265 | |
| 1266 | def evict(self, digest): |
| 1267 | """Removes item from cache if it's there.""" |
| 1268 | raise NotImplementedError() |
| 1269 | |
| 1270 | def read(self, digest): |
| 1271 | """Returns contents of the cached item as a single str.""" |
| 1272 | raise NotImplementedError() |
| 1273 | |
| 1274 | def write(self, digest, content): |
| 1275 | """Reads data from |content| generator and stores it in cache.""" |
| 1276 | raise NotImplementedError() |
| 1277 | |
Marc-Antoine Ruel | fb199cf | 2013-11-12 15:38:12 -0500 | [diff] [blame] | 1278 | def hardlink(self, digest, dest, file_mode): |
| 1279 | """Ensures file at |dest| has same content as cached |digest|. |
| 1280 | |
| 1281 | If file_mode is provided, it is used to set the executable bit if |
| 1282 | applicable. |
| 1283 | """ |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1284 | raise NotImplementedError() |
| 1285 | |
| 1286 | |
| 1287 | class MemoryCache(LocalCache): |
| 1288 | """LocalCache implementation that stores everything in memory.""" |
| 1289 | |
Vadim Shtayura | e3fbd10 | 2014-04-29 17:05:21 -0700 | [diff] [blame] | 1290 | def __init__(self, file_mode_mask=0500): |
| 1291 | """Args: |
| 1292 | file_mode_mask: bit mask to AND file mode with. Default value will make |
| 1293 | all mapped files to be read only. |
| 1294 | """ |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1295 | super(MemoryCache, self).__init__() |
Vadim Shtayura | e3fbd10 | 2014-04-29 17:05:21 -0700 | [diff] [blame] | 1296 | self._file_mode_mask = file_mode_mask |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1297 | # Let's not assume dict is thread safe. |
| 1298 | self._lock = threading.Lock() |
| 1299 | self._contents = {} |
| 1300 | |
| 1301 | def cached_set(self): |
| 1302 | with self._lock: |
| 1303 | return set(self._contents) |
| 1304 | |
| 1305 | def touch(self, digest, size): |
| 1306 | with self._lock: |
| 1307 | return digest in self._contents |
| 1308 | |
| 1309 | def evict(self, digest): |
| 1310 | with self._lock: |
| 1311 | self._contents.pop(digest, None) |
| 1312 | |
| 1313 | def read(self, digest): |
| 1314 | with self._lock: |
| 1315 | return self._contents[digest] |
| 1316 | |
| 1317 | def write(self, digest, content): |
| 1318 | # Assemble whole stream before taking the lock. |
| 1319 | data = ''.join(content) |
| 1320 | with self._lock: |
| 1321 | self._contents[digest] = data |
| 1322 | |
Marc-Antoine Ruel | fb199cf | 2013-11-12 15:38:12 -0500 | [diff] [blame] | 1323 | def hardlink(self, digest, dest, file_mode): |
| 1324 | """Since data is kept in memory, there is no filenode to hardlink.""" |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1325 | file_write(dest, [self.read(digest)]) |
Marc-Antoine Ruel | fb199cf | 2013-11-12 15:38:12 -0500 | [diff] [blame] | 1326 | if file_mode is not None: |
Vadim Shtayura | e3fbd10 | 2014-04-29 17:05:21 -0700 | [diff] [blame] | 1327 | os.chmod(dest, file_mode & self._file_mode_mask) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1328 | |
| 1329 | |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 1330 | def get_hash_algo(_namespace): |
| 1331 | """Return hash algorithm class to use when uploading to given |namespace|.""" |
| 1332 | # TODO(vadimsh): Implement this at some point. |
| 1333 | return hashlib.sha1 |
| 1334 | |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 1335 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 1336 | def is_namespace_with_compression(namespace): |
| 1337 | """Returns True if given |namespace| stores compressed objects.""" |
| 1338 | return namespace.endswith(('-gzip', '-deflate')) |
| 1339 | |
| 1340 | |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 1341 | def get_storage_api(file_or_url, namespace): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1342 | """Returns an object that implements low-level StorageApi interface. |
| 1343 | |
| 1344 | It is used by Storage to work with single isolate |namespace|. It should |
| 1345 | rarely be used directly by clients, see 'get_storage' for |
| 1346 | a better alternative. |
| 1347 | |
| 1348 | Arguments: |
| 1349 | file_or_url: a file path to use file system based storage, or URL of isolate |
| 1350 | service to use shared cloud based storage. |
| 1351 | namespace: isolate namespace to operate in, also defines hashing and |
| 1352 | compression scheme used, i.e. namespace names that end with '-gzip' |
| 1353 | store compressed data. |
| 1354 | |
| 1355 | Returns: |
| 1356 | Instance of StorageApi subclass. |
| 1357 | """ |
Marc-Antoine Ruel | 3798993 | 2013-11-19 16:28:08 -0500 | [diff] [blame] | 1358 | if file_path.is_url(file_or_url): |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 1359 | return IsolateServer(file_or_url, namespace) |
| 1360 | else: |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 1361 | return FileSystem(file_or_url, namespace) |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 1362 | |
| 1363 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1364 | def get_storage(file_or_url, namespace): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1365 | """Returns Storage class that can upload and download from |namespace|. |
| 1366 | |
| 1367 | Arguments: |
| 1368 | file_or_url: a file path to use file system based storage, or URL of isolate |
| 1369 | service to use shared cloud based storage. |
| 1370 | namespace: isolate namespace to operate in, also defines hashing and |
| 1371 | compression scheme used, i.e. namespace names that end with '-gzip' |
| 1372 | store compressed data. |
| 1373 | |
| 1374 | Returns: |
| 1375 | Instance of Storage. |
| 1376 | """ |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 1377 | return Storage(get_storage_api(file_or_url, namespace)) |
maruel@chromium.org | dedbf49 | 2013-09-12 20:42:11 +0000 | [diff] [blame] | 1378 | |
maruel@chromium.org | dedbf49 | 2013-09-12 20:42:11 +0000 | [diff] [blame] | 1379 | |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1380 | def expand_symlinks(indir, relfile): |
| 1381 | """Follows symlinks in |relfile|, but treating symlinks that point outside the |
| 1382 | build tree as if they were ordinary directories/files. Returns the final |
| 1383 | symlink-free target and a list of paths to symlinks encountered in the |
| 1384 | process. |
| 1385 | |
| 1386 | The rule about symlinks outside the build tree is for the benefit of the |
| 1387 | Chromium OS ebuild, which symlinks the output directory to an unrelated path |
| 1388 | in the chroot. |
| 1389 | |
| 1390 | Fails when a directory loop is detected, although in theory we could support |
| 1391 | that case. |
| 1392 | """ |
| 1393 | is_directory = relfile.endswith(os.path.sep) |
| 1394 | done = indir |
| 1395 | todo = relfile.strip(os.path.sep) |
| 1396 | symlinks = [] |
| 1397 | |
| 1398 | while todo: |
| 1399 | pre_symlink, symlink, post_symlink = file_path.split_at_symlink( |
| 1400 | done, todo) |
| 1401 | if not symlink: |
| 1402 | todo = file_path.fix_native_path_case(done, todo) |
| 1403 | done = os.path.join(done, todo) |
| 1404 | break |
| 1405 | symlink_path = os.path.join(done, pre_symlink, symlink) |
| 1406 | post_symlink = post_symlink.lstrip(os.path.sep) |
| 1407 | # readlink doesn't exist on Windows. |
| 1408 | # pylint: disable=E1101 |
| 1409 | target = os.path.normpath(os.path.join(done, pre_symlink)) |
| 1410 | symlink_target = os.readlink(symlink_path) |
| 1411 | if os.path.isabs(symlink_target): |
| 1412 | # Absolute path are considered a normal directories. The use case is |
| 1413 | # generally someone who puts the output directory on a separate drive. |
| 1414 | target = symlink_target |
| 1415 | else: |
| 1416 | # The symlink itself could be using the wrong path case. |
| 1417 | target = file_path.fix_native_path_case(target, symlink_target) |
| 1418 | |
| 1419 | if not os.path.exists(target): |
| 1420 | raise MappingError( |
| 1421 | 'Symlink target doesn\'t exist: %s -> %s' % (symlink_path, target)) |
| 1422 | target = file_path.get_native_path_case(target) |
| 1423 | if not file_path.path_starts_with(indir, target): |
| 1424 | done = symlink_path |
| 1425 | todo = post_symlink |
| 1426 | continue |
| 1427 | if file_path.path_starts_with(target, symlink_path): |
| 1428 | raise MappingError( |
| 1429 | 'Can\'t map recursive symlink reference %s -> %s' % |
| 1430 | (symlink_path, target)) |
| 1431 | logging.info('Found symlink: %s -> %s', symlink_path, target) |
| 1432 | symlinks.append(os.path.relpath(symlink_path, indir)) |
| 1433 | # Treat the common prefix of the old and new paths as done, and start |
| 1434 | # scanning again. |
| 1435 | target = target.split(os.path.sep) |
| 1436 | symlink_path = symlink_path.split(os.path.sep) |
| 1437 | prefix_length = 0 |
| 1438 | for target_piece, symlink_path_piece in zip(target, symlink_path): |
| 1439 | if target_piece == symlink_path_piece: |
| 1440 | prefix_length += 1 |
| 1441 | else: |
| 1442 | break |
| 1443 | done = os.path.sep.join(target[:prefix_length]) |
| 1444 | todo = os.path.join( |
| 1445 | os.path.sep.join(target[prefix_length:]), post_symlink) |
| 1446 | |
| 1447 | relfile = os.path.relpath(done, indir) |
| 1448 | relfile = relfile.rstrip(os.path.sep) + is_directory * os.path.sep |
| 1449 | return relfile, symlinks |
| 1450 | |
| 1451 | |
| 1452 | def expand_directory_and_symlink(indir, relfile, blacklist, follow_symlinks): |
| 1453 | """Expands a single input. It can result in multiple outputs. |
| 1454 | |
| 1455 | This function is recursive when relfile is a directory. |
| 1456 | |
| 1457 | Note: this code doesn't properly handle recursive symlink like one created |
| 1458 | with: |
| 1459 | ln -s .. foo |
| 1460 | """ |
| 1461 | if os.path.isabs(relfile): |
| 1462 | raise MappingError('Can\'t map absolute path %s' % relfile) |
| 1463 | |
| 1464 | infile = file_path.normpath(os.path.join(indir, relfile)) |
| 1465 | if not infile.startswith(indir): |
| 1466 | raise MappingError('Can\'t map file %s outside %s' % (infile, indir)) |
| 1467 | |
| 1468 | filepath = os.path.join(indir, relfile) |
| 1469 | native_filepath = file_path.get_native_path_case(filepath) |
| 1470 | if filepath != native_filepath: |
| 1471 | # Special case './'. |
| 1472 | if filepath != native_filepath + '.' + os.path.sep: |
Marc-Antoine Ruel | 582e224 | 2014-06-26 15:22:06 -0400 | [diff] [blame] | 1473 | # While it'd be nice to enforce path casing on Windows, it's impractical. |
| 1474 | # Also give up enforcing strict path case on OSX. Really, it's that sad. |
| 1475 | # The case where it happens is very specific and hard to reproduce: |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1476 | # get_native_path_case( |
| 1477 | # u'Foo.framework/Versions/A/Resources/Something.nib') will return |
| 1478 | # u'Foo.framework/Versions/A/resources/Something.nib', e.g. lowercase 'r'. |
| 1479 | # |
| 1480 | # Note that this is really something deep in OSX because running |
| 1481 | # ls Foo.framework/Versions/A |
| 1482 | # will print out 'Resources', while file_path.get_native_path_case() |
| 1483 | # returns a lower case 'r'. |
| 1484 | # |
| 1485 | # So *something* is happening under the hood resulting in the command 'ls' |
| 1486 | # and Carbon.File.FSPathMakeRef('path').FSRefMakePath() to disagree. We |
| 1487 | # have no idea why. |
Marc-Antoine Ruel | 582e224 | 2014-06-26 15:22:06 -0400 | [diff] [blame] | 1488 | if sys.platform not in ('darwin', 'win32'): |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1489 | raise MappingError( |
| 1490 | 'File path doesn\'t equal native file path\n%s != %s' % |
| 1491 | (filepath, native_filepath)) |
| 1492 | |
| 1493 | symlinks = [] |
| 1494 | if follow_symlinks: |
| 1495 | relfile, symlinks = expand_symlinks(indir, relfile) |
| 1496 | |
| 1497 | if relfile.endswith(os.path.sep): |
| 1498 | if not os.path.isdir(infile): |
| 1499 | raise MappingError( |
| 1500 | '%s is not a directory but ends with "%s"' % (infile, os.path.sep)) |
| 1501 | |
| 1502 | # Special case './'. |
| 1503 | if relfile.startswith('.' + os.path.sep): |
| 1504 | relfile = relfile[2:] |
| 1505 | outfiles = symlinks |
| 1506 | try: |
| 1507 | for filename in os.listdir(infile): |
| 1508 | inner_relfile = os.path.join(relfile, filename) |
| 1509 | if blacklist and blacklist(inner_relfile): |
| 1510 | continue |
| 1511 | if os.path.isdir(os.path.join(indir, inner_relfile)): |
| 1512 | inner_relfile += os.path.sep |
| 1513 | outfiles.extend( |
| 1514 | expand_directory_and_symlink(indir, inner_relfile, blacklist, |
| 1515 | follow_symlinks)) |
| 1516 | return outfiles |
| 1517 | except OSError as e: |
| 1518 | raise MappingError( |
| 1519 | 'Unable to iterate over directory %s.\n%s' % (infile, e)) |
| 1520 | else: |
| 1521 | # Always add individual files even if they were blacklisted. |
| 1522 | if os.path.isdir(infile): |
| 1523 | raise MappingError( |
| 1524 | 'Input directory %s must have a trailing slash' % infile) |
| 1525 | |
| 1526 | if not os.path.isfile(infile): |
| 1527 | raise MappingError('Input file %s doesn\'t exist' % infile) |
| 1528 | |
| 1529 | return symlinks + [relfile] |
| 1530 | |
| 1531 | |
Marc-Antoine Ruel | 0519946 | 2014-03-13 15:40:48 -0400 | [diff] [blame] | 1532 | def process_input(filepath, prevdict, read_only, algo): |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1533 | """Processes an input file, a dependency, and return meta data about it. |
| 1534 | |
| 1535 | Behaviors: |
| 1536 | - Retrieves the file mode, file size, file timestamp, file link |
| 1537 | destination if it is a file link and calcultate the SHA-1 of the file's |
| 1538 | content if the path points to a file and not a symlink. |
| 1539 | |
| 1540 | Arguments: |
| 1541 | filepath: File to act on. |
| 1542 | prevdict: the previous dictionary. It is used to retrieve the cached sha-1 |
| 1543 | to skip recalculating the hash. Optional. |
Marc-Antoine Ruel | 7124e39 | 2014-01-09 11:49:21 -0500 | [diff] [blame] | 1544 | read_only: If 1 or 2, the file mode is manipulated. In practice, only save |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1545 | one of 4 modes: 0755 (rwx), 0644 (rw), 0555 (rx), 0444 (r). On |
| 1546 | windows, mode is not set since all files are 'executable' by |
| 1547 | default. |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1548 | algo: Hashing algorithm used. |
| 1549 | |
| 1550 | Returns: |
| 1551 | The necessary data to create a entry in the 'files' section of an .isolated |
| 1552 | file. |
| 1553 | """ |
| 1554 | out = {} |
| 1555 | # TODO(csharp): Fix crbug.com/150823 and enable the touched logic again. |
| 1556 | # if prevdict.get('T') == True: |
| 1557 | # # The file's content is ignored. Skip the time and hard code mode. |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1558 | # out['s'] = 0 |
| 1559 | # out['h'] = algo().hexdigest() |
| 1560 | # out['T'] = True |
| 1561 | # return out |
| 1562 | |
| 1563 | # Always check the file stat and check if it is a link. The timestamp is used |
| 1564 | # to know if the file's content/symlink destination should be looked into. |
| 1565 | # E.g. only reuse from prevdict if the timestamp hasn't changed. |
| 1566 | # There is the risk of the file's timestamp being reset to its last value |
| 1567 | # manually while its content changed. We don't protect against that use case. |
| 1568 | try: |
| 1569 | filestats = os.lstat(filepath) |
| 1570 | except OSError: |
| 1571 | # The file is not present. |
| 1572 | raise MappingError('%s is missing' % filepath) |
| 1573 | is_link = stat.S_ISLNK(filestats.st_mode) |
| 1574 | |
Marc-Antoine Ruel | 0519946 | 2014-03-13 15:40:48 -0400 | [diff] [blame] | 1575 | if sys.platform != 'win32': |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1576 | # Ignore file mode on Windows since it's not really useful there. |
| 1577 | filemode = stat.S_IMODE(filestats.st_mode) |
| 1578 | # Remove write access for group and all access to 'others'. |
| 1579 | filemode &= ~(stat.S_IWGRP | stat.S_IRWXO) |
| 1580 | if read_only: |
| 1581 | filemode &= ~stat.S_IWUSR |
| 1582 | if filemode & stat.S_IXUSR: |
| 1583 | filemode |= stat.S_IXGRP |
| 1584 | else: |
| 1585 | filemode &= ~stat.S_IXGRP |
| 1586 | if not is_link: |
| 1587 | out['m'] = filemode |
| 1588 | |
| 1589 | # Used to skip recalculating the hash or link destination. Use the most recent |
| 1590 | # update time. |
| 1591 | # TODO(maruel): Save it in the .state file instead of .isolated so the |
| 1592 | # .isolated file is deterministic. |
| 1593 | out['t'] = int(round(filestats.st_mtime)) |
| 1594 | |
| 1595 | if not is_link: |
| 1596 | out['s'] = filestats.st_size |
| 1597 | # If the timestamp wasn't updated and the file size is still the same, carry |
| 1598 | # on the sha-1. |
| 1599 | if (prevdict.get('t') == out['t'] and |
| 1600 | prevdict.get('s') == out['s']): |
| 1601 | # Reuse the previous hash if available. |
| 1602 | out['h'] = prevdict.get('h') |
| 1603 | if not out.get('h'): |
| 1604 | out['h'] = hash_file(filepath, algo) |
| 1605 | else: |
| 1606 | # If the timestamp wasn't updated, carry on the link destination. |
| 1607 | if prevdict.get('t') == out['t']: |
| 1608 | # Reuse the previous link destination if available. |
| 1609 | out['l'] = prevdict.get('l') |
| 1610 | if out.get('l') is None: |
| 1611 | # The link could be in an incorrect path case. In practice, this only |
| 1612 | # happen on OSX on case insensitive HFS. |
| 1613 | # TODO(maruel): It'd be better if it was only done once, in |
| 1614 | # expand_directory_and_symlink(), so it would not be necessary to do again |
| 1615 | # here. |
| 1616 | symlink_value = os.readlink(filepath) # pylint: disable=E1101 |
| 1617 | filedir = file_path.get_native_path_case(os.path.dirname(filepath)) |
| 1618 | native_dest = file_path.fix_native_path_case(filedir, symlink_value) |
| 1619 | out['l'] = os.path.relpath(native_dest, filedir) |
| 1620 | return out |
| 1621 | |
| 1622 | |
| 1623 | def save_isolated(isolated, data): |
| 1624 | """Writes one or multiple .isolated files. |
| 1625 | |
| 1626 | Note: this reference implementation does not create child .isolated file so it |
| 1627 | always returns an empty list. |
| 1628 | |
| 1629 | Returns the list of child isolated files that are included by |isolated|. |
| 1630 | """ |
| 1631 | # Make sure the data is valid .isolated data by 'reloading' it. |
| 1632 | algo = SUPPORTED_ALGOS[data['algo']] |
Marc-Antoine Ruel | 0519946 | 2014-03-13 15:40:48 -0400 | [diff] [blame] | 1633 | load_isolated(json.dumps(data), algo) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1634 | tools.write_json(isolated, data, True) |
| 1635 | return [] |
| 1636 | |
| 1637 | |
maruel@chromium.org | 7b844a6 | 2013-09-17 13:04:59 +0000 | [diff] [blame] | 1638 | def upload_tree(base_url, indir, infiles, namespace): |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 1639 | """Uploads the given tree to the given url. |
| 1640 | |
| 1641 | Arguments: |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 1642 | base_url: The base url, it is assume that |base_url|/has/ can be used to |
| 1643 | query if an element was already uploaded, and |base_url|/store/ |
| 1644 | can be used to upload a new element. |
| 1645 | indir: Root directory the infiles are based in. |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1646 | infiles: dict of files to upload from |indir| to |base_url|. |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 1647 | namespace: The namespace to use on the server. |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 1648 | """ |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1649 | logging.info('upload_tree(indir=%s, files=%d)', indir, len(infiles)) |
| 1650 | |
| 1651 | # Convert |indir| + |infiles| into a list of FileItem objects. |
| 1652 | # Filter out symlinks, since they are not represented by items on isolate |
| 1653 | # server side. |
| 1654 | items = [ |
| 1655 | FileItem( |
| 1656 | path=os.path.join(indir, filepath), |
| 1657 | digest=metadata['h'], |
| 1658 | size=metadata['s'], |
| 1659 | high_priority=metadata.get('priority') == '0') |
| 1660 | for filepath, metadata in infiles.iteritems() |
| 1661 | if 'l' not in metadata |
| 1662 | ] |
| 1663 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1664 | with get_storage(base_url, namespace) as storage: |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1665 | storage.upload_items(items) |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 1666 | return 0 |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 1667 | |
| 1668 | |
Marc-Antoine Ruel | 0519946 | 2014-03-13 15:40:48 -0400 | [diff] [blame] | 1669 | def load_isolated(content, algo): |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1670 | """Verifies the .isolated file is valid and loads this object with the json |
| 1671 | data. |
maruel@chromium.org | 385d73d | 2013-09-19 18:33:21 +0000 | [diff] [blame] | 1672 | |
| 1673 | Arguments: |
| 1674 | - content: raw serialized content to load. |
maruel@chromium.org | 385d73d | 2013-09-19 18:33:21 +0000 | [diff] [blame] | 1675 | - algo: hashlib algorithm class. Used to confirm the algorithm matches the |
| 1676 | algorithm used on the Isolate Server. |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1677 | """ |
| 1678 | try: |
| 1679 | data = json.loads(content) |
| 1680 | except ValueError: |
| 1681 | raise ConfigError('Failed to parse: %s...' % content[:100]) |
| 1682 | |
| 1683 | if not isinstance(data, dict): |
| 1684 | raise ConfigError('Expected dict, got %r' % data) |
| 1685 | |
maruel@chromium.org | 385d73d | 2013-09-19 18:33:21 +0000 | [diff] [blame] | 1686 | # Check 'version' first, since it could modify the parsing after. |
Marc-Antoine Ruel | 0519946 | 2014-03-13 15:40:48 -0400 | [diff] [blame] | 1687 | value = data.get('version', '1.0') |
maruel@chromium.org | 385d73d | 2013-09-19 18:33:21 +0000 | [diff] [blame] | 1688 | if not isinstance(value, basestring): |
| 1689 | raise ConfigError('Expected string, got %r' % value) |
Marc-Antoine Ruel | 0519946 | 2014-03-13 15:40:48 -0400 | [diff] [blame] | 1690 | try: |
| 1691 | version = tuple(map(int, value.split('.'))) |
| 1692 | except ValueError: |
| 1693 | raise ConfigError('Expected valid version, got %r' % value) |
| 1694 | |
| 1695 | expected_version = tuple(map(int, ISOLATED_FILE_VERSION.split('.'))) |
| 1696 | # Major version must match. |
| 1697 | if version[0] != expected_version[0]: |
Marc-Antoine Ruel | 1c1edd6 | 2013-12-06 09:13:13 -0500 | [diff] [blame] | 1698 | raise ConfigError( |
| 1699 | 'Expected compatible \'%s\' version, got %r' % |
| 1700 | (ISOLATED_FILE_VERSION, value)) |
maruel@chromium.org | 385d73d | 2013-09-19 18:33:21 +0000 | [diff] [blame] | 1701 | |
| 1702 | if algo is None: |
Marc-Antoine Ruel | ac54cb4 | 2013-11-18 14:05:35 -0500 | [diff] [blame] | 1703 | # TODO(maruel): Remove the default around Jan 2014. |
maruel@chromium.org | 385d73d | 2013-09-19 18:33:21 +0000 | [diff] [blame] | 1704 | # Default the algorithm used in the .isolated file itself, falls back to |
| 1705 | # 'sha-1' if unspecified. |
| 1706 | algo = SUPPORTED_ALGOS_REVERSE[data.get('algo', 'sha-1')] |
| 1707 | |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1708 | for key, value in data.iteritems(): |
maruel@chromium.org | 385d73d | 2013-09-19 18:33:21 +0000 | [diff] [blame] | 1709 | if key == 'algo': |
| 1710 | if not isinstance(value, basestring): |
| 1711 | raise ConfigError('Expected string, got %r' % value) |
| 1712 | if value not in SUPPORTED_ALGOS: |
| 1713 | raise ConfigError( |
| 1714 | 'Expected one of \'%s\', got %r' % |
| 1715 | (', '.join(sorted(SUPPORTED_ALGOS)), value)) |
| 1716 | if value != SUPPORTED_ALGOS_REVERSE[algo]: |
| 1717 | raise ConfigError( |
| 1718 | 'Expected \'%s\', got %r' % (SUPPORTED_ALGOS_REVERSE[algo], value)) |
| 1719 | |
| 1720 | elif key == 'command': |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1721 | if not isinstance(value, list): |
| 1722 | raise ConfigError('Expected list, got %r' % value) |
| 1723 | if not value: |
| 1724 | raise ConfigError('Expected non-empty command') |
| 1725 | for subvalue in value: |
| 1726 | if not isinstance(subvalue, basestring): |
| 1727 | raise ConfigError('Expected string, got %r' % subvalue) |
| 1728 | |
| 1729 | elif key == 'files': |
| 1730 | if not isinstance(value, dict): |
| 1731 | raise ConfigError('Expected dict, got %r' % value) |
| 1732 | for subkey, subvalue in value.iteritems(): |
| 1733 | if not isinstance(subkey, basestring): |
| 1734 | raise ConfigError('Expected string, got %r' % subkey) |
| 1735 | if not isinstance(subvalue, dict): |
| 1736 | raise ConfigError('Expected dict, got %r' % subvalue) |
| 1737 | for subsubkey, subsubvalue in subvalue.iteritems(): |
| 1738 | if subsubkey == 'l': |
| 1739 | if not isinstance(subsubvalue, basestring): |
| 1740 | raise ConfigError('Expected string, got %r' % subsubvalue) |
| 1741 | elif subsubkey == 'm': |
| 1742 | if not isinstance(subsubvalue, int): |
| 1743 | raise ConfigError('Expected int, got %r' % subsubvalue) |
| 1744 | elif subsubkey == 'h': |
| 1745 | if not is_valid_hash(subsubvalue, algo): |
| 1746 | raise ConfigError('Expected sha-1, got %r' % subsubvalue) |
| 1747 | elif subsubkey == 's': |
Marc-Antoine Ruel | aab3a62 | 2013-11-28 09:47:05 -0500 | [diff] [blame] | 1748 | if not isinstance(subsubvalue, (int, long)): |
| 1749 | raise ConfigError('Expected int or long, got %r' % subsubvalue) |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1750 | else: |
| 1751 | raise ConfigError('Unknown subsubkey %s' % subsubkey) |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1752 | if bool('h' in subvalue) == bool('l' in subvalue): |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1753 | raise ConfigError( |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1754 | 'Need only one of \'h\' (sha-1) or \'l\' (link), got: %r' % |
| 1755 | subvalue) |
| 1756 | if bool('h' in subvalue) != bool('s' in subvalue): |
| 1757 | raise ConfigError( |
| 1758 | 'Both \'h\' (sha-1) and \'s\' (size) should be set, got: %r' % |
| 1759 | subvalue) |
| 1760 | if bool('s' in subvalue) == bool('l' in subvalue): |
| 1761 | raise ConfigError( |
| 1762 | 'Need only one of \'s\' (size) or \'l\' (link), got: %r' % |
| 1763 | subvalue) |
| 1764 | if bool('l' in subvalue) and bool('m' in subvalue): |
| 1765 | raise ConfigError( |
| 1766 | 'Cannot use \'m\' (mode) and \'l\' (link), got: %r' % |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1767 | subvalue) |
| 1768 | |
| 1769 | elif key == 'includes': |
| 1770 | if not isinstance(value, list): |
| 1771 | raise ConfigError('Expected list, got %r' % value) |
| 1772 | if not value: |
| 1773 | raise ConfigError('Expected non-empty includes list') |
| 1774 | for subvalue in value: |
| 1775 | if not is_valid_hash(subvalue, algo): |
| 1776 | raise ConfigError('Expected sha-1, got %r' % subvalue) |
| 1777 | |
Marc-Antoine Ruel | 0519946 | 2014-03-13 15:40:48 -0400 | [diff] [blame] | 1778 | elif key == 'os': |
| 1779 | if version >= (1, 4): |
| 1780 | raise ConfigError('Key \'os\' is not allowed starting version 1.4') |
| 1781 | |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1782 | elif key == 'read_only': |
Marc-Antoine Ruel | 7124e39 | 2014-01-09 11:49:21 -0500 | [diff] [blame] | 1783 | if not value in (0, 1, 2): |
| 1784 | raise ConfigError('Expected 0, 1 or 2, got %r' % value) |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1785 | |
| 1786 | elif key == 'relative_cwd': |
| 1787 | if not isinstance(value, basestring): |
| 1788 | raise ConfigError('Expected string, got %r' % value) |
| 1789 | |
maruel@chromium.org | 385d73d | 2013-09-19 18:33:21 +0000 | [diff] [blame] | 1790 | elif key == 'version': |
| 1791 | # Already checked above. |
| 1792 | pass |
| 1793 | |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1794 | else: |
maruel@chromium.org | 385d73d | 2013-09-19 18:33:21 +0000 | [diff] [blame] | 1795 | raise ConfigError('Unknown key %r' % key) |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1796 | |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1797 | # Automatically fix os.path.sep if necessary. While .isolated files are always |
| 1798 | # in the the native path format, someone could want to download an .isolated |
| 1799 | # tree from another OS. |
| 1800 | wrong_path_sep = '/' if os.path.sep == '\\' else '\\' |
| 1801 | if 'files' in data: |
| 1802 | data['files'] = dict( |
| 1803 | (k.replace(wrong_path_sep, os.path.sep), v) |
| 1804 | for k, v in data['files'].iteritems()) |
| 1805 | for v in data['files'].itervalues(): |
| 1806 | if 'l' in v: |
| 1807 | v['l'] = v['l'].replace(wrong_path_sep, os.path.sep) |
| 1808 | if 'relative_cwd' in data: |
| 1809 | data['relative_cwd'] = data['relative_cwd'].replace( |
| 1810 | wrong_path_sep, os.path.sep) |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1811 | return data |
| 1812 | |
| 1813 | |
| 1814 | class IsolatedFile(object): |
| 1815 | """Represents a single parsed .isolated file.""" |
| 1816 | def __init__(self, obj_hash, algo): |
| 1817 | """|obj_hash| is really the sha-1 of the file.""" |
| 1818 | logging.debug('IsolatedFile(%s)' % obj_hash) |
| 1819 | self.obj_hash = obj_hash |
| 1820 | self.algo = algo |
| 1821 | # Set once all the left-side of the tree is parsed. 'Tree' here means the |
| 1822 | # .isolate and all the .isolated files recursively included by it with |
| 1823 | # 'includes' key. The order of each sha-1 in 'includes', each representing a |
| 1824 | # .isolated file in the hash table, is important, as the later ones are not |
| 1825 | # processed until the firsts are retrieved and read. |
| 1826 | self.can_fetch = False |
| 1827 | |
| 1828 | # Raw data. |
| 1829 | self.data = {} |
| 1830 | # A IsolatedFile instance, one per object in self.includes. |
| 1831 | self.children = [] |
| 1832 | |
| 1833 | # Set once the .isolated file is loaded. |
| 1834 | self._is_parsed = False |
| 1835 | # Set once the files are fetched. |
| 1836 | self.files_fetched = False |
| 1837 | |
Marc-Antoine Ruel | 0519946 | 2014-03-13 15:40:48 -0400 | [diff] [blame] | 1838 | def load(self, content): |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1839 | """Verifies the .isolated file is valid and loads this object with the json |
| 1840 | data. |
| 1841 | """ |
| 1842 | logging.debug('IsolatedFile.load(%s)' % self.obj_hash) |
| 1843 | assert not self._is_parsed |
Marc-Antoine Ruel | 0519946 | 2014-03-13 15:40:48 -0400 | [diff] [blame] | 1844 | self.data = load_isolated(content, self.algo) |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1845 | self.children = [ |
| 1846 | IsolatedFile(i, self.algo) for i in self.data.get('includes', []) |
| 1847 | ] |
| 1848 | self._is_parsed = True |
| 1849 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1850 | def fetch_files(self, fetch_queue, files): |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1851 | """Adds files in this .isolated file not present in |files| dictionary. |
| 1852 | |
| 1853 | Preemptively request files. |
| 1854 | |
| 1855 | Note that |files| is modified by this function. |
| 1856 | """ |
| 1857 | assert self.can_fetch |
| 1858 | if not self._is_parsed or self.files_fetched: |
| 1859 | return |
| 1860 | logging.debug('fetch_files(%s)' % self.obj_hash) |
| 1861 | for filepath, properties in self.data.get('files', {}).iteritems(): |
| 1862 | # Root isolated has priority on the files being mapped. In particular, |
| 1863 | # overriden files must not be fetched. |
| 1864 | if filepath not in files: |
| 1865 | files[filepath] = properties |
| 1866 | if 'h' in properties: |
| 1867 | # Preemptively request files. |
| 1868 | logging.debug('fetching %s' % filepath) |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1869 | fetch_queue.add(properties['h'], properties['s'], WorkerPool.MED) |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1870 | self.files_fetched = True |
| 1871 | |
| 1872 | |
| 1873 | class Settings(object): |
| 1874 | """Results of a completely parsed .isolated file.""" |
| 1875 | def __init__(self): |
| 1876 | self.command = [] |
| 1877 | self.files = {} |
| 1878 | self.read_only = None |
| 1879 | self.relative_cwd = None |
| 1880 | # The main .isolated file, a IsolatedFile instance. |
| 1881 | self.root = None |
| 1882 | |
Marc-Antoine Ruel | 0519946 | 2014-03-13 15:40:48 -0400 | [diff] [blame] | 1883 | def load(self, fetch_queue, root_isolated_hash, algo): |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1884 | """Loads the .isolated and all the included .isolated asynchronously. |
| 1885 | |
| 1886 | It enables support for "included" .isolated files. They are processed in |
| 1887 | strict order but fetched asynchronously from the cache. This is important so |
| 1888 | that a file in an included .isolated file that is overridden by an embedding |
| 1889 | .isolated file is not fetched needlessly. The includes are fetched in one |
| 1890 | pass and the files are fetched as soon as all the ones on the left-side |
| 1891 | of the tree were fetched. |
| 1892 | |
| 1893 | The prioritization is very important here for nested .isolated files. |
| 1894 | 'includes' have the highest priority and the algorithm is optimized for both |
| 1895 | deep and wide trees. A deep one is a long link of .isolated files referenced |
| 1896 | one at a time by one item in 'includes'. A wide one has a large number of |
| 1897 | 'includes' in a single .isolated file. 'left' is defined as an included |
| 1898 | .isolated file earlier in the 'includes' list. So the order of the elements |
| 1899 | in 'includes' is important. |
| 1900 | """ |
| 1901 | self.root = IsolatedFile(root_isolated_hash, algo) |
| 1902 | |
| 1903 | # Isolated files being retrieved now: hash -> IsolatedFile instance. |
| 1904 | pending = {} |
| 1905 | # Set of hashes of already retrieved items to refuse recursive includes. |
| 1906 | seen = set() |
| 1907 | |
| 1908 | def retrieve(isolated_file): |
| 1909 | h = isolated_file.obj_hash |
| 1910 | if h in seen: |
| 1911 | raise ConfigError('IsolatedFile %s is retrieved recursively' % h) |
| 1912 | assert h not in pending |
| 1913 | seen.add(h) |
| 1914 | pending[h] = isolated_file |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1915 | fetch_queue.add(h, priority=WorkerPool.HIGH) |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1916 | |
| 1917 | retrieve(self.root) |
| 1918 | |
| 1919 | while pending: |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1920 | item_hash = fetch_queue.wait(pending) |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1921 | item = pending.pop(item_hash) |
Marc-Antoine Ruel | 0519946 | 2014-03-13 15:40:48 -0400 | [diff] [blame] | 1922 | item.load(fetch_queue.cache.read(item_hash)) |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1923 | if item_hash == root_isolated_hash: |
| 1924 | # It's the root item. |
| 1925 | item.can_fetch = True |
| 1926 | |
| 1927 | for new_child in item.children: |
| 1928 | retrieve(new_child) |
| 1929 | |
| 1930 | # Traverse the whole tree to see if files can now be fetched. |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1931 | self._traverse_tree(fetch_queue, self.root) |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1932 | |
| 1933 | def check(n): |
| 1934 | return all(check(x) for x in n.children) and n.files_fetched |
| 1935 | assert check(self.root) |
| 1936 | |
| 1937 | self.relative_cwd = self.relative_cwd or '' |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1938 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1939 | def _traverse_tree(self, fetch_queue, node): |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1940 | if node.can_fetch: |
| 1941 | if not node.files_fetched: |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1942 | self._update_self(fetch_queue, node) |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1943 | will_break = False |
| 1944 | for i in node.children: |
| 1945 | if not i.can_fetch: |
| 1946 | if will_break: |
| 1947 | break |
| 1948 | # Automatically mark the first one as fetcheable. |
| 1949 | i.can_fetch = True |
| 1950 | will_break = True |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1951 | self._traverse_tree(fetch_queue, i) |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1952 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1953 | def _update_self(self, fetch_queue, node): |
| 1954 | node.fetch_files(fetch_queue, self.files) |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1955 | # Grabs properties. |
| 1956 | if not self.command and node.data.get('command'): |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1957 | # Ensure paths are correctly separated on windows. |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1958 | self.command = node.data['command'] |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1959 | if self.command: |
| 1960 | self.command[0] = self.command[0].replace('/', os.path.sep) |
| 1961 | self.command = tools.fix_python_path(self.command) |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 1962 | if self.read_only is None and node.data.get('read_only') is not None: |
| 1963 | self.read_only = node.data['read_only'] |
| 1964 | if (self.relative_cwd is None and |
| 1965 | node.data.get('relative_cwd') is not None): |
| 1966 | self.relative_cwd = node.data['relative_cwd'] |
| 1967 | |
| 1968 | |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 1969 | def fetch_isolated(isolated_hash, storage, cache, outdir, require_command): |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1970 | """Aggressively downloads the .isolated file(s), then download all the files. |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1971 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1972 | Arguments: |
| 1973 | isolated_hash: hash of the root *.isolated file. |
| 1974 | storage: Storage class that communicates with isolate storage. |
| 1975 | cache: LocalCache class that knows how to store and map files locally. |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1976 | outdir: Output directory to map file tree to. |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1977 | require_command: Ensure *.isolated specifies a command to run. |
| 1978 | |
| 1979 | Returns: |
| 1980 | Settings object that holds details about loaded *.isolated file. |
| 1981 | """ |
Marc-Antoine Ruel | 4e8cd18 | 2014-06-18 13:27:17 -0400 | [diff] [blame] | 1982 | logging.debug( |
| 1983 | 'fetch_isolated(%s, %s, %s, %s, %s)', |
| 1984 | isolated_hash, storage, cache, outdir, require_command) |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 1985 | # Hash algorithm to use, defined by namespace |storage| is using. |
| 1986 | algo = storage.hash_algo |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1987 | with cache: |
| 1988 | fetch_queue = FetchQueue(storage, cache) |
| 1989 | settings = Settings() |
| 1990 | |
| 1991 | with tools.Profiler('GetIsolateds'): |
| 1992 | # Optionally support local files by manually adding them to cache. |
| 1993 | if not is_valid_hash(isolated_hash, algo): |
Marc-Antoine Ruel | 4e8cd18 | 2014-06-18 13:27:17 -0400 | [diff] [blame] | 1994 | logging.debug('%s is not a valid hash, assuming a file', isolated_hash) |
| 1995 | try: |
| 1996 | isolated_hash = fetch_queue.inject_local_file(isolated_hash, algo) |
| 1997 | except IOError: |
| 1998 | raise MappingError( |
| 1999 | '%s doesn\'t seem to be a valid file. Did you intent to pass a ' |
| 2000 | 'valid hash?' % isolated_hash) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 2001 | |
| 2002 | # Load all *.isolated and start loading rest of the files. |
Marc-Antoine Ruel | 0519946 | 2014-03-13 15:40:48 -0400 | [diff] [blame] | 2003 | settings.load(fetch_queue, isolated_hash, algo) |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 2004 | if require_command and not settings.command: |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 2005 | # TODO(vadimsh): All fetch operations are already enqueue and there's no |
| 2006 | # easy way to cancel them. |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 2007 | raise ConfigError('No command to run') |
| 2008 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 2009 | with tools.Profiler('GetRest'): |
| 2010 | # Create file system hierarchy. |
| 2011 | if not os.path.isdir(outdir): |
| 2012 | os.makedirs(outdir) |
| 2013 | create_directories(outdir, settings.files) |
Marc-Antoine Ruel | ccafe0e | 2013-11-08 16:15:36 -0500 | [diff] [blame] | 2014 | create_symlinks(outdir, settings.files.iteritems()) |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 2015 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 2016 | # Ensure working directory exists. |
| 2017 | cwd = os.path.normpath(os.path.join(outdir, settings.relative_cwd)) |
| 2018 | if not os.path.isdir(cwd): |
| 2019 | os.makedirs(cwd) |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 2020 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 2021 | # Multimap: digest -> list of pairs (path, props). |
| 2022 | remaining = {} |
| 2023 | for filepath, props in settings.files.iteritems(): |
| 2024 | if 'h' in props: |
| 2025 | remaining.setdefault(props['h'], []).append((filepath, props)) |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 2026 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 2027 | # Now block on the remaining files to be downloaded and mapped. |
| 2028 | logging.info('Retrieving remaining files (%d of them)...', |
| 2029 | fetch_queue.pending_count) |
| 2030 | last_update = time.time() |
| 2031 | with threading_utils.DeadlockDetector(DEADLOCK_TIMEOUT) as detector: |
| 2032 | while remaining: |
| 2033 | detector.ping() |
| 2034 | |
| 2035 | # Wait for any item to finish fetching to cache. |
| 2036 | digest = fetch_queue.wait(remaining) |
| 2037 | |
| 2038 | # Link corresponding files to a fetched item in cache. |
| 2039 | for filepath, props in remaining.pop(digest): |
Marc-Antoine Ruel | fb199cf | 2013-11-12 15:38:12 -0500 | [diff] [blame] | 2040 | cache.hardlink( |
| 2041 | digest, os.path.join(outdir, filepath), props.get('m')) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 2042 | |
| 2043 | # Report progress. |
| 2044 | duration = time.time() - last_update |
| 2045 | if duration > DELAY_BETWEEN_UPDATES_IN_SECS: |
| 2046 | msg = '%d files remaining...' % len(remaining) |
| 2047 | print msg |
| 2048 | logging.info(msg) |
| 2049 | last_update = time.time() |
| 2050 | |
| 2051 | # Cache could evict some items we just tried to fetch, it's a fatal error. |
| 2052 | if not fetch_queue.verify_all_cached(): |
| 2053 | raise MappingError('Cache is too small to hold all requested files') |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 2054 | return settings |
| 2055 | |
| 2056 | |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 2057 | def directory_to_metadata(root, algo, blacklist): |
| 2058 | """Returns the FileItem list and .isolated metadata for a directory.""" |
| 2059 | root = file_path.get_native_path_case(root) |
Vadim Shtayura | 439d3fc | 2014-05-07 16:05:12 -0700 | [diff] [blame] | 2060 | paths = expand_directory_and_symlink( |
| 2061 | root, '.' + os.path.sep, blacklist, sys.platform != 'win32') |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 2062 | metadata = dict( |
Marc-Antoine Ruel | 0519946 | 2014-03-13 15:40:48 -0400 | [diff] [blame] | 2063 | (relpath, process_input(os.path.join(root, relpath), {}, False, algo)) |
Vadim Shtayura | 439d3fc | 2014-05-07 16:05:12 -0700 | [diff] [blame] | 2064 | for relpath in paths |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 2065 | ) |
| 2066 | for v in metadata.itervalues(): |
| 2067 | v.pop('t') |
| 2068 | items = [ |
| 2069 | FileItem( |
| 2070 | path=os.path.join(root, relpath), |
| 2071 | digest=meta['h'], |
| 2072 | size=meta['s'], |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 2073 | high_priority=relpath.endswith('.isolated')) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 2074 | for relpath, meta in metadata.iteritems() if 'h' in meta |
| 2075 | ] |
| 2076 | return items, metadata |
| 2077 | |
| 2078 | |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 2079 | def archive_files_to_storage(storage, files, blacklist): |
Marc-Antoine Ruel | 2283ad1 | 2014-02-09 11:14:57 -0500 | [diff] [blame] | 2080 | """Stores every entries and returns the relevant data. |
| 2081 | |
| 2082 | Arguments: |
| 2083 | storage: a Storage object that communicates with the remote object store. |
Marc-Antoine Ruel | 2283ad1 | 2014-02-09 11:14:57 -0500 | [diff] [blame] | 2084 | files: list of file paths to upload. If a directory is specified, a |
| 2085 | .isolated file is created and its hash is returned. |
| 2086 | blacklist: function that returns True if a file should be omitted. |
| 2087 | """ |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 2088 | assert all(isinstance(i, unicode) for i in files), files |
| 2089 | if len(files) != len(set(map(os.path.abspath, files))): |
| 2090 | raise Error('Duplicate entries found.') |
| 2091 | |
| 2092 | results = [] |
| 2093 | # The temporary directory is only created as needed. |
| 2094 | tempdir = None |
| 2095 | try: |
| 2096 | # TODO(maruel): Yield the files to a worker thread. |
| 2097 | items_to_upload = [] |
| 2098 | for f in files: |
| 2099 | try: |
| 2100 | filepath = os.path.abspath(f) |
| 2101 | if os.path.isdir(filepath): |
| 2102 | # Uploading a whole directory. |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 2103 | items, metadata = directory_to_metadata( |
| 2104 | filepath, storage.hash_algo, blacklist) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 2105 | |
| 2106 | # Create the .isolated file. |
| 2107 | if not tempdir: |
| 2108 | tempdir = tempfile.mkdtemp(prefix='isolateserver') |
| 2109 | handle, isolated = tempfile.mkstemp(dir=tempdir, suffix='.isolated') |
| 2110 | os.close(handle) |
| 2111 | data = { |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 2112 | 'algo': SUPPORTED_ALGOS_REVERSE[storage.hash_algo], |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 2113 | 'files': metadata, |
Marc-Antoine Ruel | 1c1edd6 | 2013-12-06 09:13:13 -0500 | [diff] [blame] | 2114 | 'version': ISOLATED_FILE_VERSION, |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 2115 | } |
| 2116 | save_isolated(isolated, data) |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 2117 | h = hash_file(isolated, storage.hash_algo) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 2118 | items_to_upload.extend(items) |
| 2119 | items_to_upload.append( |
| 2120 | FileItem( |
| 2121 | path=isolated, |
| 2122 | digest=h, |
| 2123 | size=os.stat(isolated).st_size, |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 2124 | high_priority=True)) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 2125 | results.append((h, f)) |
| 2126 | |
| 2127 | elif os.path.isfile(filepath): |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 2128 | h = hash_file(filepath, storage.hash_algo) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 2129 | items_to_upload.append( |
| 2130 | FileItem( |
| 2131 | path=filepath, |
| 2132 | digest=h, |
| 2133 | size=os.stat(filepath).st_size, |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 2134 | high_priority=f.endswith('.isolated'))) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 2135 | results.append((h, f)) |
| 2136 | else: |
| 2137 | raise Error('%s is neither a file or directory.' % f) |
| 2138 | except OSError: |
| 2139 | raise Error('Failed to process %s.' % f) |
Marc-Antoine Ruel | 2283ad1 | 2014-02-09 11:14:57 -0500 | [diff] [blame] | 2140 | # Technically we would care about which files were uploaded but we don't |
| 2141 | # much in practice. |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 2142 | _uploaded_files = storage.upload_items(items_to_upload) |
| 2143 | return results |
| 2144 | finally: |
| 2145 | if tempdir: |
| 2146 | shutil.rmtree(tempdir) |
| 2147 | |
| 2148 | |
Marc-Antoine Ruel | 488ce8f | 2014-02-09 11:25:04 -0500 | [diff] [blame] | 2149 | def archive(out, namespace, files, blacklist): |
| 2150 | if files == ['-']: |
| 2151 | files = sys.stdin.readlines() |
| 2152 | |
| 2153 | if not files: |
| 2154 | raise Error('Nothing to upload') |
| 2155 | |
| 2156 | files = [f.decode('utf-8') for f in files] |
Marc-Antoine Ruel | 488ce8f | 2014-02-09 11:25:04 -0500 | [diff] [blame] | 2157 | blacklist = tools.gen_blacklist(blacklist) |
| 2158 | with get_storage(out, namespace) as storage: |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 2159 | results = archive_files_to_storage(storage, files, blacklist) |
Marc-Antoine Ruel | 488ce8f | 2014-02-09 11:25:04 -0500 | [diff] [blame] | 2160 | print('\n'.join('%s %s' % (r[0], r[1]) for r in results)) |
| 2161 | |
| 2162 | |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 2163 | @subcommand.usage('<file1..fileN> or - to read from stdin') |
| 2164 | def CMDarchive(parser, args): |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 2165 | """Archives data to the server. |
| 2166 | |
| 2167 | If a directory is specified, a .isolated file is created the whole directory |
| 2168 | is uploaded. Then this .isolated file can be included in another one to run |
| 2169 | commands. |
| 2170 | |
| 2171 | The commands output each file that was processed with its content hash. For |
| 2172 | directories, the .isolated generated for the directory is listed as the |
| 2173 | directory entry itself. |
| 2174 | """ |
Marc-Antoine Ruel | 8806e62 | 2014-02-12 14:15:53 -0500 | [diff] [blame] | 2175 | add_isolate_server_options(parser, False) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 2176 | parser.add_option( |
| 2177 | '--blacklist', |
| 2178 | action='append', default=list(DEFAULT_BLACKLIST), |
| 2179 | help='List of regexp to use as blacklist filter when uploading ' |
| 2180 | 'directories') |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 2181 | options, files = parser.parse_args(args) |
Marc-Antoine Ruel | 488ce8f | 2014-02-09 11:25:04 -0500 | [diff] [blame] | 2182 | process_isolate_server_options(parser, options) |
Vadim Shtayura | 6b555c1 | 2014-07-23 16:22:18 -0700 | [diff] [blame] | 2183 | if file_path.is_url(options.isolate_server): |
| 2184 | auth.ensure_logged_in(options.isolate_server) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 2185 | try: |
Marc-Antoine Ruel | 488ce8f | 2014-02-09 11:25:04 -0500 | [diff] [blame] | 2186 | archive(options.isolate_server, options.namespace, files, options.blacklist) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 2187 | except Error as e: |
| 2188 | parser.error(e.args[0]) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 2189 | return 0 |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 2190 | |
| 2191 | |
| 2192 | def CMDdownload(parser, args): |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 2193 | """Download data from the server. |
| 2194 | |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 2195 | It can either download individual files or a complete tree from a .isolated |
| 2196 | file. |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 2197 | """ |
Marc-Antoine Ruel | 8806e62 | 2014-02-12 14:15:53 -0500 | [diff] [blame] | 2198 | add_isolate_server_options(parser, True) |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 2199 | parser.add_option( |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 2200 | '-i', '--isolated', metavar='HASH', |
| 2201 | help='hash of an isolated file, .isolated file content is discarded, use ' |
| 2202 | '--file if you need it') |
| 2203 | parser.add_option( |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 2204 | '-f', '--file', metavar='HASH DEST', default=[], action='append', nargs=2, |
| 2205 | help='hash and destination of a file, can be used multiple times') |
| 2206 | parser.add_option( |
| 2207 | '-t', '--target', metavar='DIR', default=os.getcwd(), |
| 2208 | help='destination directory') |
| 2209 | options, args = parser.parse_args(args) |
Marc-Antoine Ruel | 488ce8f | 2014-02-09 11:25:04 -0500 | [diff] [blame] | 2210 | process_isolate_server_options(parser, options) |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 2211 | if args: |
| 2212 | parser.error('Unsupported arguments: %s' % args) |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 2213 | if bool(options.isolated) == bool(options.file): |
| 2214 | parser.error('Use one of --isolated or --file, and only one.') |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 2215 | |
| 2216 | options.target = os.path.abspath(options.target) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 2217 | |
Marc-Antoine Ruel | 8806e62 | 2014-02-12 14:15:53 -0500 | [diff] [blame] | 2218 | remote = options.isolate_server or options.indir |
Vadim Shtayura | 6b555c1 | 2014-07-23 16:22:18 -0700 | [diff] [blame] | 2219 | if file_path.is_url(remote): |
| 2220 | auth.ensure_logged_in(remote) |
| 2221 | |
Marc-Antoine Ruel | 8806e62 | 2014-02-12 14:15:53 -0500 | [diff] [blame] | 2222 | with get_storage(remote, options.namespace) as storage: |
Vadim Shtayura | 3172be5 | 2013-12-03 12:49:05 -0800 | [diff] [blame] | 2223 | # Fetching individual files. |
| 2224 | if options.file: |
| 2225 | channel = threading_utils.TaskChannel() |
| 2226 | pending = {} |
| 2227 | for digest, dest in options.file: |
| 2228 | pending[digest] = dest |
| 2229 | storage.async_fetch( |
| 2230 | channel, |
| 2231 | WorkerPool.MED, |
| 2232 | digest, |
| 2233 | UNKNOWN_FILE_SIZE, |
| 2234 | functools.partial(file_write, os.path.join(options.target, dest))) |
| 2235 | while pending: |
| 2236 | fetched = channel.pull() |
| 2237 | dest = pending.pop(fetched) |
| 2238 | logging.info('%s: %s', fetched, dest) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 2239 | |
Vadim Shtayura | 3172be5 | 2013-12-03 12:49:05 -0800 | [diff] [blame] | 2240 | # Fetching whole isolated tree. |
| 2241 | if options.isolated: |
| 2242 | settings = fetch_isolated( |
| 2243 | isolated_hash=options.isolated, |
| 2244 | storage=storage, |
| 2245 | cache=MemoryCache(), |
Vadim Shtayura | 3172be5 | 2013-12-03 12:49:05 -0800 | [diff] [blame] | 2246 | outdir=options.target, |
Vadim Shtayura | 3172be5 | 2013-12-03 12:49:05 -0800 | [diff] [blame] | 2247 | require_command=False) |
| 2248 | rel = os.path.join(options.target, settings.relative_cwd) |
| 2249 | print('To run this test please run from the directory %s:' % |
| 2250 | os.path.join(options.target, rel)) |
| 2251 | print(' ' + ' '.join(settings.command)) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 2252 | |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 2253 | return 0 |
| 2254 | |
| 2255 | |
Marc-Antoine Ruel | 488ce8f | 2014-02-09 11:25:04 -0500 | [diff] [blame] | 2256 | @subcommand.usage('<file1..fileN> or - to read from stdin') |
| 2257 | def CMDhashtable(parser, args): |
| 2258 | """Archives data to a hashtable on the file system. |
| 2259 | |
| 2260 | If a directory is specified, a .isolated file is created the whole directory |
| 2261 | is uploaded. Then this .isolated file can be included in another one to run |
| 2262 | commands. |
| 2263 | |
| 2264 | The commands output each file that was processed with its content hash. For |
| 2265 | directories, the .isolated generated for the directory is listed as the |
| 2266 | directory entry itself. |
| 2267 | """ |
| 2268 | add_outdir_options(parser) |
| 2269 | parser.add_option( |
| 2270 | '--blacklist', |
| 2271 | action='append', default=list(DEFAULT_BLACKLIST), |
| 2272 | help='List of regexp to use as blacklist filter when uploading ' |
| 2273 | 'directories') |
| 2274 | options, files = parser.parse_args(args) |
Marc-Antoine Ruel | 8806e62 | 2014-02-12 14:15:53 -0500 | [diff] [blame] | 2275 | process_outdir_options(parser, options, os.getcwd()) |
Marc-Antoine Ruel | 488ce8f | 2014-02-09 11:25:04 -0500 | [diff] [blame] | 2276 | try: |
| 2277 | # Do not compress files when archiving to the file system. |
| 2278 | archive(options.outdir, 'default', files, options.blacklist) |
| 2279 | except Error as e: |
| 2280 | parser.error(e.args[0]) |
| 2281 | return 0 |
| 2282 | |
| 2283 | |
Marc-Antoine Ruel | 8806e62 | 2014-02-12 14:15:53 -0500 | [diff] [blame] | 2284 | def add_isolate_server_options(parser, add_indir): |
| 2285 | """Adds --isolate-server and --namespace options to parser. |
| 2286 | |
| 2287 | Includes --indir if desired. |
| 2288 | """ |
Marc-Antoine Ruel | 1687b5e | 2014-02-06 17:47:53 -0500 | [diff] [blame] | 2289 | parser.add_option( |
| 2290 | '-I', '--isolate-server', |
| 2291 | metavar='URL', default=os.environ.get('ISOLATE_SERVER', ''), |
Marc-Antoine Ruel | 8806e62 | 2014-02-12 14:15:53 -0500 | [diff] [blame] | 2292 | help='URL of the Isolate Server to use. Defaults to the environment ' |
| 2293 | 'variable ISOLATE_SERVER if set. No need to specify https://, this ' |
| 2294 | 'is assumed.') |
Marc-Antoine Ruel | 1687b5e | 2014-02-06 17:47:53 -0500 | [diff] [blame] | 2295 | parser.add_option( |
| 2296 | '--namespace', default='default-gzip', |
| 2297 | help='The namespace to use on the Isolate Server, default: %default') |
Marc-Antoine Ruel | 8806e62 | 2014-02-12 14:15:53 -0500 | [diff] [blame] | 2298 | if add_indir: |
| 2299 | parser.add_option( |
| 2300 | '--indir', metavar='DIR', |
| 2301 | help='Directory used to store the hashtable instead of using an ' |
| 2302 | 'isolate server.') |
Marc-Antoine Ruel | 1687b5e | 2014-02-06 17:47:53 -0500 | [diff] [blame] | 2303 | |
| 2304 | |
| 2305 | def process_isolate_server_options(parser, options): |
Marc-Antoine Ruel | 8806e62 | 2014-02-12 14:15:53 -0500 | [diff] [blame] | 2306 | """Processes the --isolate-server and --indir options and aborts if neither is |
| 2307 | specified. |
Marc-Antoine Ruel | 1687b5e | 2014-02-06 17:47:53 -0500 | [diff] [blame] | 2308 | """ |
Marc-Antoine Ruel | 8806e62 | 2014-02-12 14:15:53 -0500 | [diff] [blame] | 2309 | has_indir = hasattr(options, 'indir') |
Marc-Antoine Ruel | 1687b5e | 2014-02-06 17:47:53 -0500 | [diff] [blame] | 2310 | if not options.isolate_server: |
Marc-Antoine Ruel | 8806e62 | 2014-02-12 14:15:53 -0500 | [diff] [blame] | 2311 | if not has_indir: |
| 2312 | parser.error('--isolate-server is required.') |
| 2313 | elif not options.indir: |
| 2314 | parser.error('Use one of --indir or --isolate-server.') |
| 2315 | else: |
| 2316 | if has_indir and options.indir: |
| 2317 | parser.error('Use only one of --indir or --isolate-server.') |
| 2318 | |
| 2319 | if options.isolate_server: |
| 2320 | parts = urlparse.urlparse(options.isolate_server, 'https') |
Marc-Antoine Ruel | 1687b5e | 2014-02-06 17:47:53 -0500 | [diff] [blame] | 2321 | if parts.query: |
| 2322 | parser.error('--isolate-server doesn\'t support query parameter.') |
| 2323 | if parts.fragment: |
| 2324 | parser.error('--isolate-server doesn\'t support fragment in the url.') |
Marc-Antoine Ruel | 8806e62 | 2014-02-12 14:15:53 -0500 | [diff] [blame] | 2325 | # urlparse('foo.com') will result in netloc='', path='foo.com', which is not |
| 2326 | # what is desired here. |
| 2327 | new = list(parts) |
| 2328 | if not new[1] and new[2]: |
| 2329 | new[1] = new[2].rstrip('/') |
| 2330 | new[2] = '' |
| 2331 | new[2] = new[2].rstrip('/') |
| 2332 | options.isolate_server = urlparse.urlunparse(new) |
Marc-Antoine Ruel | cfb6085 | 2014-07-02 15:22:00 -0400 | [diff] [blame] | 2333 | on_error.report_on_exception_exit(options.isolate_server) |
Marc-Antoine Ruel | 8806e62 | 2014-02-12 14:15:53 -0500 | [diff] [blame] | 2334 | return |
| 2335 | |
| 2336 | if file_path.is_url(options.indir): |
| 2337 | parser.error('Can\'t use an URL for --indir.') |
| 2338 | options.indir = unicode(options.indir).replace('/', os.path.sep) |
| 2339 | options.indir = os.path.abspath( |
| 2340 | os.path.normpath(os.path.join(os.getcwd(), options.indir))) |
| 2341 | if not os.path.isdir(options.indir): |
| 2342 | parser.error('Path given to --indir must exist.') |
| 2343 | |
Marc-Antoine Ruel | 1687b5e | 2014-02-06 17:47:53 -0500 | [diff] [blame] | 2344 | |
| 2345 | |
Marc-Antoine Ruel | 488ce8f | 2014-02-09 11:25:04 -0500 | [diff] [blame] | 2346 | def add_outdir_options(parser): |
Marc-Antoine Ruel | 8806e62 | 2014-02-12 14:15:53 -0500 | [diff] [blame] | 2347 | """Adds --outdir, which is orthogonal to --isolate-server. |
| 2348 | |
| 2349 | Note: On upload, separate commands are used between 'archive' and 'hashtable'. |
| 2350 | On 'download', the same command can download from either an isolate server or |
| 2351 | a file system. |
| 2352 | """ |
Marc-Antoine Ruel | 488ce8f | 2014-02-09 11:25:04 -0500 | [diff] [blame] | 2353 | parser.add_option( |
| 2354 | '-o', '--outdir', metavar='DIR', |
| 2355 | help='Directory used to recreate the tree.') |
| 2356 | |
| 2357 | |
Marc-Antoine Ruel | 8806e62 | 2014-02-12 14:15:53 -0500 | [diff] [blame] | 2358 | def process_outdir_options(parser, options, cwd): |
Marc-Antoine Ruel | 488ce8f | 2014-02-09 11:25:04 -0500 | [diff] [blame] | 2359 | if not options.outdir: |
| 2360 | parser.error('--outdir is required.') |
| 2361 | if file_path.is_url(options.outdir): |
Marc-Antoine Ruel | 8806e62 | 2014-02-12 14:15:53 -0500 | [diff] [blame] | 2362 | parser.error('Can\'t use an URL for --outdir.') |
Marc-Antoine Ruel | 488ce8f | 2014-02-09 11:25:04 -0500 | [diff] [blame] | 2363 | options.outdir = unicode(options.outdir).replace('/', os.path.sep) |
| 2364 | # outdir doesn't need native path case since tracing is never done from there. |
| 2365 | options.outdir = os.path.abspath( |
| 2366 | os.path.normpath(os.path.join(cwd, options.outdir))) |
| 2367 | # In theory, we'd create the directory outdir right away. Defer doing it in |
| 2368 | # case there's errors in the command line. |
| 2369 | |
| 2370 | |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 2371 | class OptionParserIsolateServer(tools.OptionParserWithLogging): |
| 2372 | def __init__(self, **kwargs): |
Marc-Antoine Ruel | ac54cb4 | 2013-11-18 14:05:35 -0500 | [diff] [blame] | 2373 | tools.OptionParserWithLogging.__init__( |
| 2374 | self, |
| 2375 | version=__version__, |
| 2376 | prog=os.path.basename(sys.modules[__name__].__file__), |
| 2377 | **kwargs) |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 2378 | auth.add_auth_options(self) |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 2379 | |
| 2380 | def parse_args(self, *args, **kwargs): |
| 2381 | options, args = tools.OptionParserWithLogging.parse_args( |
| 2382 | self, *args, **kwargs) |
Vadim Shtayura | 5d1efce | 2014-02-04 10:55:43 -0800 | [diff] [blame] | 2383 | auth.process_auth_options(self, options) |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 2384 | return options, args |
| 2385 | |
| 2386 | |
| 2387 | def main(args): |
| 2388 | dispatcher = subcommand.CommandDispatcher(__name__) |
Marc-Antoine Ruel | cfb6085 | 2014-07-02 15:22:00 -0400 | [diff] [blame] | 2389 | return dispatcher.execute(OptionParserIsolateServer(), args) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 2390 | |
| 2391 | |
| 2392 | if __name__ == '__main__': |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 2393 | fix_encoding.fix_encoding() |
| 2394 | tools.disable_buffering() |
| 2395 | colorama.init() |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 2396 | sys.exit(main(sys.argv[1:])) |