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