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