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