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 | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 6 | """Archives a set of files or directories to an Isolate Server.""" |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 7 | |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 8 | __version__ = '0.4.5' |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 9 | |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 10 | import base64 |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 11 | import functools |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 12 | import logging |
Marc-Antoine Ruel | a57d7db | 2014-10-15 20:31:19 -0400 | [diff] [blame] | 13 | import optparse |
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 |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 16 | import signal |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 17 | import sys |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 18 | import tempfile |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 19 | import threading |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 20 | import time |
Marc-Antoine Ruel | e98dde9 | 2015-01-22 14:53:05 -0500 | [diff] [blame] | 21 | import types |
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 |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 31 | from utils import fs |
Marc-Antoine Ruel | f74cffe | 2015-07-15 15:21:34 -0400 | [diff] [blame] | 32 | from utils import logging_utils |
Marc-Antoine Ruel | e4ad07e | 2014-10-15 20:22:29 -0400 | [diff] [blame] | 33 | from utils import lru |
vadimsh@chromium.org | 6b70621 | 2013-08-28 15:03:46 +0000 | [diff] [blame] | 34 | from utils import net |
Marc-Antoine Ruel | cfb6085 | 2014-07-02 15:22:00 -0400 | [diff] [blame] | 35 | from utils import on_error |
vadimsh@chromium.org | b074b16 | 2013-08-22 17:55:46 +0000 | [diff] [blame] | 36 | from utils import threading_utils |
vadimsh@chromium.org | a432647 | 2013-08-24 02:05:41 +0000 | [diff] [blame] | 37 | from utils import tools |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 38 | |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 39 | import auth |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 40 | import isolated_format |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 41 | |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 42 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 43 | # Version of isolate protocol passed to the server in /handshake request. |
| 44 | ISOLATE_PROTOCOL_VERSION = '1.0' |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 45 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 46 | |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 47 | # The file size to be used when we don't know the correct file size, |
| 48 | # generally used for .isolated files. |
| 49 | UNKNOWN_FILE_SIZE = None |
| 50 | |
| 51 | |
| 52 | # Maximum expected delay (in seconds) between successive file fetches or uploads |
| 53 | # in Storage. If it takes longer than that, a deadlock might be happening |
| 54 | # and all stack frames for all threads are dumped to log. |
| 55 | DEADLOCK_TIMEOUT = 5 * 60 |
| 56 | |
| 57 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 58 | # 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] | 59 | # All files are sorted by likelihood of a change in the file content |
| 60 | # (currently file size is used to estimate this: larger the file -> larger the |
| 61 | # 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] | 62 | # 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] | 63 | # and so on. Numbers here is a trade-off; the more per request, the lower the |
| 64 | # effect of HTTP round trip latency and TCP-level chattiness. On the other hand, |
| 65 | # larger values cause longer lookups, increasing the initial latency to start |
| 66 | # uploading, which is especially an issue for large files. This value is |
| 67 | # optimized for the "few thousands files to look up with minimal number of large |
| 68 | # files missing" case. |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 69 | ITEMS_PER_CONTAINS_QUERIES = (20, 20, 50, 50, 50, 100) |
csharp@chromium.org | 07fa759 | 2013-01-11 18:19:30 +0000 | [diff] [blame] | 70 | |
maruel@chromium.org | 9958e4a | 2013-09-17 00:01:48 +0000 | [diff] [blame] | 71 | |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 72 | # A list of already compressed extension types that should not receive any |
| 73 | # compression before being uploaded. |
| 74 | ALREADY_COMPRESSED_TYPES = [ |
Marc-Antoine Ruel | 7f234c8 | 2014-08-06 21:55:18 -0400 | [diff] [blame] | 75 | '7z', 'avi', 'cur', 'gif', 'h264', 'jar', 'jpeg', 'jpg', 'mp4', 'pdf', |
| 76 | 'png', 'wav', 'zip', |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 77 | ] |
| 78 | |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 79 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 80 | # Chunk size to use when reading from network stream. |
| 81 | NET_IO_FILE_CHUNK = 16 * 1024 |
| 82 | |
maruel@chromium.org | 8750e4b | 2013-09-18 02:37:57 +0000 | [diff] [blame] | 83 | |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 84 | # Read timeout in seconds for downloads from isolate storage. If there's no |
| 85 | # response from the server within this timeout whole download will be aborted. |
| 86 | DOWNLOAD_READ_TIMEOUT = 60 |
| 87 | |
| 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 | |
Marc-Antoine Ruel | ac54cb4 | 2013-11-18 14:05:35 -0500 | [diff] [blame] | 95 | DEFAULT_BLACKLIST = ( |
| 96 | # Temporary vim or python files. |
| 97 | r'^.+\.(?:pyc|swp)$', |
| 98 | # .git or .svn directory. |
| 99 | r'^(?:.+' + re.escape(os.path.sep) + r'|)\.(?:git|svn)$', |
| 100 | ) |
| 101 | |
| 102 | |
Vadim Shtayura | 8623c27 | 2014-12-01 11:45:27 -0800 | [diff] [blame] | 103 | # A class to use to communicate with the server by default. Can be changed by |
| 104 | # 'set_storage_api_class'. Default is IsolateServer. |
| 105 | _storage_api_cls = None |
| 106 | |
| 107 | |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 108 | class Error(Exception): |
| 109 | """Generic runtime error.""" |
| 110 | pass |
| 111 | |
| 112 | |
maruel | a72f46e | 2016-02-24 11:05:45 -0800 | [diff] [blame^] | 113 | class IsolatedErrorNoCommand(isolated_format.IsolatedError): |
| 114 | """Signals an early abort due to lack of command specified.""" |
| 115 | pass |
| 116 | |
| 117 | |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 118 | class Aborted(Error): |
| 119 | """Operation aborted.""" |
| 120 | pass |
| 121 | |
| 122 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 123 | def stream_read(stream, chunk_size): |
| 124 | """Reads chunks from |stream| and yields them.""" |
| 125 | while True: |
| 126 | data = stream.read(chunk_size) |
| 127 | if not data: |
| 128 | break |
| 129 | yield data |
| 130 | |
| 131 | |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 132 | def file_read(path, chunk_size=isolated_format.DISK_FILE_CHUNK, offset=0): |
Vadim Shtayura | f0cb97a | 2013-12-05 13:57:49 -0800 | [diff] [blame] | 133 | """Yields file content in chunks of |chunk_size| starting from |offset|.""" |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 134 | with fs.open(path, 'rb') as f: |
Vadim Shtayura | f0cb97a | 2013-12-05 13:57:49 -0800 | [diff] [blame] | 135 | if offset: |
| 136 | f.seek(offset) |
maruel@chromium.org | 8750e4b | 2013-09-18 02:37:57 +0000 | [diff] [blame] | 137 | while True: |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 138 | data = f.read(chunk_size) |
maruel@chromium.org | 8750e4b | 2013-09-18 02:37:57 +0000 | [diff] [blame] | 139 | if not data: |
| 140 | break |
| 141 | yield data |
| 142 | |
| 143 | |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 144 | def file_write(path, content_generator): |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 145 | """Writes file content as generated by content_generator. |
| 146 | |
maruel@chromium.org | 8750e4b | 2013-09-18 02:37:57 +0000 | [diff] [blame] | 147 | Creates the intermediary directory as needed. |
| 148 | |
| 149 | Returns the number of bytes written. |
| 150 | |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 151 | Meant to be mocked out in unit tests. |
| 152 | """ |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 153 | filedir = os.path.dirname(path) |
| 154 | if not fs.isdir(filedir): |
| 155 | fs.makedirs(filedir) |
maruel@chromium.org | 8750e4b | 2013-09-18 02:37:57 +0000 | [diff] [blame] | 156 | total = 0 |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 157 | with fs.open(path, 'wb') as f: |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 158 | for d in content_generator: |
maruel@chromium.org | 8750e4b | 2013-09-18 02:37:57 +0000 | [diff] [blame] | 159 | total += len(d) |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 160 | f.write(d) |
maruel@chromium.org | 8750e4b | 2013-09-18 02:37:57 +0000 | [diff] [blame] | 161 | return total |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 162 | |
| 163 | |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 164 | def zip_compress(content_generator, level=7): |
| 165 | """Reads chunks from |content_generator| and yields zip compressed chunks.""" |
| 166 | compressor = zlib.compressobj(level) |
| 167 | for chunk in content_generator: |
| 168 | compressed = compressor.compress(chunk) |
| 169 | if compressed: |
| 170 | yield compressed |
| 171 | tail = compressor.flush(zlib.Z_FINISH) |
| 172 | if tail: |
| 173 | yield tail |
| 174 | |
| 175 | |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 176 | def zip_decompress( |
| 177 | content_generator, chunk_size=isolated_format.DISK_FILE_CHUNK): |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 178 | """Reads zipped data from |content_generator| and yields decompressed data. |
| 179 | |
| 180 | Decompresses data in small chunks (no larger than |chunk_size|) so that |
| 181 | zip bomb file doesn't cause zlib to preallocate huge amount of memory. |
| 182 | |
| 183 | Raises IOError if data is corrupted or incomplete. |
| 184 | """ |
| 185 | decompressor = zlib.decompressobj() |
| 186 | compressed_size = 0 |
| 187 | try: |
| 188 | for chunk in content_generator: |
| 189 | compressed_size += len(chunk) |
| 190 | data = decompressor.decompress(chunk, chunk_size) |
| 191 | if data: |
| 192 | yield data |
| 193 | while decompressor.unconsumed_tail: |
| 194 | data = decompressor.decompress(decompressor.unconsumed_tail, chunk_size) |
| 195 | if data: |
| 196 | yield data |
| 197 | tail = decompressor.flush() |
| 198 | if tail: |
| 199 | yield tail |
| 200 | except zlib.error as e: |
| 201 | raise IOError( |
| 202 | 'Corrupted zip stream (read %d bytes) - %s' % (compressed_size, e)) |
| 203 | # Ensure all data was read and decompressed. |
| 204 | if decompressor.unused_data or decompressor.unconsumed_tail: |
| 205 | raise IOError('Not all data was decompressed') |
| 206 | |
| 207 | |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 208 | def get_zip_compression_level(filename): |
| 209 | """Given a filename calculates the ideal zip compression level to use.""" |
| 210 | file_ext = os.path.splitext(filename)[1].lower() |
| 211 | # TODO(csharp): Profile to find what compression level works best. |
| 212 | return 0 if file_ext in ALREADY_COMPRESSED_TYPES else 7 |
| 213 | |
| 214 | |
maruel@chromium.org | af25485 | 2013-09-17 17:48:14 +0000 | [diff] [blame] | 215 | def create_directories(base_directory, files): |
| 216 | """Creates the directory structure needed by the given list of files.""" |
| 217 | logging.debug('create_directories(%s, %d)', base_directory, len(files)) |
| 218 | # Creates the tree of directories to create. |
| 219 | directories = set(os.path.dirname(f) for f in files) |
| 220 | for item in list(directories): |
| 221 | while item: |
| 222 | directories.add(item) |
| 223 | item = os.path.dirname(item) |
| 224 | for d in sorted(directories): |
| 225 | if d: |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 226 | fs.mkdir(os.path.join(base_directory, d)) |
maruel@chromium.org | af25485 | 2013-09-17 17:48:14 +0000 | [diff] [blame] | 227 | |
| 228 | |
Marc-Antoine Ruel | ccafe0e | 2013-11-08 16:15:36 -0500 | [diff] [blame] | 229 | def create_symlinks(base_directory, files): |
| 230 | """Creates any symlinks needed by the given set of files.""" |
maruel@chromium.org | af25485 | 2013-09-17 17:48:14 +0000 | [diff] [blame] | 231 | for filepath, properties in files: |
| 232 | if 'l' not in properties: |
| 233 | continue |
| 234 | if sys.platform == 'win32': |
Marc-Antoine Ruel | ccafe0e | 2013-11-08 16:15:36 -0500 | [diff] [blame] | 235 | # TODO(maruel): Create symlink via the win32 api. |
maruel@chromium.org | af25485 | 2013-09-17 17:48:14 +0000 | [diff] [blame] | 236 | logging.warning('Ignoring symlink %s', filepath) |
| 237 | continue |
| 238 | outfile = os.path.join(base_directory, filepath) |
Marc-Antoine Ruel | ccafe0e | 2013-11-08 16:15:36 -0500 | [diff] [blame] | 239 | # os.symlink() doesn't exist on Windows. |
maruel@chromium.org | af25485 | 2013-09-17 17:48:14 +0000 | [diff] [blame] | 240 | os.symlink(properties['l'], outfile) # pylint: disable=E1101 |
maruel@chromium.org | af25485 | 2013-09-17 17:48:14 +0000 | [diff] [blame] | 241 | |
| 242 | |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 243 | def is_valid_file(path, size): |
maruel@chromium.org | dedbf49 | 2013-09-12 20:42:11 +0000 | [diff] [blame] | 244 | """Determines if the given files appears valid. |
| 245 | |
| 246 | Currently it just checks the file's size. |
| 247 | """ |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 248 | if size == UNKNOWN_FILE_SIZE: |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 249 | return fs.isfile(path) |
| 250 | actual_size = fs.stat(path).st_size |
maruel@chromium.org | dedbf49 | 2013-09-12 20:42:11 +0000 | [diff] [blame] | 251 | if size != actual_size: |
| 252 | logging.warning( |
| 253 | 'Found invalid item %s; %d != %d', |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 254 | os.path.basename(path), actual_size, size) |
maruel@chromium.org | dedbf49 | 2013-09-12 20:42:11 +0000 | [diff] [blame] | 255 | return False |
| 256 | return True |
| 257 | |
| 258 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 259 | class Item(object): |
| 260 | """An item to push to Storage. |
| 261 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 262 | Its digest and size may be provided in advance, if known. Otherwise they will |
| 263 | be derived from content(). If digest is provided, it MUST correspond to |
| 264 | hash algorithm used by Storage. |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 265 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 266 | When used with Storage, Item starts its life in a main thread, travels |
| 267 | to 'contains' thread, then to 'push' thread and then finally back to |
| 268 | the main thread. It is never used concurrently from multiple threads. |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 269 | """ |
| 270 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 271 | def __init__(self, digest=None, size=None, high_priority=False): |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 272 | self.digest = digest |
| 273 | self.size = size |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 274 | self.high_priority = high_priority |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 275 | self.compression_level = 6 |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 276 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 277 | def content(self): |
| 278 | """Iterable with content of this item as byte string (str) chunks.""" |
| 279 | raise NotImplementedError() |
| 280 | |
| 281 | def prepare(self, hash_algo): |
| 282 | """Ensures self.digest and self.size are set. |
| 283 | |
| 284 | Uses content() as a source of data to calculate them. Does nothing if digest |
| 285 | and size is already known. |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 286 | |
| 287 | Arguments: |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 288 | hash_algo: hash algorithm to use to calculate digest. |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 289 | """ |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 290 | if self.digest is None or self.size is None: |
| 291 | digest = hash_algo() |
| 292 | total = 0 |
| 293 | for chunk in self.content(): |
| 294 | digest.update(chunk) |
| 295 | total += len(chunk) |
| 296 | self.digest = digest.hexdigest() |
| 297 | self.size = total |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 298 | |
| 299 | |
| 300 | class FileItem(Item): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 301 | """A file to push to Storage. |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 302 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 303 | Its digest and size may be provided in advance, if known. Otherwise they will |
| 304 | be derived from the file content. |
| 305 | """ |
| 306 | |
| 307 | def __init__(self, path, digest=None, size=None, high_priority=False): |
| 308 | super(FileItem, self).__init__( |
| 309 | digest, |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 310 | size if size is not None else fs.stat(path).st_size, |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 311 | high_priority) |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 312 | self.path = path |
| 313 | self.compression_level = get_zip_compression_level(path) |
| 314 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 315 | def content(self): |
| 316 | return file_read(self.path) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 317 | |
| 318 | |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 319 | class BufferItem(Item): |
| 320 | """A byte buffer to push to Storage.""" |
| 321 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 322 | def __init__(self, buf, high_priority=False): |
| 323 | super(BufferItem, self).__init__(None, len(buf), high_priority) |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 324 | self.buffer = buf |
| 325 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 326 | def content(self): |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 327 | return [self.buffer] |
| 328 | |
| 329 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 330 | class Storage(object): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 331 | """Efficiently downloads or uploads large set of files via StorageApi. |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 332 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 333 | Implements compression support, parallel 'contains' checks, parallel uploads |
| 334 | and more. |
| 335 | |
| 336 | Works only within single namespace (and thus hashing algorithm and compression |
| 337 | scheme are fixed). |
| 338 | |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 339 | Spawns multiple internal threads. Thread safe, but not fork safe. Modifies |
| 340 | signal handlers table to handle Ctrl+C. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 341 | """ |
| 342 | |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 343 | def __init__(self, storage_api): |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 344 | self._storage_api = storage_api |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 345 | self._use_zip = isolated_format.is_namespace_with_compression( |
| 346 | storage_api.namespace) |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 347 | self._hash_algo = isolated_format.get_hash_algo(storage_api.namespace) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 348 | self._cpu_thread_pool = None |
| 349 | self._net_thread_pool = None |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 350 | self._aborted = False |
| 351 | self._prev_sig_handlers = {} |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 352 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 353 | @property |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 354 | def hash_algo(self): |
| 355 | """Hashing algorithm used to name files in storage based on their content. |
| 356 | |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 357 | Defined by |namespace|. See also isolated_format.get_hash_algo(). |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 358 | """ |
| 359 | return self._hash_algo |
| 360 | |
| 361 | @property |
| 362 | def location(self): |
Marc-Antoine Ruel | b10edf2 | 2014-12-11 13:33:57 -0500 | [diff] [blame] | 363 | """URL of the backing store that this class is using.""" |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 364 | return self._storage_api.location |
| 365 | |
| 366 | @property |
| 367 | def namespace(self): |
| 368 | """Isolate namespace used by this storage. |
| 369 | |
| 370 | Indirectly defines hashing scheme and compression method used. |
| 371 | """ |
| 372 | return self._storage_api.namespace |
| 373 | |
| 374 | @property |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 375 | def cpu_thread_pool(self): |
| 376 | """ThreadPool for CPU-bound tasks like zipping.""" |
| 377 | if self._cpu_thread_pool is None: |
Marc-Antoine Ruel | bdad118 | 2015-02-06 16:04:35 -0500 | [diff] [blame] | 378 | threads = max(threading_utils.num_processors(), 2) |
| 379 | if sys.maxsize <= 2L**32: |
| 380 | # On 32 bits userland, do not try to use more than 16 threads. |
| 381 | threads = min(threads, 16) |
| 382 | self._cpu_thread_pool = threading_utils.ThreadPool(2, threads, 0, 'zip') |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 383 | return self._cpu_thread_pool |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 384 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 385 | @property |
| 386 | def net_thread_pool(self): |
| 387 | """AutoRetryThreadPool for IO-bound tasks, retries IOError.""" |
| 388 | if self._net_thread_pool is None: |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 389 | self._net_thread_pool = threading_utils.IOAutoRetryThreadPool() |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 390 | return self._net_thread_pool |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 391 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 392 | def close(self): |
| 393 | """Waits for all pending tasks to finish.""" |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 394 | logging.info('Waiting for all threads to die...') |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 395 | if self._cpu_thread_pool: |
| 396 | self._cpu_thread_pool.join() |
| 397 | self._cpu_thread_pool.close() |
| 398 | self._cpu_thread_pool = None |
| 399 | if self._net_thread_pool: |
| 400 | self._net_thread_pool.join() |
| 401 | self._net_thread_pool.close() |
| 402 | self._net_thread_pool = None |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 403 | logging.info('Done.') |
| 404 | |
| 405 | def abort(self): |
| 406 | """Cancels any pending or future operations.""" |
| 407 | # This is not strictly theadsafe, but in the worst case the logging message |
| 408 | # will be printed twice. Not a big deal. In other places it is assumed that |
| 409 | # unprotected reads and writes to _aborted are serializable (it is true |
| 410 | # for python) and thus no locking is used. |
| 411 | if not self._aborted: |
| 412 | logging.warning('Aborting... It can take a while.') |
| 413 | self._aborted = True |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 414 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 415 | def __enter__(self): |
| 416 | """Context manager interface.""" |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 417 | assert not self._prev_sig_handlers, self._prev_sig_handlers |
| 418 | for s in (signal.SIGINT, signal.SIGTERM): |
| 419 | self._prev_sig_handlers[s] = signal.signal(s, lambda *_args: self.abort()) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 420 | return self |
| 421 | |
| 422 | def __exit__(self, _exc_type, _exc_value, _traceback): |
| 423 | """Context manager interface.""" |
| 424 | self.close() |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 425 | while self._prev_sig_handlers: |
| 426 | s, h = self._prev_sig_handlers.popitem() |
| 427 | signal.signal(s, h) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 428 | return False |
| 429 | |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 430 | def upload_items(self, items): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 431 | """Uploads a bunch of items to the isolate server. |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 432 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 433 | 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] | 434 | |
| 435 | Arguments: |
| 436 | items: list of Item instances that represents data to upload. |
| 437 | |
| 438 | Returns: |
| 439 | List of items that were uploaded. All other items are already there. |
| 440 | """ |
Vadim Shtayura | ea38c57 | 2014-10-06 16:57:16 -0700 | [diff] [blame] | 441 | logging.info('upload_items(items=%d)', len(items)) |
| 442 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 443 | # Ensure all digests are calculated. |
| 444 | for item in items: |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 445 | item.prepare(self._hash_algo) |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 446 | |
vadimsh@chromium.org | 672cd2b | 2013-10-08 17:49:33 +0000 | [diff] [blame] | 447 | # For each digest keep only first Item that matches it. All other items |
| 448 | # are just indistinguishable copies from the point of view of isolate |
| 449 | # server (it doesn't care about paths at all, only content and digests). |
| 450 | seen = {} |
| 451 | duplicates = 0 |
| 452 | for item in items: |
| 453 | if seen.setdefault(item.digest, item) is not item: |
| 454 | duplicates += 1 |
| 455 | items = seen.values() |
| 456 | if duplicates: |
Vadim Shtayura | ea38c57 | 2014-10-06 16:57:16 -0700 | [diff] [blame] | 457 | logging.info('Skipped %d files with duplicated content', duplicates) |
vadimsh@chromium.org | 672cd2b | 2013-10-08 17:49:33 +0000 | [diff] [blame] | 458 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 459 | # Enqueue all upload tasks. |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 460 | missing = set() |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 461 | uploaded = [] |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 462 | channel = threading_utils.TaskChannel() |
| 463 | for missing_item, push_state in self.get_missing_items(items): |
| 464 | missing.add(missing_item) |
| 465 | self.async_push(channel, missing_item, push_state) |
| 466 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 467 | # No need to spawn deadlock detector thread if there's nothing to upload. |
| 468 | if missing: |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 469 | with threading_utils.DeadlockDetector(DEADLOCK_TIMEOUT) as detector: |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 470 | # Wait for all started uploads to finish. |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 471 | while len(uploaded) != len(missing): |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 472 | detector.ping() |
| 473 | item = channel.pull() |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 474 | uploaded.append(item) |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 475 | logging.debug( |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 476 | 'Uploaded %d / %d: %s', len(uploaded), len(missing), item.digest) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 477 | logging.info('All files are uploaded') |
| 478 | |
| 479 | # Print stats. |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 480 | total = len(items) |
| 481 | total_size = sum(f.size for f in items) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 482 | logging.info( |
| 483 | 'Total: %6d, %9.1fkb', |
| 484 | total, |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 485 | total_size / 1024.) |
| 486 | cache_hit = set(items) - missing |
| 487 | cache_hit_size = sum(f.size for f in cache_hit) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 488 | logging.info( |
| 489 | 'cache hit: %6d, %9.1fkb, %6.2f%% files, %6.2f%% size', |
| 490 | len(cache_hit), |
| 491 | cache_hit_size / 1024., |
| 492 | len(cache_hit) * 100. / total, |
| 493 | cache_hit_size * 100. / total_size if total_size else 0) |
| 494 | cache_miss = missing |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 495 | cache_miss_size = sum(f.size for f in cache_miss) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 496 | logging.info( |
| 497 | 'cache miss: %6d, %9.1fkb, %6.2f%% files, %6.2f%% size', |
| 498 | len(cache_miss), |
| 499 | cache_miss_size / 1024., |
| 500 | len(cache_miss) * 100. / total, |
| 501 | cache_miss_size * 100. / total_size if total_size else 0) |
| 502 | |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 503 | return uploaded |
| 504 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 505 | def async_push(self, channel, item, push_state): |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 506 | """Starts asynchronous push to the server in a parallel thread. |
| 507 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 508 | Can be used only after |item| was checked for presence on a server with |
| 509 | 'get_missing_items' call. 'get_missing_items' returns |push_state| object |
| 510 | that contains storage specific information describing how to upload |
| 511 | the item (for example in case of cloud storage, it is signed upload URLs). |
| 512 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 513 | Arguments: |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 514 | channel: TaskChannel that receives back |item| when upload ends. |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 515 | item: item to upload as instance of Item class. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 516 | push_state: push state returned by 'get_missing_items' call for |item|. |
| 517 | |
| 518 | Returns: |
| 519 | None, but |channel| later receives back |item| when upload ends. |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 520 | """ |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 521 | # Thread pool task priority. |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 522 | priority = ( |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 523 | threading_utils.PRIORITY_HIGH if item.high_priority |
| 524 | else threading_utils.PRIORITY_MED) |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 525 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 526 | def push(content): |
Marc-Antoine Ruel | 095a8be | 2014-03-21 14:58:19 -0400 | [diff] [blame] | 527 | """Pushes an Item and returns it to |channel|.""" |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 528 | if self._aborted: |
| 529 | raise Aborted() |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 530 | item.prepare(self._hash_algo) |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 531 | self._storage_api.push(item, push_state, content) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 532 | return item |
| 533 | |
| 534 | # If zipping is not required, just start a push task. |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 535 | if not self._use_zip: |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 536 | self.net_thread_pool.add_task_with_channel( |
| 537 | channel, priority, push, item.content()) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 538 | return |
| 539 | |
| 540 | # If zipping is enabled, zip in a separate thread. |
| 541 | def zip_and_push(): |
| 542 | # TODO(vadimsh): Implement streaming uploads. Before it's done, assemble |
| 543 | # content right here. It will block until all file is zipped. |
| 544 | try: |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 545 | if self._aborted: |
| 546 | raise Aborted() |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 547 | stream = zip_compress(item.content(), item.compression_level) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 548 | data = ''.join(stream) |
| 549 | except Exception as exc: |
| 550 | logging.error('Failed to zip \'%s\': %s', item, exc) |
Vadim Shtayura | 0ffc409 | 2013-11-20 17:49:52 -0800 | [diff] [blame] | 551 | channel.send_exception() |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 552 | return |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 553 | self.net_thread_pool.add_task_with_channel( |
| 554 | channel, priority, push, [data]) |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 555 | self.cpu_thread_pool.add_task(priority, zip_and_push) |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 556 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 557 | def push(self, item, push_state): |
| 558 | """Synchronously pushes a single item to the server. |
| 559 | |
| 560 | If you need to push many items at once, consider using 'upload_items' or |
| 561 | 'async_push' with instance of TaskChannel. |
| 562 | |
| 563 | Arguments: |
| 564 | item: item to upload as instance of Item class. |
| 565 | push_state: push state returned by 'get_missing_items' call for |item|. |
| 566 | |
| 567 | Returns: |
| 568 | Pushed item (same object as |item|). |
| 569 | """ |
| 570 | channel = threading_utils.TaskChannel() |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 571 | with threading_utils.DeadlockDetector(DEADLOCK_TIMEOUT): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 572 | self.async_push(channel, item, push_state) |
| 573 | pushed = channel.pull() |
| 574 | assert pushed is item |
| 575 | return item |
| 576 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 577 | def async_fetch(self, channel, priority, digest, size, sink): |
| 578 | """Starts asynchronous fetch from the server in a parallel thread. |
| 579 | |
| 580 | Arguments: |
| 581 | channel: TaskChannel that receives back |digest| when download ends. |
| 582 | priority: thread pool task priority for the fetch. |
| 583 | digest: hex digest of an item to download. |
| 584 | size: expected size of the item (after decompression). |
| 585 | sink: function that will be called as sink(generator). |
| 586 | """ |
| 587 | def fetch(): |
| 588 | try: |
| 589 | # Prepare reading pipeline. |
| 590 | stream = self._storage_api.fetch(digest) |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 591 | if self._use_zip: |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 592 | stream = zip_decompress(stream, isolated_format.DISK_FILE_CHUNK) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 593 | # Run |stream| through verifier that will assert its size. |
| 594 | verifier = FetchStreamVerifier(stream, size) |
| 595 | # Verified stream goes to |sink|. |
| 596 | sink(verifier.run()) |
| 597 | except Exception as err: |
Vadim Shtayura | 0ffc409 | 2013-11-20 17:49:52 -0800 | [diff] [blame] | 598 | logging.error('Failed to fetch %s: %s', digest, err) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 599 | raise |
| 600 | return digest |
| 601 | |
| 602 | # Don't bother with zip_thread_pool for decompression. Decompression is |
| 603 | # really fast and most probably IO bound anyway. |
| 604 | self.net_thread_pool.add_task_with_channel(channel, priority, fetch) |
| 605 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 606 | def get_missing_items(self, items): |
| 607 | """Yields items that are missing from the server. |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 608 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 609 | Issues multiple parallel queries via StorageApi's 'contains' method. |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 610 | |
| 611 | Arguments: |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 612 | items: a list of Item objects to check. |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 613 | |
| 614 | Yields: |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 615 | For each missing item it yields a pair (item, push_state), where: |
| 616 | * item - Item object that is missing (one of |items|). |
| 617 | * push_state - opaque object that contains storage specific information |
| 618 | describing how to upload the item (for example in case of cloud |
| 619 | storage, it is signed upload URLs). It can later be passed to |
| 620 | 'async_push'. |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 621 | """ |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 622 | channel = threading_utils.TaskChannel() |
| 623 | pending = 0 |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 624 | |
| 625 | # Ensure all digests are calculated. |
| 626 | for item in items: |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 627 | item.prepare(self._hash_algo) |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 628 | |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 629 | def contains(batch): |
| 630 | if self._aborted: |
| 631 | raise Aborted() |
| 632 | return self._storage_api.contains(batch) |
| 633 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 634 | # Enqueue all requests. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 635 | for batch in batch_items_for_check(items): |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 636 | self.net_thread_pool.add_task_with_channel( |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 637 | channel, threading_utils.PRIORITY_HIGH, contains, batch) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 638 | pending += 1 |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 639 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 640 | # Yield results as they come in. |
| 641 | for _ in xrange(pending): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 642 | for missing_item, push_state in channel.pull().iteritems(): |
| 643 | yield missing_item, push_state |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 644 | |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 645 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 646 | def batch_items_for_check(items): |
| 647 | """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] | 648 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 649 | Each batch corresponds to a single 'exists?' query to the server via a call |
| 650 | to StorageApi's 'contains' method. |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 651 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 652 | Arguments: |
| 653 | items: a list of Item objects. |
| 654 | |
| 655 | Yields: |
| 656 | Batches of items to query for existence in a single operation, |
| 657 | each batch is a list of Item objects. |
| 658 | """ |
| 659 | batch_count = 0 |
| 660 | batch_size_limit = ITEMS_PER_CONTAINS_QUERIES[0] |
| 661 | next_queries = [] |
| 662 | for item in sorted(items, key=lambda x: x.size, reverse=True): |
| 663 | next_queries.append(item) |
| 664 | if len(next_queries) == batch_size_limit: |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 665 | yield next_queries |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 666 | next_queries = [] |
| 667 | batch_count += 1 |
| 668 | batch_size_limit = ITEMS_PER_CONTAINS_QUERIES[ |
| 669 | min(batch_count, len(ITEMS_PER_CONTAINS_QUERIES) - 1)] |
| 670 | if next_queries: |
| 671 | yield next_queries |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 672 | |
| 673 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 674 | class FetchQueue(object): |
| 675 | """Fetches items from Storage and places them into LocalCache. |
| 676 | |
| 677 | It manages multiple concurrent fetch operations. Acts as a bridge between |
| 678 | Storage and LocalCache so that Storage and LocalCache don't depend on each |
| 679 | other at all. |
| 680 | """ |
| 681 | |
| 682 | def __init__(self, storage, cache): |
| 683 | self.storage = storage |
| 684 | self.cache = cache |
| 685 | self._channel = threading_utils.TaskChannel() |
| 686 | self._pending = set() |
| 687 | self._accessed = set() |
| 688 | self._fetched = cache.cached_set() |
| 689 | |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 690 | def add( |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 691 | self, |
| 692 | digest, |
| 693 | size=UNKNOWN_FILE_SIZE, |
| 694 | priority=threading_utils.PRIORITY_MED): |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 695 | """Starts asynchronous fetch of item |digest|.""" |
| 696 | # Fetching it now? |
| 697 | if digest in self._pending: |
| 698 | return |
| 699 | |
| 700 | # Mark this file as in use, verify_all_cached will later ensure it is still |
| 701 | # in cache. |
| 702 | self._accessed.add(digest) |
| 703 | |
| 704 | # Already fetched? Notify cache to update item's LRU position. |
| 705 | if digest in self._fetched: |
| 706 | # 'touch' returns True if item is in cache and not corrupted. |
| 707 | if self.cache.touch(digest, size): |
| 708 | return |
| 709 | # Item is corrupted, remove it from cache and fetch it again. |
| 710 | self._fetched.remove(digest) |
| 711 | self.cache.evict(digest) |
| 712 | |
| 713 | # TODO(maruel): It should look at the free disk space, the current cache |
| 714 | # size and the size of the new item on every new item: |
| 715 | # - Trim the cache as more entries are listed when free disk space is low, |
| 716 | # otherwise if the amount of data downloaded during the run > free disk |
| 717 | # space, it'll crash. |
| 718 | # - Make sure there's enough free disk space to fit all dependencies of |
| 719 | # this run! If not, abort early. |
| 720 | |
| 721 | # Start fetching. |
| 722 | self._pending.add(digest) |
| 723 | self.storage.async_fetch( |
| 724 | self._channel, priority, digest, size, |
| 725 | functools.partial(self.cache.write, digest)) |
| 726 | |
| 727 | def wait(self, digests): |
| 728 | """Starts a loop that waits for at least one of |digests| to be retrieved. |
| 729 | |
| 730 | Returns the first digest retrieved. |
| 731 | """ |
| 732 | # Flush any already fetched items. |
| 733 | for digest in digests: |
| 734 | if digest in self._fetched: |
| 735 | return digest |
| 736 | |
| 737 | # Ensure all requested items are being fetched now. |
| 738 | assert all(digest in self._pending for digest in digests), ( |
| 739 | digests, self._pending) |
| 740 | |
| 741 | # Wait for some requested item to finish fetching. |
| 742 | while self._pending: |
| 743 | digest = self._channel.pull() |
| 744 | self._pending.remove(digest) |
| 745 | self._fetched.add(digest) |
| 746 | if digest in digests: |
| 747 | return digest |
| 748 | |
| 749 | # Should never reach this point due to assert above. |
| 750 | raise RuntimeError('Impossible state') |
| 751 | |
| 752 | def inject_local_file(self, path, algo): |
| 753 | """Adds local file to the cache as if it was fetched from storage.""" |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 754 | with fs.open(path, 'rb') as f: |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 755 | data = f.read() |
| 756 | digest = algo(data).hexdigest() |
| 757 | self.cache.write(digest, [data]) |
| 758 | self._fetched.add(digest) |
| 759 | return digest |
| 760 | |
| 761 | @property |
| 762 | def pending_count(self): |
| 763 | """Returns number of items to be fetched.""" |
| 764 | return len(self._pending) |
| 765 | |
| 766 | def verify_all_cached(self): |
| 767 | """True if all accessed items are in cache.""" |
| 768 | return self._accessed.issubset(self.cache.cached_set()) |
| 769 | |
| 770 | |
| 771 | class FetchStreamVerifier(object): |
| 772 | """Verifies that fetched file is valid before passing it to the LocalCache.""" |
| 773 | |
| 774 | def __init__(self, stream, expected_size): |
Marc-Antoine Ruel | df4976d | 2015-04-15 19:56:21 -0400 | [diff] [blame] | 775 | assert stream is not None |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 776 | self.stream = stream |
| 777 | self.expected_size = expected_size |
| 778 | self.current_size = 0 |
| 779 | |
| 780 | def run(self): |
| 781 | """Generator that yields same items as |stream|. |
| 782 | |
| 783 | Verifies |stream| is complete before yielding a last chunk to consumer. |
| 784 | |
| 785 | Also wraps IOError produced by consumer into MappingError exceptions since |
| 786 | otherwise Storage will retry fetch on unrelated local cache errors. |
| 787 | """ |
| 788 | # Read one chunk ahead, keep it in |stored|. |
| 789 | # That way a complete stream can be verified before pushing last chunk |
| 790 | # to consumer. |
| 791 | stored = None |
| 792 | for chunk in self.stream: |
| 793 | assert chunk is not None |
| 794 | if stored is not None: |
| 795 | self._inspect_chunk(stored, is_last=False) |
| 796 | try: |
| 797 | yield stored |
| 798 | except IOError as exc: |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 799 | raise isolated_format.MappingError( |
| 800 | 'Failed to store an item in cache: %s' % exc) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 801 | stored = chunk |
| 802 | if stored is not None: |
| 803 | self._inspect_chunk(stored, is_last=True) |
| 804 | try: |
| 805 | yield stored |
| 806 | except IOError as exc: |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 807 | raise isolated_format.MappingError( |
| 808 | 'Failed to store an item in cache: %s' % exc) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 809 | |
| 810 | def _inspect_chunk(self, chunk, is_last): |
| 811 | """Called for each fetched chunk before passing it to consumer.""" |
| 812 | self.current_size += len(chunk) |
Marc-Antoine Ruel | 1e7658c | 2014-08-28 19:46:39 -0400 | [diff] [blame] | 813 | if (is_last and |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 814 | (self.expected_size != UNKNOWN_FILE_SIZE) and |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 815 | (self.expected_size != self.current_size)): |
| 816 | raise IOError('Incorrect file size: expected %d, got %d' % ( |
| 817 | self.expected_size, self.current_size)) |
| 818 | |
| 819 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 820 | class StorageApi(object): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 821 | """Interface for classes that implement low-level storage operations. |
| 822 | |
| 823 | StorageApi is oblivious of compression and hashing scheme used. This details |
| 824 | are handled in higher level Storage class. |
| 825 | |
| 826 | Clients should generally not use StorageApi directly. Storage class is |
| 827 | preferred since it implements compression and upload optimizations. |
| 828 | """ |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 829 | |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 830 | @property |
| 831 | def location(self): |
Marc-Antoine Ruel | b10edf2 | 2014-12-11 13:33:57 -0500 | [diff] [blame] | 832 | """URL of the backing store that this class is using.""" |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 833 | raise NotImplementedError() |
| 834 | |
| 835 | @property |
| 836 | def namespace(self): |
| 837 | """Isolate namespace used by this storage. |
| 838 | |
| 839 | Indirectly defines hashing scheme and compression method used. |
| 840 | """ |
| 841 | raise NotImplementedError() |
| 842 | |
Vadim Shtayura | f0cb97a | 2013-12-05 13:57:49 -0800 | [diff] [blame] | 843 | def fetch(self, digest, offset=0): |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 844 | """Fetches an object and yields its content. |
| 845 | |
| 846 | Arguments: |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 847 | digest: hash digest of item to download. |
Vadim Shtayura | f0cb97a | 2013-12-05 13:57:49 -0800 | [diff] [blame] | 848 | 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] | 849 | |
| 850 | Yields: |
| 851 | Chunks of downloaded item (as str objects). |
| 852 | """ |
| 853 | raise NotImplementedError() |
| 854 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 855 | def push(self, item, push_state, content=None): |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 856 | """Uploads an |item| with content generated by |content| generator. |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 857 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 858 | |item| MUST go through 'contains' call to get |push_state| before it can |
| 859 | be pushed to the storage. |
| 860 | |
| 861 | To be clear, here is one possible usage: |
| 862 | all_items = [... all items to push as Item subclasses ...] |
| 863 | for missing_item, push_state in storage_api.contains(all_items).items(): |
| 864 | storage_api.push(missing_item, push_state) |
| 865 | |
| 866 | When pushing to a namespace with compression, data that should be pushed |
| 867 | and data provided by the item is not the same. In that case |content| is |
| 868 | not None and it yields chunks of compressed data (using item.content() as |
| 869 | a source of original uncompressed data). This is implemented by Storage |
| 870 | class. |
| 871 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 872 | Arguments: |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 873 | item: Item object that holds information about an item being pushed. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 874 | push_state: push state object as returned by 'contains' call. |
| 875 | 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] | 876 | |
| 877 | Returns: |
| 878 | None. |
| 879 | """ |
| 880 | raise NotImplementedError() |
| 881 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 882 | def contains(self, items): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 883 | """Checks for |items| on the server, prepares missing ones for upload. |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 884 | |
| 885 | Arguments: |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 886 | items: list of Item objects to check for presence. |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 887 | |
| 888 | Returns: |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 889 | A dict missing Item -> opaque push state object to be passed to 'push'. |
| 890 | See doc string for 'push'. |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 891 | """ |
| 892 | raise NotImplementedError() |
| 893 | |
| 894 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 895 | class _IsolateServerPushState(object): |
| 896 | """Per-item state passed from IsolateServer.contains to IsolateServer.push. |
Mike Frysinger | 27f03da | 2014-02-12 16:47:01 -0500 | [diff] [blame] | 897 | |
| 898 | Note this needs to be a global class to support pickling. |
| 899 | """ |
| 900 | |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 901 | def __init__(self, preupload_status, size): |
| 902 | self.preupload_status = preupload_status |
| 903 | gs_upload_url = preupload_status.get('gs_upload_url') or None |
| 904 | if gs_upload_url: |
| 905 | self.upload_url = gs_upload_url |
| 906 | self.finalize_url = '_ah/api/isolateservice/v1/finalize_gs_upload' |
| 907 | else: |
| 908 | self.upload_url = '_ah/api/isolateservice/v1/store_inline' |
| 909 | self.finalize_url = None |
Mike Frysinger | 27f03da | 2014-02-12 16:47:01 -0500 | [diff] [blame] | 910 | self.uploaded = False |
| 911 | self.finalized = False |
Marc-Antoine Ruel | e98dde9 | 2015-01-22 14:53:05 -0500 | [diff] [blame] | 912 | self.size = size |
Mike Frysinger | 27f03da | 2014-02-12 16:47:01 -0500 | [diff] [blame] | 913 | |
| 914 | |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 915 | class IsolateServer(StorageApi): |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 916 | """StorageApi implementation that downloads and uploads to Isolate Server. |
| 917 | |
| 918 | It uploads and downloads directly from Google Storage whenever appropriate. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 919 | Works only within single namespace. |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 920 | """ |
| 921 | |
maruel@chromium.org | 3e42ce8 | 2013-09-12 18:36:59 +0000 | [diff] [blame] | 922 | def __init__(self, base_url, namespace): |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 923 | super(IsolateServer, self).__init__() |
Marc-Antoine Ruel | b10edf2 | 2014-12-11 13:33:57 -0500 | [diff] [blame] | 924 | assert file_path.is_url(base_url), base_url |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 925 | self._base_url = base_url.rstrip('/') |
| 926 | self._namespace = namespace |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 927 | self._namespace_dict = { |
| 928 | 'compression': 'flate' if namespace.endswith( |
| 929 | ('-gzip', '-flate')) else '', |
| 930 | 'digest_hash': 'sha-1', |
| 931 | 'namespace': namespace, |
| 932 | } |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 933 | self._lock = threading.Lock() |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 934 | self._server_caps = None |
Marc-Antoine Ruel | e98dde9 | 2015-01-22 14:53:05 -0500 | [diff] [blame] | 935 | self._memory_use = 0 |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 936 | |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 937 | @property |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 938 | def _server_capabilities(self): |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 939 | """Gets server details. |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 940 | |
| 941 | Returns: |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 942 | Server capabilities dictionary as returned by /server_details endpoint. |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 943 | """ |
maruel@chromium.org | 3e42ce8 | 2013-09-12 18:36:59 +0000 | [diff] [blame] | 944 | # TODO(maruel): Make this request much earlier asynchronously while the |
| 945 | # files are being enumerated. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 946 | |
| 947 | # TODO(vadimsh): Put |namespace| in the URL so that server can apply |
| 948 | # namespace-level ACLs to this call. |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 949 | |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 950 | with self._lock: |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 951 | if self._server_caps is None: |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 952 | self._server_caps = net.url_read_json( |
| 953 | url='%s/_ah/api/isolateservice/v1/server_details' % self._base_url, |
| 954 | data={}) |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 955 | return self._server_caps |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 956 | |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 957 | @property |
| 958 | def location(self): |
| 959 | return self._base_url |
| 960 | |
| 961 | @property |
| 962 | def namespace(self): |
| 963 | return self._namespace |
| 964 | |
Vadim Shtayura | f0cb97a | 2013-12-05 13:57:49 -0800 | [diff] [blame] | 965 | def fetch(self, digest, offset=0): |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 966 | assert offset >= 0 |
| 967 | source_url = '%s/_ah/api/isolateservice/v1/retrieve' % ( |
| 968 | self._base_url) |
Vadim Shtayura | f0cb97a | 2013-12-05 13:57:49 -0800 | [diff] [blame] | 969 | logging.debug('download_file(%s, %d)', source_url, offset) |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 970 | response = self.do_fetch(source_url, digest, offset) |
maruel@chromium.org | e45728d | 2013-09-16 23:23:22 +0000 | [diff] [blame] | 971 | |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 972 | if not response: |
maruel | e154f9c | 2015-09-14 11:03:15 -0700 | [diff] [blame] | 973 | raise IOError( |
| 974 | 'Attempted to fetch from %s; no data exist: %s / %s.' % ( |
| 975 | source_url, self._namespace, digest)) |
Vadim Shtayura | f0cb97a | 2013-12-05 13:57:49 -0800 | [diff] [blame] | 976 | |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 977 | # for DB uploads |
| 978 | content = response.get('content') |
| 979 | if content is not None: |
| 980 | return base64.b64decode(content) |
| 981 | |
| 982 | # for GS entities |
| 983 | connection = net.url_open(response['url']) |
maruel | f557475 | 2015-09-17 13:40:27 -0700 | [diff] [blame] | 984 | if not connection: |
| 985 | raise IOError('Failed to download %s / %s' % (self._namespace, digest)) |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 986 | |
| 987 | # If |offset|, verify server respects it by checking Content-Range. |
Vadim Shtayura | f0cb97a | 2013-12-05 13:57:49 -0800 | [diff] [blame] | 988 | if offset: |
| 989 | content_range = connection.get_header('Content-Range') |
| 990 | if not content_range: |
| 991 | raise IOError('Missing Content-Range header') |
| 992 | |
| 993 | # 'Content-Range' format is 'bytes <offset>-<last_byte_index>/<size>'. |
| 994 | # According to a spec, <size> can be '*' meaning "Total size of the file |
| 995 | # is not known in advance". |
| 996 | try: |
| 997 | match = re.match(r'bytes (\d+)-(\d+)/(\d+|\*)', content_range) |
| 998 | if not match: |
| 999 | raise ValueError() |
| 1000 | content_offset = int(match.group(1)) |
| 1001 | last_byte_index = int(match.group(2)) |
| 1002 | size = None if match.group(3) == '*' else int(match.group(3)) |
| 1003 | except ValueError: |
| 1004 | raise IOError('Invalid Content-Range header: %s' % content_range) |
| 1005 | |
| 1006 | # Ensure returned offset equals requested one. |
| 1007 | if offset != content_offset: |
| 1008 | raise IOError('Expecting offset %d, got %d (Content-Range is %s)' % ( |
| 1009 | offset, content_offset, content_range)) |
| 1010 | |
| 1011 | # Ensure entire tail of the file is returned. |
| 1012 | if size is not None and last_byte_index + 1 != size: |
| 1013 | raise IOError('Incomplete response. Content-Range: %s' % content_range) |
| 1014 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1015 | return stream_read(connection, NET_IO_FILE_CHUNK) |
maruel@chromium.org | e45728d | 2013-09-16 23:23:22 +0000 | [diff] [blame] | 1016 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1017 | def push(self, item, push_state, content=None): |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1018 | assert isinstance(item, Item) |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1019 | assert item.digest is not None |
| 1020 | assert item.size is not None |
| 1021 | assert isinstance(push_state, _IsolateServerPushState) |
| 1022 | assert not push_state.finalized |
| 1023 | |
| 1024 | # Default to item.content(). |
| 1025 | content = item.content() if content is None else content |
Marc-Antoine Ruel | e98dde9 | 2015-01-22 14:53:05 -0500 | [diff] [blame] | 1026 | logging.info('Push state size: %d', push_state.size) |
| 1027 | if isinstance(content, (basestring, list)): |
| 1028 | # Memory is already used, too late. |
| 1029 | with self._lock: |
| 1030 | self._memory_use += push_state.size |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 1031 | else: |
Marc-Antoine Ruel | e98dde9 | 2015-01-22 14:53:05 -0500 | [diff] [blame] | 1032 | # TODO(vadimsh): Do not read from |content| generator when retrying push. |
| 1033 | # If |content| is indeed a generator, it can not be re-winded back to the |
| 1034 | # beginning of the stream. A retry will find it exhausted. A possible |
| 1035 | # solution is to wrap |content| generator with some sort of caching |
| 1036 | # restartable generator. It should be done alongside streaming support |
| 1037 | # implementation. |
| 1038 | # |
| 1039 | # In theory, we should keep the generator, so that it is not serialized in |
| 1040 | # memory. Sadly net.HttpService.request() requires the body to be |
| 1041 | # serialized. |
| 1042 | assert isinstance(content, types.GeneratorType), repr(content) |
| 1043 | slept = False |
| 1044 | # HACK HACK HACK. Please forgive me for my sins but OMG, it works! |
Marc-Antoine Ruel | e6677c8 | 2015-02-05 14:54:22 -0500 | [diff] [blame] | 1045 | # One byte less than 512mb. This is to cope with incompressible content. |
| 1046 | max_size = int(sys.maxsize * 0.25) |
Marc-Antoine Ruel | e98dde9 | 2015-01-22 14:53:05 -0500 | [diff] [blame] | 1047 | while True: |
| 1048 | with self._lock: |
| 1049 | # This is due to 32 bits python when uploading very large files. The |
| 1050 | # problem is that it's comparing uncompressed sizes, while we care |
| 1051 | # about compressed sizes since it's what is serialized in memory. |
| 1052 | # The first check assumes large files are compressible and that by |
| 1053 | # throttling one upload at once, we can survive. Otherwise, kaboom. |
| 1054 | memory_use = self._memory_use |
| 1055 | if ((push_state.size >= max_size and not memory_use) or |
| 1056 | (memory_use + push_state.size <= max_size)): |
| 1057 | self._memory_use += push_state.size |
| 1058 | memory_use = self._memory_use |
| 1059 | break |
| 1060 | time.sleep(0.1) |
| 1061 | slept = True |
| 1062 | if slept: |
| 1063 | logging.info('Unblocked: %d %d', memory_use, push_state.size) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 1064 | |
Marc-Antoine Ruel | e98dde9 | 2015-01-22 14:53:05 -0500 | [diff] [blame] | 1065 | try: |
| 1066 | # This push operation may be a retry after failed finalization call below, |
| 1067 | # no need to reupload contents in that case. |
| 1068 | if not push_state.uploaded: |
| 1069 | # PUT file to |upload_url|. |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 1070 | success = self.do_push(push_state, content) |
Marc-Antoine Ruel | e98dde9 | 2015-01-22 14:53:05 -0500 | [diff] [blame] | 1071 | if not success: |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 1072 | raise IOError('Failed to upload file with hash %s to URL %s' % ( |
Marc-Antoine Ruel | e98dde9 | 2015-01-22 14:53:05 -0500 | [diff] [blame] | 1073 | item.digest, push_state.upload_url)) |
| 1074 | push_state.uploaded = True |
| 1075 | else: |
| 1076 | logging.info( |
| 1077 | 'A file %s already uploaded, retrying finalization only', |
| 1078 | item.digest) |
| 1079 | |
| 1080 | # Optionally notify the server that it's done. |
| 1081 | if push_state.finalize_url: |
| 1082 | # TODO(vadimsh): Calculate MD5 or CRC32C sum while uploading a file and |
| 1083 | # send it to isolated server. That way isolate server can verify that |
| 1084 | # the data safely reached Google Storage (GS provides MD5 and CRC32C of |
| 1085 | # stored files). |
| 1086 | # TODO(maruel): Fix the server to accept properly data={} so |
| 1087 | # url_read_json() can be used. |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 1088 | response = net.url_read_json( |
| 1089 | url='%s/%s' % (self._base_url, push_state.finalize_url), |
| 1090 | data={ |
| 1091 | 'upload_ticket': push_state.preupload_status['upload_ticket'], |
| 1092 | }) |
| 1093 | if not response or not response['ok']: |
| 1094 | raise IOError('Failed to finalize file with hash %s.' % item.digest) |
Marc-Antoine Ruel | e98dde9 | 2015-01-22 14:53:05 -0500 | [diff] [blame] | 1095 | push_state.finalized = True |
| 1096 | finally: |
| 1097 | with self._lock: |
| 1098 | self._memory_use -= push_state.size |
maruel@chromium.org | d1e20c9 | 2013-09-17 20:54:26 +0000 | [diff] [blame] | 1099 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1100 | def contains(self, items): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1101 | # Ensure all items were initialized with 'prepare' call. Storage does that. |
| 1102 | assert all(i.digest is not None and i.size is not None for i in items) |
| 1103 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1104 | # Request body is a json encoded list of dicts. |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 1105 | body = { |
| 1106 | 'items': [ |
| 1107 | { |
| 1108 | 'digest': item.digest, |
| 1109 | 'is_isolated': bool(item.high_priority), |
| 1110 | 'size': item.size, |
| 1111 | } for item in items |
| 1112 | ], |
| 1113 | 'namespace': self._namespace_dict, |
| 1114 | } |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1115 | |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 1116 | query_url = '%s/_ah/api/isolateservice/v1/preupload' % self._base_url |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1117 | |
| 1118 | # 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] | 1119 | response = None |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1120 | try: |
Marc-Antoine Ruel | 0a62061 | 2014-08-13 15:47:07 -0400 | [diff] [blame] | 1121 | response = net.url_read_json(url=query_url, data=body) |
| 1122 | if response is None: |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 1123 | raise isolated_format.MappingError( |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 1124 | 'Failed to execute preupload query') |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1125 | except ValueError as err: |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 1126 | raise isolated_format.MappingError( |
Marc-Antoine Ruel | 0a62061 | 2014-08-13 15:47:07 -0400 | [diff] [blame] | 1127 | 'Invalid response from server: %s, body is %s' % (err, response)) |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1128 | |
| 1129 | # Pick Items that are missing, attach _PushState to them. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1130 | missing_items = {} |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 1131 | for preupload_status in response.get('items', []): |
| 1132 | assert 'upload_ticket' in preupload_status, ( |
| 1133 | preupload_status, '/preupload did not generate an upload ticket') |
| 1134 | index = int(preupload_status['index']) |
| 1135 | missing_items[items[index]] = _IsolateServerPushState( |
| 1136 | preupload_status, items[index].size) |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 1137 | logging.info('Queried %d files, %d cache hit', |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 1138 | len(items), len(items) - len(missing_items)) |
| 1139 | return missing_items |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 1140 | |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 1141 | def do_fetch(self, url, digest, offset): |
Vadim Shtayura | 8623c27 | 2014-12-01 11:45:27 -0800 | [diff] [blame] | 1142 | """Fetches isolated data from the URL. |
| 1143 | |
| 1144 | Used only for fetching files, not for API calls. Can be overridden in |
| 1145 | subclasses. |
| 1146 | |
| 1147 | Args: |
| 1148 | url: URL to fetch the data from, can possibly return http redirect. |
| 1149 | offset: byte offset inside the file to start fetching from. |
| 1150 | |
| 1151 | Returns: |
| 1152 | net.HttpResponse compatible object, with 'read' and 'get_header' calls. |
| 1153 | """ |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 1154 | assert isinstance(offset, int) |
| 1155 | data = { |
| 1156 | 'digest': digest.encode('utf-8'), |
| 1157 | 'namespace': self._namespace_dict, |
| 1158 | 'offset': offset, |
| 1159 | } |
maruel | 0c25f4f | 2015-12-15 05:41:17 -0800 | [diff] [blame] | 1160 | # TODO(maruel): url + '?' + urllib.urlencode(data) once a HTTP GET endpoint |
| 1161 | # is added. |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 1162 | return net.url_read_json( |
| 1163 | url=url, |
| 1164 | data=data, |
| 1165 | read_timeout=DOWNLOAD_READ_TIMEOUT) |
Vadim Shtayura | 8623c27 | 2014-12-01 11:45:27 -0800 | [diff] [blame] | 1166 | |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 1167 | def do_push(self, push_state, content): |
Vadim Shtayura | 8623c27 | 2014-12-01 11:45:27 -0800 | [diff] [blame] | 1168 | """Uploads isolated file to the URL. |
| 1169 | |
| 1170 | Used only for storing files, not for API calls. Can be overridden in |
| 1171 | subclasses. |
| 1172 | |
| 1173 | Args: |
| 1174 | url: URL to upload the data to. |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 1175 | push_state: an _IsolateServicePushState instance |
| 1176 | item: the original Item to be uploaded |
Vadim Shtayura | 8623c27 | 2014-12-01 11:45:27 -0800 | [diff] [blame] | 1177 | content: an iterable that yields 'str' chunks. |
Vadim Shtayura | 8623c27 | 2014-12-01 11:45:27 -0800 | [diff] [blame] | 1178 | """ |
| 1179 | # A cheezy way to avoid memcpy of (possibly huge) file, until streaming |
| 1180 | # upload support is implemented. |
| 1181 | if isinstance(content, list) and len(content) == 1: |
| 1182 | content = content[0] |
| 1183 | else: |
| 1184 | content = ''.join(content) |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 1185 | |
| 1186 | # DB upload |
| 1187 | if not push_state.finalize_url: |
| 1188 | url = '%s/%s' % (self._base_url, push_state.upload_url) |
| 1189 | content = base64.b64encode(content) |
| 1190 | data = { |
| 1191 | 'upload_ticket': push_state.preupload_status['upload_ticket'], |
| 1192 | 'content': content, |
| 1193 | } |
| 1194 | response = net.url_read_json(url=url, data=data) |
| 1195 | return response is not None and response['ok'] |
| 1196 | |
| 1197 | # upload to GS |
| 1198 | url = push_state.upload_url |
Vadim Shtayura | 8623c27 | 2014-12-01 11:45:27 -0800 | [diff] [blame] | 1199 | response = net.url_read( |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 1200 | content_type='application/octet-stream', |
| 1201 | data=content, |
| 1202 | method='PUT', |
tandrii | b44d54d | 2016-02-10 11:31:41 -0800 | [diff] [blame] | 1203 | headers={'Cache-Control': 'public, max-age=31536000'}, |
Cory Massaro | cc19c8c | 2015-03-10 13:35:11 -0700 | [diff] [blame] | 1204 | url=url) |
Vadim Shtayura | 8623c27 | 2014-12-01 11:45:27 -0800 | [diff] [blame] | 1205 | return response is not None |
| 1206 | |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 1207 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1208 | class LocalCache(object): |
| 1209 | """Local cache that stores objects fetched via Storage. |
| 1210 | |
| 1211 | It can be accessed concurrently from multiple threads, so it should protect |
| 1212 | its internal state with some lock. |
| 1213 | """ |
Marc-Antoine Ruel | 2283ad1 | 2014-02-09 11:14:57 -0500 | [diff] [blame] | 1214 | cache_dir = None |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1215 | |
| 1216 | def __enter__(self): |
| 1217 | """Context manager interface.""" |
| 1218 | return self |
| 1219 | |
| 1220 | def __exit__(self, _exc_type, _exec_value, _traceback): |
| 1221 | """Context manager interface.""" |
| 1222 | return False |
| 1223 | |
| 1224 | def cached_set(self): |
| 1225 | """Returns a set of all cached digests (always a new object).""" |
| 1226 | raise NotImplementedError() |
| 1227 | |
| 1228 | def touch(self, digest, size): |
| 1229 | """Ensures item is not corrupted and updates its LRU position. |
| 1230 | |
| 1231 | Arguments: |
| 1232 | digest: hash digest of item to check. |
| 1233 | size: expected size of this item. |
| 1234 | |
| 1235 | Returns: |
| 1236 | True if item is in cache and not corrupted. |
| 1237 | """ |
| 1238 | raise NotImplementedError() |
| 1239 | |
| 1240 | def evict(self, digest): |
| 1241 | """Removes item from cache if it's there.""" |
| 1242 | raise NotImplementedError() |
| 1243 | |
| 1244 | def read(self, digest): |
| 1245 | """Returns contents of the cached item as a single str.""" |
| 1246 | raise NotImplementedError() |
| 1247 | |
| 1248 | def write(self, digest, content): |
| 1249 | """Reads data from |content| generator and stores it in cache.""" |
| 1250 | raise NotImplementedError() |
| 1251 | |
Marc-Antoine Ruel | fb199cf | 2013-11-12 15:38:12 -0500 | [diff] [blame] | 1252 | def hardlink(self, digest, dest, file_mode): |
| 1253 | """Ensures file at |dest| has same content as cached |digest|. |
| 1254 | |
| 1255 | If file_mode is provided, it is used to set the executable bit if |
| 1256 | applicable. |
| 1257 | """ |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1258 | raise NotImplementedError() |
| 1259 | |
| 1260 | |
| 1261 | class MemoryCache(LocalCache): |
| 1262 | """LocalCache implementation that stores everything in memory.""" |
| 1263 | |
Vadim Shtayura | e3fbd10 | 2014-04-29 17:05:21 -0700 | [diff] [blame] | 1264 | def __init__(self, file_mode_mask=0500): |
| 1265 | """Args: |
| 1266 | file_mode_mask: bit mask to AND file mode with. Default value will make |
| 1267 | all mapped files to be read only. |
| 1268 | """ |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1269 | super(MemoryCache, self).__init__() |
Vadim Shtayura | e3fbd10 | 2014-04-29 17:05:21 -0700 | [diff] [blame] | 1270 | self._file_mode_mask = file_mode_mask |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1271 | # Let's not assume dict is thread safe. |
| 1272 | self._lock = threading.Lock() |
| 1273 | self._contents = {} |
| 1274 | |
| 1275 | def cached_set(self): |
| 1276 | with self._lock: |
| 1277 | return set(self._contents) |
| 1278 | |
| 1279 | def touch(self, digest, size): |
| 1280 | with self._lock: |
| 1281 | return digest in self._contents |
| 1282 | |
| 1283 | def evict(self, digest): |
| 1284 | with self._lock: |
| 1285 | self._contents.pop(digest, None) |
| 1286 | |
| 1287 | def read(self, digest): |
| 1288 | with self._lock: |
| 1289 | return self._contents[digest] |
| 1290 | |
| 1291 | def write(self, digest, content): |
| 1292 | # Assemble whole stream before taking the lock. |
| 1293 | data = ''.join(content) |
| 1294 | with self._lock: |
| 1295 | self._contents[digest] = data |
| 1296 | |
Marc-Antoine Ruel | fb199cf | 2013-11-12 15:38:12 -0500 | [diff] [blame] | 1297 | def hardlink(self, digest, dest, file_mode): |
| 1298 | """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] | 1299 | file_write(dest, [self.read(digest)]) |
Marc-Antoine Ruel | fb199cf | 2013-11-12 15:38:12 -0500 | [diff] [blame] | 1300 | if file_mode is not None: |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1301 | fs.chmod(dest, file_mode & self._file_mode_mask) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1302 | |
| 1303 | |
Marc-Antoine Ruel | e4ad07e | 2014-10-15 20:22:29 -0400 | [diff] [blame] | 1304 | class CachePolicies(object): |
| 1305 | def __init__(self, max_cache_size, min_free_space, max_items): |
| 1306 | """ |
| 1307 | Arguments: |
| 1308 | - max_cache_size: Trim if the cache gets larger than this value. If 0, the |
| 1309 | cache is effectively a leak. |
| 1310 | - min_free_space: Trim if disk free space becomes lower than this value. If |
| 1311 | 0, it unconditionally fill the disk. |
| 1312 | - max_items: Maximum number of items to keep in the cache. If 0, do not |
| 1313 | enforce a limit. |
| 1314 | """ |
| 1315 | self.max_cache_size = max_cache_size |
| 1316 | self.min_free_space = min_free_space |
| 1317 | self.max_items = max_items |
| 1318 | |
| 1319 | |
| 1320 | class DiskCache(LocalCache): |
| 1321 | """Stateful LRU cache in a flat hash table in a directory. |
| 1322 | |
| 1323 | Saves its state as json file. |
| 1324 | """ |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1325 | STATE_FILE = u'state.json' |
Marc-Antoine Ruel | e4ad07e | 2014-10-15 20:22:29 -0400 | [diff] [blame] | 1326 | |
| 1327 | def __init__(self, cache_dir, policies, hash_algo): |
| 1328 | """ |
| 1329 | Arguments: |
| 1330 | cache_dir: directory where to place the cache. |
| 1331 | policies: cache retention policies. |
| 1332 | algo: hashing algorithm used. |
| 1333 | """ |
| 1334 | super(DiskCache, self).__init__() |
| 1335 | self.cache_dir = cache_dir |
| 1336 | self.policies = policies |
| 1337 | self.hash_algo = hash_algo |
| 1338 | self.state_file = os.path.join(cache_dir, self.STATE_FILE) |
| 1339 | |
| 1340 | # All protected methods (starting with '_') except _path should be called |
| 1341 | # with this lock locked. |
| 1342 | self._lock = threading_utils.LockWithAssert() |
| 1343 | self._lru = lru.LRUDict() |
| 1344 | |
| 1345 | # Profiling values. |
| 1346 | self._added = [] |
| 1347 | self._removed = [] |
| 1348 | self._free_disk = 0 |
| 1349 | |
| 1350 | with tools.Profiler('Setup'): |
| 1351 | with self._lock: |
| 1352 | self._load() |
| 1353 | |
| 1354 | def __enter__(self): |
| 1355 | return self |
| 1356 | |
| 1357 | def __exit__(self, _exc_type, _exec_value, _traceback): |
| 1358 | with tools.Profiler('CleanupTrimming'): |
| 1359 | with self._lock: |
| 1360 | self._trim() |
| 1361 | |
| 1362 | logging.info( |
| 1363 | '%5d (%8dkb) added', |
| 1364 | len(self._added), sum(self._added) / 1024) |
| 1365 | logging.info( |
| 1366 | '%5d (%8dkb) current', |
| 1367 | len(self._lru), |
| 1368 | sum(self._lru.itervalues()) / 1024) |
| 1369 | logging.info( |
| 1370 | '%5d (%8dkb) removed', |
| 1371 | len(self._removed), sum(self._removed) / 1024) |
| 1372 | logging.info( |
| 1373 | ' %8dkb free', |
| 1374 | self._free_disk / 1024) |
| 1375 | return False |
| 1376 | |
| 1377 | def cached_set(self): |
| 1378 | with self._lock: |
| 1379 | return self._lru.keys_set() |
| 1380 | |
| 1381 | def touch(self, digest, size): |
| 1382 | """Verifies an actual file is valid. |
| 1383 | |
| 1384 | Note that is doesn't compute the hash so it could still be corrupted if the |
| 1385 | file size didn't change. |
| 1386 | |
| 1387 | TODO(maruel): More stringent verification while keeping the check fast. |
| 1388 | """ |
| 1389 | # Do the check outside the lock. |
| 1390 | if not is_valid_file(self._path(digest), size): |
| 1391 | return False |
| 1392 | |
| 1393 | # Update it's LRU position. |
| 1394 | with self._lock: |
| 1395 | if digest not in self._lru: |
| 1396 | return False |
| 1397 | self._lru.touch(digest) |
| 1398 | return True |
| 1399 | |
| 1400 | def evict(self, digest): |
| 1401 | with self._lock: |
| 1402 | self._lru.pop(digest) |
| 1403 | self._delete_file(digest, UNKNOWN_FILE_SIZE) |
| 1404 | |
| 1405 | def read(self, digest): |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1406 | with fs.open(self._path(digest), 'rb') as f: |
Marc-Antoine Ruel | e4ad07e | 2014-10-15 20:22:29 -0400 | [diff] [blame] | 1407 | return f.read() |
| 1408 | |
| 1409 | def write(self, digest, content): |
Marc-Antoine Ruel | df4976d | 2015-04-15 19:56:21 -0400 | [diff] [blame] | 1410 | assert content is not None |
Marc-Antoine Ruel | e4ad07e | 2014-10-15 20:22:29 -0400 | [diff] [blame] | 1411 | path = self._path(digest) |
| 1412 | # A stale broken file may remain. It is possible for the file to have write |
| 1413 | # access bit removed which would cause the file_write() call to fail to open |
| 1414 | # in write mode. Take no chance here. |
| 1415 | file_path.try_remove(path) |
| 1416 | try: |
| 1417 | size = file_write(path, content) |
| 1418 | except: |
| 1419 | # There are two possible places were an exception can occur: |
| 1420 | # 1) Inside |content| generator in case of network or unzipping errors. |
| 1421 | # 2) Inside file_write itself in case of disk IO errors. |
| 1422 | # In any case delete an incomplete file and propagate the exception to |
| 1423 | # caller, it will be logged there. |
| 1424 | file_path.try_remove(path) |
| 1425 | raise |
| 1426 | # Make the file read-only in the cache. This has a few side-effects since |
| 1427 | # the file node is modified, so every directory entries to this file becomes |
| 1428 | # read-only. It's fine here because it is a new file. |
| 1429 | file_path.set_read_only(path, True) |
| 1430 | with self._lock: |
| 1431 | self._add(digest, size) |
| 1432 | |
| 1433 | def hardlink(self, digest, dest, file_mode): |
| 1434 | """Hardlinks the file to |dest|. |
| 1435 | |
| 1436 | Note that the file permission bits are on the file node, not the directory |
| 1437 | entry, so changing the access bit on any of the directory entries for the |
| 1438 | file node will affect them all. |
| 1439 | """ |
| 1440 | path = self._path(digest) |
maruel | 1f7e816 | 2015-09-16 10:35:43 -0700 | [diff] [blame] | 1441 | if not file_path.link_file(dest, path, file_path.HARDLINK_WITH_FALLBACK): |
| 1442 | # Report to the server that it failed with more details. We'll want to |
| 1443 | # squash them all. |
| 1444 | on_error.report('Failed to hardlink\n%s -> %s' % (path, dest)) |
| 1445 | |
Marc-Antoine Ruel | e4ad07e | 2014-10-15 20:22:29 -0400 | [diff] [blame] | 1446 | if file_mode is not None: |
| 1447 | # Ignores all other bits. |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1448 | fs.chmod(dest, file_mode & 0500) |
Marc-Antoine Ruel | e4ad07e | 2014-10-15 20:22:29 -0400 | [diff] [blame] | 1449 | |
| 1450 | def _load(self): |
| 1451 | """Loads state of the cache from json file.""" |
| 1452 | self._lock.assert_locked() |
| 1453 | |
| 1454 | if not os.path.isdir(self.cache_dir): |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1455 | fs.makedirs(self.cache_dir) |
Marc-Antoine Ruel | e4ad07e | 2014-10-15 20:22:29 -0400 | [diff] [blame] | 1456 | else: |
| 1457 | # Make sure the cache is read-only. |
| 1458 | # TODO(maruel): Calculate the cost and optimize the performance |
| 1459 | # accordingly. |
| 1460 | file_path.make_tree_read_only(self.cache_dir) |
| 1461 | |
| 1462 | # Load state of the cache. |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1463 | if fs.isfile(self.state_file): |
Marc-Antoine Ruel | e4ad07e | 2014-10-15 20:22:29 -0400 | [diff] [blame] | 1464 | try: |
| 1465 | self._lru = lru.LRUDict.load(self.state_file) |
| 1466 | except ValueError as err: |
| 1467 | logging.error('Failed to load cache state: %s' % (err,)) |
| 1468 | # Don't want to keep broken state file. |
| 1469 | file_path.try_remove(self.state_file) |
| 1470 | |
| 1471 | # Ensure that all files listed in the state still exist and add new ones. |
| 1472 | previous = self._lru.keys_set() |
| 1473 | unknown = [] |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1474 | for filename in fs.listdir(self.cache_dir): |
Marc-Antoine Ruel | e4ad07e | 2014-10-15 20:22:29 -0400 | [diff] [blame] | 1475 | if filename == self.STATE_FILE: |
| 1476 | continue |
| 1477 | if filename in previous: |
| 1478 | previous.remove(filename) |
| 1479 | continue |
| 1480 | # An untracked file. |
| 1481 | if not isolated_format.is_valid_hash(filename, self.hash_algo): |
| 1482 | logging.warning('Removing unknown file %s from cache', filename) |
Marc-Antoine Ruel | 8cd3337 | 2015-02-09 12:54:43 -0500 | [diff] [blame] | 1483 | p = self._path(filename) |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1484 | if fs.isdir(p): |
Marc-Antoine Ruel | 8cd3337 | 2015-02-09 12:54:43 -0500 | [diff] [blame] | 1485 | try: |
| 1486 | file_path.rmtree(p) |
| 1487 | except OSError: |
| 1488 | pass |
| 1489 | else: |
| 1490 | file_path.try_remove(p) |
Marc-Antoine Ruel | e4ad07e | 2014-10-15 20:22:29 -0400 | [diff] [blame] | 1491 | continue |
| 1492 | # File that's not referenced in 'state.json'. |
| 1493 | # TODO(vadimsh): Verify its SHA1 matches file name. |
| 1494 | logging.warning('Adding unknown file %s to cache', filename) |
| 1495 | unknown.append(filename) |
| 1496 | |
| 1497 | if unknown: |
| 1498 | # Add as oldest files. They will be deleted eventually if not accessed. |
| 1499 | self._add_oldest_list(unknown) |
| 1500 | logging.warning('Added back %d unknown files', len(unknown)) |
| 1501 | |
| 1502 | if previous: |
| 1503 | # Filter out entries that were not found. |
| 1504 | logging.warning('Removed %d lost files', len(previous)) |
| 1505 | for filename in previous: |
| 1506 | self._lru.pop(filename) |
| 1507 | self._trim() |
| 1508 | |
| 1509 | def _save(self): |
| 1510 | """Saves the LRU ordering.""" |
| 1511 | self._lock.assert_locked() |
| 1512 | if sys.platform != 'win32': |
| 1513 | d = os.path.dirname(self.state_file) |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1514 | if fs.isdir(d): |
Marc-Antoine Ruel | e4ad07e | 2014-10-15 20:22:29 -0400 | [diff] [blame] | 1515 | # Necessary otherwise the file can't be created. |
| 1516 | file_path.set_read_only(d, False) |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1517 | if fs.isfile(self.state_file): |
Marc-Antoine Ruel | e4ad07e | 2014-10-15 20:22:29 -0400 | [diff] [blame] | 1518 | file_path.set_read_only(self.state_file, False) |
| 1519 | self._lru.save(self.state_file) |
| 1520 | |
| 1521 | def _trim(self): |
| 1522 | """Trims anything we don't know, make sure enough free space exists.""" |
| 1523 | self._lock.assert_locked() |
| 1524 | |
| 1525 | # Ensure maximum cache size. |
| 1526 | if self.policies.max_cache_size: |
| 1527 | total_size = sum(self._lru.itervalues()) |
| 1528 | while total_size > self.policies.max_cache_size: |
| 1529 | total_size -= self._remove_lru_file() |
| 1530 | |
| 1531 | # Ensure maximum number of items in the cache. |
| 1532 | if self.policies.max_items and len(self._lru) > self.policies.max_items: |
| 1533 | for _ in xrange(len(self._lru) - self.policies.max_items): |
| 1534 | self._remove_lru_file() |
| 1535 | |
| 1536 | # Ensure enough free space. |
| 1537 | self._free_disk = file_path.get_free_space(self.cache_dir) |
| 1538 | trimmed_due_to_space = False |
| 1539 | while ( |
| 1540 | self.policies.min_free_space and |
| 1541 | self._lru and |
| 1542 | self._free_disk < self.policies.min_free_space): |
| 1543 | trimmed_due_to_space = True |
| 1544 | self._remove_lru_file() |
| 1545 | self._free_disk = file_path.get_free_space(self.cache_dir) |
| 1546 | if trimmed_due_to_space: |
| 1547 | total_usage = sum(self._lru.itervalues()) |
| 1548 | usage_percent = 0. |
| 1549 | if total_usage: |
| 1550 | usage_percent = 100. * self.policies.max_cache_size / float(total_usage) |
| 1551 | logging.warning( |
| 1552 | 'Trimmed due to not enough free disk space: %.1fkb free, %.1fkb ' |
| 1553 | 'cache (%.1f%% of its maximum capacity)', |
| 1554 | self._free_disk / 1024., |
| 1555 | total_usage / 1024., |
| 1556 | usage_percent) |
| 1557 | self._save() |
| 1558 | |
| 1559 | def _path(self, digest): |
| 1560 | """Returns the path to one item.""" |
| 1561 | return os.path.join(self.cache_dir, digest) |
| 1562 | |
| 1563 | def _remove_lru_file(self): |
| 1564 | """Removes the last recently used file and returns its size.""" |
| 1565 | self._lock.assert_locked() |
| 1566 | digest, size = self._lru.pop_oldest() |
| 1567 | self._delete_file(digest, size) |
| 1568 | return size |
| 1569 | |
| 1570 | def _add(self, digest, size=UNKNOWN_FILE_SIZE): |
| 1571 | """Adds an item into LRU cache marking it as a newest one.""" |
| 1572 | self._lock.assert_locked() |
| 1573 | if size == UNKNOWN_FILE_SIZE: |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1574 | size = fs.stat(self._path(digest)).st_size |
Marc-Antoine Ruel | e4ad07e | 2014-10-15 20:22:29 -0400 | [diff] [blame] | 1575 | self._added.append(size) |
| 1576 | self._lru.add(digest, size) |
| 1577 | |
| 1578 | def _add_oldest_list(self, digests): |
| 1579 | """Adds a bunch of items into LRU cache marking them as oldest ones.""" |
| 1580 | self._lock.assert_locked() |
| 1581 | pairs = [] |
| 1582 | for digest in digests: |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1583 | size = fs.stat(self._path(digest)).st_size |
Marc-Antoine Ruel | e4ad07e | 2014-10-15 20:22:29 -0400 | [diff] [blame] | 1584 | self._added.append(size) |
| 1585 | pairs.append((digest, size)) |
| 1586 | self._lru.batch_insert_oldest(pairs) |
| 1587 | |
| 1588 | def _delete_file(self, digest, size=UNKNOWN_FILE_SIZE): |
| 1589 | """Deletes cache file from the file system.""" |
| 1590 | self._lock.assert_locked() |
| 1591 | try: |
| 1592 | if size == UNKNOWN_FILE_SIZE: |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1593 | size = fs.stat(self._path(digest)).st_size |
Marc-Antoine Ruel | e4ad07e | 2014-10-15 20:22:29 -0400 | [diff] [blame] | 1594 | file_path.try_remove(self._path(digest)) |
| 1595 | self._removed.append(size) |
| 1596 | except OSError as e: |
| 1597 | logging.error('Error attempting to delete a file %s:\n%s' % (digest, e)) |
| 1598 | |
| 1599 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1600 | class IsolatedBundle(object): |
| 1601 | """Fetched and parsed .isolated file with all dependencies.""" |
| 1602 | |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1603 | def __init__(self): |
| 1604 | self.command = [] |
| 1605 | self.files = {} |
| 1606 | self.read_only = None |
| 1607 | self.relative_cwd = None |
| 1608 | # The main .isolated file, a IsolatedFile instance. |
| 1609 | self.root = None |
| 1610 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1611 | def fetch(self, fetch_queue, root_isolated_hash, algo): |
| 1612 | """Fetches the .isolated and all the included .isolated. |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1613 | |
| 1614 | It enables support for "included" .isolated files. They are processed in |
| 1615 | strict order but fetched asynchronously from the cache. This is important so |
| 1616 | that a file in an included .isolated file that is overridden by an embedding |
| 1617 | .isolated file is not fetched needlessly. The includes are fetched in one |
| 1618 | pass and the files are fetched as soon as all the ones on the left-side |
| 1619 | of the tree were fetched. |
| 1620 | |
| 1621 | The prioritization is very important here for nested .isolated files. |
| 1622 | 'includes' have the highest priority and the algorithm is optimized for both |
| 1623 | deep and wide trees. A deep one is a long link of .isolated files referenced |
| 1624 | one at a time by one item in 'includes'. A wide one has a large number of |
| 1625 | 'includes' in a single .isolated file. 'left' is defined as an included |
| 1626 | .isolated file earlier in the 'includes' list. So the order of the elements |
| 1627 | in 'includes' is important. |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1628 | |
| 1629 | As a side effect this method starts asynchronous fetch of all data files |
| 1630 | by adding them to |fetch_queue|. It doesn't wait for data files to finish |
| 1631 | fetching though. |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1632 | """ |
| 1633 | self.root = isolated_format.IsolatedFile(root_isolated_hash, algo) |
| 1634 | |
| 1635 | # Isolated files being retrieved now: hash -> IsolatedFile instance. |
| 1636 | pending = {} |
| 1637 | # Set of hashes of already retrieved items to refuse recursive includes. |
| 1638 | seen = set() |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1639 | # Set of IsolatedFile's whose data files have already being fetched. |
| 1640 | processed = set() |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1641 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1642 | def retrieve_async(isolated_file): |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1643 | h = isolated_file.obj_hash |
| 1644 | if h in seen: |
| 1645 | raise isolated_format.IsolatedError( |
| 1646 | 'IsolatedFile %s is retrieved recursively' % h) |
| 1647 | assert h not in pending |
| 1648 | seen.add(h) |
| 1649 | pending[h] = isolated_file |
| 1650 | fetch_queue.add(h, priority=threading_utils.PRIORITY_HIGH) |
| 1651 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1652 | # Start fetching root *.isolated file (single file, not the whole bundle). |
| 1653 | retrieve_async(self.root) |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1654 | |
| 1655 | while pending: |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1656 | # Wait until some *.isolated file is fetched, parse it. |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1657 | item_hash = fetch_queue.wait(pending) |
| 1658 | item = pending.pop(item_hash) |
| 1659 | item.load(fetch_queue.cache.read(item_hash)) |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1660 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1661 | # Start fetching included *.isolated files. |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1662 | for new_child in item.children: |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1663 | retrieve_async(new_child) |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1664 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1665 | # Always fetch *.isolated files in traversal order, waiting if necessary |
| 1666 | # until next to-be-processed node loads. "Waiting" is done by yielding |
| 1667 | # back to the outer loop, that waits until some *.isolated is loaded. |
| 1668 | for node in isolated_format.walk_includes(self.root): |
| 1669 | if node not in processed: |
| 1670 | # Not visited, and not yet loaded -> wait for it to load. |
| 1671 | if not node.is_loaded: |
| 1672 | break |
| 1673 | # Not visited and loaded -> process it and continue the traversal. |
| 1674 | self._start_fetching_files(node, fetch_queue) |
| 1675 | processed.add(node) |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1676 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1677 | # All *.isolated files should be processed by now and only them. |
| 1678 | all_isolateds = set(isolated_format.walk_includes(self.root)) |
| 1679 | assert all_isolateds == processed, (all_isolateds, processed) |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1680 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1681 | # Extract 'command' and other bundle properties. |
| 1682 | for node in isolated_format.walk_includes(self.root): |
| 1683 | self._update_self(node) |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1684 | self.relative_cwd = self.relative_cwd or '' |
| 1685 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1686 | def _start_fetching_files(self, isolated, fetch_queue): |
| 1687 | """Starts fetching files from |isolated| that are not yet being fetched. |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1688 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1689 | Modifies self.files. |
| 1690 | """ |
| 1691 | logging.debug('fetch_files(%s)', isolated.obj_hash) |
| 1692 | for filepath, properties in isolated.data.get('files', {}).iteritems(): |
| 1693 | # Root isolated has priority on the files being mapped. In particular, |
| 1694 | # overridden files must not be fetched. |
| 1695 | if filepath not in self.files: |
| 1696 | self.files[filepath] = properties |
| 1697 | if 'h' in properties: |
| 1698 | # Preemptively request files. |
| 1699 | logging.debug('fetching %s', filepath) |
| 1700 | fetch_queue.add( |
| 1701 | properties['h'], properties['s'], threading_utils.PRIORITY_MED) |
| 1702 | |
| 1703 | def _update_self(self, node): |
| 1704 | """Extracts bundle global parameters from loaded *.isolated file. |
| 1705 | |
| 1706 | Will be called with each loaded *.isolated file in order of traversal of |
| 1707 | isolated include graph (see isolated_format.walk_includes). |
| 1708 | """ |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1709 | # Grabs properties. |
| 1710 | if not self.command and node.data.get('command'): |
| 1711 | # Ensure paths are correctly separated on windows. |
| 1712 | self.command = node.data['command'] |
| 1713 | if self.command: |
| 1714 | self.command[0] = self.command[0].replace('/', os.path.sep) |
| 1715 | self.command = tools.fix_python_path(self.command) |
| 1716 | if self.read_only is None and node.data.get('read_only') is not None: |
| 1717 | self.read_only = node.data['read_only'] |
| 1718 | if (self.relative_cwd is None and |
| 1719 | node.data.get('relative_cwd') is not None): |
| 1720 | self.relative_cwd = node.data['relative_cwd'] |
| 1721 | |
| 1722 | |
Vadim Shtayura | 8623c27 | 2014-12-01 11:45:27 -0800 | [diff] [blame] | 1723 | def set_storage_api_class(cls): |
| 1724 | """Replaces StorageApi implementation used by default.""" |
| 1725 | global _storage_api_cls |
| 1726 | assert _storage_api_cls is None |
| 1727 | assert issubclass(cls, StorageApi) |
| 1728 | _storage_api_cls = cls |
| 1729 | |
| 1730 | |
Marc-Antoine Ruel | b10edf2 | 2014-12-11 13:33:57 -0500 | [diff] [blame] | 1731 | def get_storage_api(url, namespace): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1732 | """Returns an object that implements low-level StorageApi interface. |
| 1733 | |
| 1734 | It is used by Storage to work with single isolate |namespace|. It should |
| 1735 | rarely be used directly by clients, see 'get_storage' for |
| 1736 | a better alternative. |
| 1737 | |
| 1738 | Arguments: |
Marc-Antoine Ruel | b10edf2 | 2014-12-11 13:33:57 -0500 | [diff] [blame] | 1739 | url: URL of isolate service to use shared cloud based storage. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1740 | namespace: isolate namespace to operate in, also defines hashing and |
| 1741 | compression scheme used, i.e. namespace names that end with '-gzip' |
| 1742 | store compressed data. |
| 1743 | |
| 1744 | Returns: |
| 1745 | Instance of StorageApi subclass. |
| 1746 | """ |
Marc-Antoine Ruel | b10edf2 | 2014-12-11 13:33:57 -0500 | [diff] [blame] | 1747 | cls = _storage_api_cls or IsolateServer |
| 1748 | return cls(url, namespace) |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 1749 | |
| 1750 | |
Marc-Antoine Ruel | b10edf2 | 2014-12-11 13:33:57 -0500 | [diff] [blame] | 1751 | def get_storage(url, namespace): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1752 | """Returns Storage class that can upload and download from |namespace|. |
| 1753 | |
| 1754 | Arguments: |
Marc-Antoine Ruel | b10edf2 | 2014-12-11 13:33:57 -0500 | [diff] [blame] | 1755 | url: URL of isolate service to use shared cloud based storage. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1756 | namespace: isolate namespace to operate in, also defines hashing and |
| 1757 | compression scheme used, i.e. namespace names that end with '-gzip' |
| 1758 | store compressed data. |
| 1759 | |
| 1760 | Returns: |
| 1761 | Instance of Storage. |
| 1762 | """ |
Marc-Antoine Ruel | b10edf2 | 2014-12-11 13:33:57 -0500 | [diff] [blame] | 1763 | return Storage(get_storage_api(url, namespace)) |
maruel@chromium.org | dedbf49 | 2013-09-12 20:42:11 +0000 | [diff] [blame] | 1764 | |
maruel@chromium.org | dedbf49 | 2013-09-12 20:42:11 +0000 | [diff] [blame] | 1765 | |
Vadim Shtayura | ea38c57 | 2014-10-06 16:57:16 -0700 | [diff] [blame] | 1766 | def upload_tree(base_url, infiles, namespace): |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 1767 | """Uploads the given tree to the given url. |
| 1768 | |
| 1769 | Arguments: |
Vadim Shtayura | ea38c57 | 2014-10-06 16:57:16 -0700 | [diff] [blame] | 1770 | base_url: The url of the isolate server to upload to. |
| 1771 | infiles: iterable of pairs (absolute path, metadata dict) of files. |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 1772 | namespace: The namespace to use on the server. |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 1773 | """ |
Vadim Shtayura | ea38c57 | 2014-10-06 16:57:16 -0700 | [diff] [blame] | 1774 | # Convert |infiles| into a list of FileItem objects, skip duplicates. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1775 | # Filter out symlinks, since they are not represented by items on isolate |
| 1776 | # server side. |
Vadim Shtayura | ea38c57 | 2014-10-06 16:57:16 -0700 | [diff] [blame] | 1777 | items = [] |
| 1778 | seen = set() |
| 1779 | skipped = 0 |
| 1780 | for filepath, metadata in infiles: |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1781 | assert isinstance(filepath, unicode), filepath |
Vadim Shtayura | ea38c57 | 2014-10-06 16:57:16 -0700 | [diff] [blame] | 1782 | if 'l' not in metadata and filepath not in seen: |
| 1783 | seen.add(filepath) |
| 1784 | item = FileItem( |
| 1785 | path=filepath, |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1786 | digest=metadata['h'], |
| 1787 | size=metadata['s'], |
| 1788 | high_priority=metadata.get('priority') == '0') |
Vadim Shtayura | ea38c57 | 2014-10-06 16:57:16 -0700 | [diff] [blame] | 1789 | items.append(item) |
| 1790 | else: |
| 1791 | skipped += 1 |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1792 | |
Vadim Shtayura | ea38c57 | 2014-10-06 16:57:16 -0700 | [diff] [blame] | 1793 | logging.info('Skipped %d duplicated entries', skipped) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1794 | with get_storage(base_url, namespace) as storage: |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1795 | storage.upload_items(items) |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1796 | |
| 1797 | |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 1798 | def fetch_isolated(isolated_hash, storage, cache, outdir, require_command): |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1799 | """Aggressively downloads the .isolated file(s), then download all the files. |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1800 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1801 | Arguments: |
| 1802 | isolated_hash: hash of the root *.isolated file. |
| 1803 | storage: Storage class that communicates with isolate storage. |
| 1804 | 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] | 1805 | outdir: Output directory to map file tree to. |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1806 | require_command: Ensure *.isolated specifies a command to run. |
| 1807 | |
| 1808 | Returns: |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1809 | IsolatedBundle object that holds details about loaded *.isolated file. |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1810 | """ |
Marc-Antoine Ruel | 4e8cd18 | 2014-06-18 13:27:17 -0400 | [diff] [blame] | 1811 | logging.debug( |
| 1812 | 'fetch_isolated(%s, %s, %s, %s, %s)', |
| 1813 | isolated_hash, storage, cache, outdir, require_command) |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 1814 | # Hash algorithm to use, defined by namespace |storage| is using. |
| 1815 | algo = storage.hash_algo |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1816 | with cache: |
| 1817 | fetch_queue = FetchQueue(storage, cache) |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1818 | bundle = IsolatedBundle() |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1819 | |
| 1820 | with tools.Profiler('GetIsolateds'): |
| 1821 | # Optionally support local files by manually adding them to cache. |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 1822 | if not isolated_format.is_valid_hash(isolated_hash, algo): |
Marc-Antoine Ruel | 4e8cd18 | 2014-06-18 13:27:17 -0400 | [diff] [blame] | 1823 | logging.debug('%s is not a valid hash, assuming a file', isolated_hash) |
maruel | 1ceb387 | 2015-10-14 06:10:44 -0700 | [diff] [blame] | 1824 | path = unicode(os.path.abspath(isolated_hash)) |
Marc-Antoine Ruel | 4e8cd18 | 2014-06-18 13:27:17 -0400 | [diff] [blame] | 1825 | try: |
maruel | 1ceb387 | 2015-10-14 06:10:44 -0700 | [diff] [blame] | 1826 | isolated_hash = fetch_queue.inject_local_file(path, algo) |
Marc-Antoine Ruel | 4e8cd18 | 2014-06-18 13:27:17 -0400 | [diff] [blame] | 1827 | except IOError: |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 1828 | raise isolated_format.MappingError( |
Marc-Antoine Ruel | 4e8cd18 | 2014-06-18 13:27:17 -0400 | [diff] [blame] | 1829 | '%s doesn\'t seem to be a valid file. Did you intent to pass a ' |
| 1830 | 'valid hash?' % isolated_hash) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1831 | |
| 1832 | # Load all *.isolated and start loading rest of the files. |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1833 | bundle.fetch(fetch_queue, isolated_hash, algo) |
| 1834 | if require_command and not bundle.command: |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1835 | # TODO(vadimsh): All fetch operations are already enqueue and there's no |
| 1836 | # easy way to cancel them. |
maruel | a72f46e | 2016-02-24 11:05:45 -0800 | [diff] [blame^] | 1837 | raise IsolatedErrorNoCommand() |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1838 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1839 | with tools.Profiler('GetRest'): |
| 1840 | # Create file system hierarchy. |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1841 | if not fs.isdir(outdir): |
| 1842 | fs.makedirs(outdir) |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1843 | create_directories(outdir, bundle.files) |
| 1844 | create_symlinks(outdir, bundle.files.iteritems()) |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1845 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1846 | # Ensure working directory exists. |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1847 | cwd = os.path.normpath(os.path.join(outdir, bundle.relative_cwd)) |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1848 | if not fs.isdir(cwd): |
| 1849 | fs.makedirs(cwd) |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1850 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1851 | # Multimap: digest -> list of pairs (path, props). |
| 1852 | remaining = {} |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1853 | for filepath, props in bundle.files.iteritems(): |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1854 | if 'h' in props: |
| 1855 | remaining.setdefault(props['h'], []).append((filepath, props)) |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1856 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1857 | # Now block on the remaining files to be downloaded and mapped. |
| 1858 | logging.info('Retrieving remaining files (%d of them)...', |
| 1859 | fetch_queue.pending_count) |
| 1860 | last_update = time.time() |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1861 | with threading_utils.DeadlockDetector(DEADLOCK_TIMEOUT) as detector: |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1862 | while remaining: |
| 1863 | detector.ping() |
| 1864 | |
| 1865 | # Wait for any item to finish fetching to cache. |
| 1866 | digest = fetch_queue.wait(remaining) |
| 1867 | |
| 1868 | # Link corresponding files to a fetched item in cache. |
| 1869 | for filepath, props in remaining.pop(digest): |
Marc-Antoine Ruel | fb199cf | 2013-11-12 15:38:12 -0500 | [diff] [blame] | 1870 | cache.hardlink( |
| 1871 | digest, os.path.join(outdir, filepath), props.get('m')) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1872 | |
| 1873 | # Report progress. |
| 1874 | duration = time.time() - last_update |
| 1875 | if duration > DELAY_BETWEEN_UPDATES_IN_SECS: |
| 1876 | msg = '%d files remaining...' % len(remaining) |
| 1877 | print msg |
| 1878 | logging.info(msg) |
| 1879 | last_update = time.time() |
| 1880 | |
| 1881 | # Cache could evict some items we just tried to fetch, it's a fatal error. |
| 1882 | if not fetch_queue.verify_all_cached(): |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 1883 | raise isolated_format.MappingError( |
| 1884 | 'Cache is too small to hold all requested files') |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1885 | return bundle |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1886 | |
| 1887 | |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1888 | def directory_to_metadata(root, algo, blacklist): |
| 1889 | """Returns the FileItem list and .isolated metadata for a directory.""" |
| 1890 | root = file_path.get_native_path_case(root) |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 1891 | paths = isolated_format.expand_directory_and_symlink( |
Vadim Shtayura | 439d3fc | 2014-05-07 16:05:12 -0700 | [diff] [blame] | 1892 | root, '.' + os.path.sep, blacklist, sys.platform != 'win32') |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 1893 | metadata = { |
| 1894 | relpath: isolated_format.file_to_metadata( |
Marc-Antoine Ruel | f1d827c | 2014-11-24 15:22:25 -0500 | [diff] [blame] | 1895 | os.path.join(root, relpath), {}, 0, algo) |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 1896 | for relpath in paths |
| 1897 | } |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1898 | for v in metadata.itervalues(): |
| 1899 | v.pop('t') |
| 1900 | items = [ |
| 1901 | FileItem( |
| 1902 | path=os.path.join(root, relpath), |
| 1903 | digest=meta['h'], |
| 1904 | size=meta['s'], |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1905 | high_priority=relpath.endswith('.isolated')) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1906 | for relpath, meta in metadata.iteritems() if 'h' in meta |
| 1907 | ] |
| 1908 | return items, metadata |
| 1909 | |
| 1910 | |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 1911 | def archive_files_to_storage(storage, files, blacklist): |
Marc-Antoine Ruel | 2283ad1 | 2014-02-09 11:14:57 -0500 | [diff] [blame] | 1912 | """Stores every entries and returns the relevant data. |
| 1913 | |
| 1914 | Arguments: |
| 1915 | storage: a Storage object that communicates with the remote object store. |
Marc-Antoine Ruel | 2283ad1 | 2014-02-09 11:14:57 -0500 | [diff] [blame] | 1916 | files: list of file paths to upload. If a directory is specified, a |
| 1917 | .isolated file is created and its hash is returned. |
| 1918 | blacklist: function that returns True if a file should be omitted. |
| 1919 | """ |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1920 | assert all(isinstance(i, unicode) for i in files), files |
| 1921 | if len(files) != len(set(map(os.path.abspath, files))): |
| 1922 | raise Error('Duplicate entries found.') |
| 1923 | |
| 1924 | results = [] |
| 1925 | # The temporary directory is only created as needed. |
| 1926 | tempdir = None |
| 1927 | try: |
| 1928 | # TODO(maruel): Yield the files to a worker thread. |
| 1929 | items_to_upload = [] |
| 1930 | for f in files: |
| 1931 | try: |
| 1932 | filepath = os.path.abspath(f) |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1933 | if fs.isdir(filepath): |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1934 | # Uploading a whole directory. |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 1935 | items, metadata = directory_to_metadata( |
| 1936 | filepath, storage.hash_algo, blacklist) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1937 | |
| 1938 | # Create the .isolated file. |
| 1939 | if not tempdir: |
Marc-Antoine Ruel | 3c979cb | 2015-03-11 13:43:28 -0400 | [diff] [blame] | 1940 | tempdir = tempfile.mkdtemp(prefix=u'isolateserver') |
| 1941 | handle, isolated = tempfile.mkstemp(dir=tempdir, suffix=u'.isolated') |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1942 | os.close(handle) |
| 1943 | data = { |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 1944 | 'algo': |
| 1945 | isolated_format.SUPPORTED_ALGOS_REVERSE[storage.hash_algo], |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1946 | 'files': metadata, |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 1947 | 'version': isolated_format.ISOLATED_FILE_VERSION, |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1948 | } |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 1949 | isolated_format.save_isolated(isolated, data) |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 1950 | h = isolated_format.hash_file(isolated, storage.hash_algo) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1951 | items_to_upload.extend(items) |
| 1952 | items_to_upload.append( |
| 1953 | FileItem( |
| 1954 | path=isolated, |
| 1955 | digest=h, |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1956 | size=fs.stat(isolated).st_size, |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1957 | high_priority=True)) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1958 | results.append((h, f)) |
| 1959 | |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1960 | elif fs.isfile(filepath): |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 1961 | h = isolated_format.hash_file(filepath, storage.hash_algo) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1962 | items_to_upload.append( |
| 1963 | FileItem( |
| 1964 | path=filepath, |
| 1965 | digest=h, |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1966 | size=fs.stat(filepath).st_size, |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1967 | high_priority=f.endswith('.isolated'))) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1968 | results.append((h, f)) |
| 1969 | else: |
| 1970 | raise Error('%s is neither a file or directory.' % f) |
| 1971 | except OSError: |
| 1972 | raise Error('Failed to process %s.' % f) |
Marc-Antoine Ruel | 2283ad1 | 2014-02-09 11:14:57 -0500 | [diff] [blame] | 1973 | # Technically we would care about which files were uploaded but we don't |
| 1974 | # much in practice. |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1975 | _uploaded_files = storage.upload_items(items_to_upload) |
| 1976 | return results |
| 1977 | finally: |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1978 | if tempdir and fs.isdir(tempdir): |
Marc-Antoine Ruel | e4ad07e | 2014-10-15 20:22:29 -0400 | [diff] [blame] | 1979 | file_path.rmtree(tempdir) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1980 | |
| 1981 | |
Marc-Antoine Ruel | 488ce8f | 2014-02-09 11:25:04 -0500 | [diff] [blame] | 1982 | def archive(out, namespace, files, blacklist): |
| 1983 | if files == ['-']: |
| 1984 | files = sys.stdin.readlines() |
| 1985 | |
| 1986 | if not files: |
| 1987 | raise Error('Nothing to upload') |
| 1988 | |
| 1989 | files = [f.decode('utf-8') for f in files] |
Marc-Antoine Ruel | 488ce8f | 2014-02-09 11:25:04 -0500 | [diff] [blame] | 1990 | blacklist = tools.gen_blacklist(blacklist) |
| 1991 | with get_storage(out, namespace) as storage: |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 1992 | results = archive_files_to_storage(storage, files, blacklist) |
Marc-Antoine Ruel | 488ce8f | 2014-02-09 11:25:04 -0500 | [diff] [blame] | 1993 | print('\n'.join('%s %s' % (r[0], r[1]) for r in results)) |
| 1994 | |
| 1995 | |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 1996 | @subcommand.usage('<file1..fileN> or - to read from stdin') |
| 1997 | def CMDarchive(parser, args): |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1998 | """Archives data to the server. |
| 1999 | |
| 2000 | If a directory is specified, a .isolated file is created the whole directory |
| 2001 | is uploaded. Then this .isolated file can be included in another one to run |
| 2002 | commands. |
| 2003 | |
| 2004 | The commands output each file that was processed with its content hash. For |
| 2005 | directories, the .isolated generated for the directory is listed as the |
| 2006 | directory entry itself. |
| 2007 | """ |
Marc-Antoine Ruel | f7d737d | 2014-12-10 15:36:29 -0500 | [diff] [blame] | 2008 | add_isolate_server_options(parser) |
Marc-Antoine Ruel | 1f8ba35 | 2014-11-04 15:55:03 -0500 | [diff] [blame] | 2009 | add_archive_options(parser) |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 2010 | options, files = parser.parse_args(args) |
Marc-Antoine Ruel | e290ada | 2014-12-10 19:48:49 -0500 | [diff] [blame] | 2011 | process_isolate_server_options(parser, options, True) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 2012 | try: |
Marc-Antoine Ruel | 488ce8f | 2014-02-09 11:25:04 -0500 | [diff] [blame] | 2013 | archive(options.isolate_server, options.namespace, files, options.blacklist) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 2014 | except Error as e: |
| 2015 | parser.error(e.args[0]) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 2016 | return 0 |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 2017 | |
| 2018 | |
| 2019 | def CMDdownload(parser, args): |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 2020 | """Download data from the server. |
| 2021 | |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 2022 | It can either download individual files or a complete tree from a .isolated |
| 2023 | file. |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 2024 | """ |
Marc-Antoine Ruel | f7d737d | 2014-12-10 15:36:29 -0500 | [diff] [blame] | 2025 | add_isolate_server_options(parser) |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 2026 | parser.add_option( |
Marc-Antoine Ruel | 185ded4 | 2015-01-28 20:49:18 -0500 | [diff] [blame] | 2027 | '-s', '--isolated', metavar='HASH', |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 2028 | help='hash of an isolated file, .isolated file content is discarded, use ' |
| 2029 | '--file if you need it') |
| 2030 | parser.add_option( |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 2031 | '-f', '--file', metavar='HASH DEST', default=[], action='append', nargs=2, |
| 2032 | help='hash and destination of a file, can be used multiple times') |
| 2033 | parser.add_option( |
Marc-Antoine Ruel | f90861c | 2015-03-24 20:54:49 -0400 | [diff] [blame] | 2034 | '-t', '--target', metavar='DIR', default='download', |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 2035 | help='destination directory') |
Marc-Antoine Ruel | a57d7db | 2014-10-15 20:31:19 -0400 | [diff] [blame] | 2036 | add_cache_options(parser) |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 2037 | options, args = parser.parse_args(args) |
| 2038 | if args: |
| 2039 | parser.error('Unsupported arguments: %s' % args) |
Marc-Antoine Ruel | f7d737d | 2014-12-10 15:36:29 -0500 | [diff] [blame] | 2040 | |
Marc-Antoine Ruel | e290ada | 2014-12-10 19:48:49 -0500 | [diff] [blame] | 2041 | process_isolate_server_options(parser, options, True) |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 2042 | if bool(options.isolated) == bool(options.file): |
| 2043 | parser.error('Use one of --isolated or --file, and only one.') |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 2044 | |
Marc-Antoine Ruel | a57d7db | 2014-10-15 20:31:19 -0400 | [diff] [blame] | 2045 | cache = process_cache_options(options) |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 2046 | options.target = unicode(os.path.abspath(options.target)) |
Marc-Antoine Ruel | f90861c | 2015-03-24 20:54:49 -0400 | [diff] [blame] | 2047 | if options.isolated: |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 2048 | if (fs.isfile(options.target) or |
| 2049 | (fs.isdir(options.target) and fs.listdir(options.target))): |
Marc-Antoine Ruel | f90861c | 2015-03-24 20:54:49 -0400 | [diff] [blame] | 2050 | parser.error( |
| 2051 | '--target \'%s\' exists, please use another target' % options.target) |
Marc-Antoine Ruel | f7d737d | 2014-12-10 15:36:29 -0500 | [diff] [blame] | 2052 | with get_storage(options.isolate_server, options.namespace) as storage: |
Vadim Shtayura | 3172be5 | 2013-12-03 12:49:05 -0800 | [diff] [blame] | 2053 | # Fetching individual files. |
| 2054 | if options.file: |
Marc-Antoine Ruel | a57d7db | 2014-10-15 20:31:19 -0400 | [diff] [blame] | 2055 | # TODO(maruel): Enable cache in this case too. |
Vadim Shtayura | 3172be5 | 2013-12-03 12:49:05 -0800 | [diff] [blame] | 2056 | channel = threading_utils.TaskChannel() |
| 2057 | pending = {} |
| 2058 | for digest, dest in options.file: |
| 2059 | pending[digest] = dest |
| 2060 | storage.async_fetch( |
| 2061 | channel, |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 2062 | threading_utils.PRIORITY_MED, |
Vadim Shtayura | 3172be5 | 2013-12-03 12:49:05 -0800 | [diff] [blame] | 2063 | digest, |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 2064 | UNKNOWN_FILE_SIZE, |
Vadim Shtayura | 3172be5 | 2013-12-03 12:49:05 -0800 | [diff] [blame] | 2065 | functools.partial(file_write, os.path.join(options.target, dest))) |
| 2066 | while pending: |
| 2067 | fetched = channel.pull() |
| 2068 | dest = pending.pop(fetched) |
| 2069 | logging.info('%s: %s', fetched, dest) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 2070 | |
Vadim Shtayura | 3172be5 | 2013-12-03 12:49:05 -0800 | [diff] [blame] | 2071 | # Fetching whole isolated tree. |
| 2072 | if options.isolated: |
Marc-Antoine Ruel | a57d7db | 2014-10-15 20:31:19 -0400 | [diff] [blame] | 2073 | with cache: |
| 2074 | bundle = fetch_isolated( |
| 2075 | isolated_hash=options.isolated, |
| 2076 | storage=storage, |
| 2077 | cache=cache, |
| 2078 | outdir=options.target, |
| 2079 | require_command=False) |
| 2080 | if bundle.command: |
| 2081 | rel = os.path.join(options.target, bundle.relative_cwd) |
| 2082 | print('To run this test please run from the directory %s:' % |
| 2083 | os.path.join(options.target, rel)) |
| 2084 | print(' ' + ' '.join(bundle.command)) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 2085 | |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 2086 | return 0 |
| 2087 | |
| 2088 | |
Marc-Antoine Ruel | 1f8ba35 | 2014-11-04 15:55:03 -0500 | [diff] [blame] | 2089 | def add_archive_options(parser): |
| 2090 | parser.add_option( |
| 2091 | '--blacklist', |
| 2092 | action='append', default=list(DEFAULT_BLACKLIST), |
| 2093 | help='List of regexp to use as blacklist filter when uploading ' |
| 2094 | 'directories') |
| 2095 | |
| 2096 | |
Marc-Antoine Ruel | f7d737d | 2014-12-10 15:36:29 -0500 | [diff] [blame] | 2097 | def add_isolate_server_options(parser): |
| 2098 | """Adds --isolate-server and --namespace options to parser.""" |
Marc-Antoine Ruel | 1687b5e | 2014-02-06 17:47:53 -0500 | [diff] [blame] | 2099 | parser.add_option( |
| 2100 | '-I', '--isolate-server', |
| 2101 | metavar='URL', default=os.environ.get('ISOLATE_SERVER', ''), |
Marc-Antoine Ruel | 8806e62 | 2014-02-12 14:15:53 -0500 | [diff] [blame] | 2102 | help='URL of the Isolate Server to use. Defaults to the environment ' |
| 2103 | 'variable ISOLATE_SERVER if set. No need to specify https://, this ' |
| 2104 | 'is assumed.') |
Marc-Antoine Ruel | 1687b5e | 2014-02-06 17:47:53 -0500 | [diff] [blame] | 2105 | parser.add_option( |
| 2106 | '--namespace', default='default-gzip', |
| 2107 | help='The namespace to use on the Isolate Server, default: %default') |
| 2108 | |
| 2109 | |
Marc-Antoine Ruel | e290ada | 2014-12-10 19:48:49 -0500 | [diff] [blame] | 2110 | def process_isolate_server_options(parser, options, set_exception_handler): |
Marc-Antoine Ruel | f7d737d | 2014-12-10 15:36:29 -0500 | [diff] [blame] | 2111 | """Processes the --isolate-server option and aborts if not specified. |
| 2112 | |
| 2113 | Returns the identity as determined by the server. |
Marc-Antoine Ruel | 1687b5e | 2014-02-06 17:47:53 -0500 | [diff] [blame] | 2114 | """ |
| 2115 | if not options.isolate_server: |
Marc-Antoine Ruel | f7d737d | 2014-12-10 15:36:29 -0500 | [diff] [blame] | 2116 | parser.error('--isolate-server is required.') |
Marc-Antoine Ruel | 012067b | 2014-12-10 15:45:42 -0500 | [diff] [blame] | 2117 | try: |
| 2118 | options.isolate_server = net.fix_url(options.isolate_server) |
| 2119 | except ValueError as e: |
| 2120 | parser.error('--isolate-server %s' % e) |
Marc-Antoine Ruel | e290ada | 2014-12-10 19:48:49 -0500 | [diff] [blame] | 2121 | if set_exception_handler: |
| 2122 | on_error.report_on_exception_exit(options.isolate_server) |
Marc-Antoine Ruel | f7d737d | 2014-12-10 15:36:29 -0500 | [diff] [blame] | 2123 | try: |
| 2124 | return auth.ensure_logged_in(options.isolate_server) |
| 2125 | except ValueError as e: |
| 2126 | parser.error(str(e)) |
Marc-Antoine Ruel | 8806e62 | 2014-02-12 14:15:53 -0500 | [diff] [blame] | 2127 | |
Marc-Antoine Ruel | 1687b5e | 2014-02-06 17:47:53 -0500 | [diff] [blame] | 2128 | |
Marc-Antoine Ruel | a57d7db | 2014-10-15 20:31:19 -0400 | [diff] [blame] | 2129 | def add_cache_options(parser): |
| 2130 | cache_group = optparse.OptionGroup(parser, 'Cache management') |
| 2131 | cache_group.add_option( |
| 2132 | '--cache', metavar='DIR', |
| 2133 | help='Directory to keep a local cache of the files. Accelerates download ' |
| 2134 | 'by reusing already downloaded files. Default=%default') |
| 2135 | cache_group.add_option( |
| 2136 | '--max-cache-size', |
| 2137 | type='int', |
| 2138 | metavar='NNN', |
maruel | 7158610 | 2016-01-29 11:44:09 -0800 | [diff] [blame] | 2139 | default=50*1024*1024*1024, |
Marc-Antoine Ruel | a57d7db | 2014-10-15 20:31:19 -0400 | [diff] [blame] | 2140 | help='Trim if the cache gets larger than this value, default=%default') |
| 2141 | cache_group.add_option( |
| 2142 | '--min-free-space', |
| 2143 | type='int', |
| 2144 | metavar='NNN', |
| 2145 | default=2*1024*1024*1024, |
| 2146 | help='Trim if disk free space becomes lower than this value, ' |
| 2147 | 'default=%default') |
| 2148 | cache_group.add_option( |
| 2149 | '--max-items', |
| 2150 | type='int', |
| 2151 | metavar='NNN', |
| 2152 | default=100000, |
| 2153 | help='Trim if more than this number of items are in the cache ' |
| 2154 | 'default=%default') |
| 2155 | parser.add_option_group(cache_group) |
| 2156 | |
| 2157 | |
| 2158 | def process_cache_options(options): |
| 2159 | if options.cache: |
| 2160 | policies = CachePolicies( |
| 2161 | options.max_cache_size, options.min_free_space, options.max_items) |
| 2162 | |
| 2163 | # |options.cache| path may not exist until DiskCache() instance is created. |
| 2164 | return DiskCache( |
Marc-Antoine Ruel | 3c979cb | 2015-03-11 13:43:28 -0400 | [diff] [blame] | 2165 | unicode(os.path.abspath(options.cache)), |
Marc-Antoine Ruel | a57d7db | 2014-10-15 20:31:19 -0400 | [diff] [blame] | 2166 | policies, |
| 2167 | isolated_format.get_hash_algo(options.namespace)) |
| 2168 | else: |
| 2169 | return MemoryCache() |
| 2170 | |
| 2171 | |
Marc-Antoine Ruel | f74cffe | 2015-07-15 15:21:34 -0400 | [diff] [blame] | 2172 | class OptionParserIsolateServer(logging_utils.OptionParserWithLogging): |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 2173 | def __init__(self, **kwargs): |
Marc-Antoine Ruel | f74cffe | 2015-07-15 15:21:34 -0400 | [diff] [blame] | 2174 | logging_utils.OptionParserWithLogging.__init__( |
Marc-Antoine Ruel | ac54cb4 | 2013-11-18 14:05:35 -0500 | [diff] [blame] | 2175 | self, |
| 2176 | version=__version__, |
| 2177 | prog=os.path.basename(sys.modules[__name__].__file__), |
| 2178 | **kwargs) |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 2179 | auth.add_auth_options(self) |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 2180 | |
| 2181 | def parse_args(self, *args, **kwargs): |
Marc-Antoine Ruel | f74cffe | 2015-07-15 15:21:34 -0400 | [diff] [blame] | 2182 | options, args = logging_utils.OptionParserWithLogging.parse_args( |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 2183 | self, *args, **kwargs) |
Vadim Shtayura | 5d1efce | 2014-02-04 10:55:43 -0800 | [diff] [blame] | 2184 | auth.process_auth_options(self, options) |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 2185 | return options, args |
| 2186 | |
| 2187 | |
| 2188 | def main(args): |
| 2189 | dispatcher = subcommand.CommandDispatcher(__name__) |
Marc-Antoine Ruel | cfb6085 | 2014-07-02 15:22:00 -0400 | [diff] [blame] | 2190 | return dispatcher.execute(OptionParserIsolateServer(), args) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 2191 | |
| 2192 | |
| 2193 | if __name__ == '__main__': |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 2194 | fix_encoding.fix_encoding() |
| 2195 | tools.disable_buffering() |
| 2196 | colorama.init() |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 2197 | sys.exit(main(sys.argv[1:])) |