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 | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 8 | __version__ = '0.9.0' |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 9 | |
Marc-Antoine Ruel | d0868ec | 2018-11-28 20:47:29 +0000 | [diff] [blame] | 10 | import collections |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 11 | import errno |
tansell | 9e04a8d | 2016-07-28 09:31:59 -0700 | [diff] [blame] | 12 | import functools |
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 |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 16 | import Queue |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 17 | import re |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 18 | import signal |
tansell | 9e04a8d | 2016-07-28 09:31:59 -0700 | [diff] [blame] | 19 | import stat |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 20 | import sys |
tansell | 26de79e | 2016-11-13 18:41:11 -0800 | [diff] [blame] | 21 | import tarfile |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 22 | import tempfile |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 23 | import threading |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 24 | import time |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 25 | import zlib |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 26 | |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 27 | from third_party import colorama |
| 28 | from third_party.depot_tools import fix_encoding |
| 29 | from third_party.depot_tools import subcommand |
| 30 | |
Marc-Antoine Ruel | 3798993 | 2013-11-19 16:28:08 -0500 | [diff] [blame] | 31 | from utils import file_path |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 32 | from utils import fs |
Marc-Antoine Ruel | f74cffe | 2015-07-15 15:21:34 -0400 | [diff] [blame] | 33 | from utils import logging_utils |
vadimsh@chromium.org | 6b70621 | 2013-08-28 15:03:46 +0000 | [diff] [blame] | 34 | from utils import net |
Marc-Antoine Ruel | cfb6085 | 2014-07-02 15:22:00 -0400 | [diff] [blame] | 35 | from utils import on_error |
maruel | 8e4e40c | 2016-05-30 06:21:07 -0700 | [diff] [blame] | 36 | from utils import subprocess42 |
vadimsh@chromium.org | b074b16 | 2013-08-22 17:55:46 +0000 | [diff] [blame] | 37 | from utils import threading_utils |
vadimsh@chromium.org | a432647 | 2013-08-24 02:05:41 +0000 | [diff] [blame] | 38 | from utils import tools |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 39 | |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 40 | import auth |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 41 | import isolated_format |
aludwin | 8117830 | 2016-11-30 17:18:49 -0800 | [diff] [blame] | 42 | import isolate_storage |
Marc-Antoine Ruel | 34f5f28 | 2018-05-16 16:04:31 -0400 | [diff] [blame] | 43 | import local_caching |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 44 | |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 45 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 46 | # Version of isolate protocol passed to the server in /handshake request. |
| 47 | ISOLATE_PROTOCOL_VERSION = '1.0' |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 48 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 49 | |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 50 | # Maximum expected delay (in seconds) between successive file fetches or uploads |
| 51 | # in Storage. If it takes longer than that, a deadlock might be happening |
| 52 | # and all stack frames for all threads are dumped to log. |
| 53 | DEADLOCK_TIMEOUT = 5 * 60 |
| 54 | |
| 55 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 56 | # 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] | 57 | # All files are sorted by likelihood of a change in the file content |
| 58 | # (currently file size is used to estimate this: larger the file -> larger the |
| 59 | # 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] | 60 | # 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] | 61 | # and so on. Numbers here is a trade-off; the more per request, the lower the |
| 62 | # effect of HTTP round trip latency and TCP-level chattiness. On the other hand, |
| 63 | # larger values cause longer lookups, increasing the initial latency to start |
| 64 | # uploading, which is especially an issue for large files. This value is |
| 65 | # optimized for the "few thousands files to look up with minimal number of large |
| 66 | # files missing" case. |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 67 | ITEMS_PER_CONTAINS_QUERIES = (20, 20, 50, 50, 50, 100) |
csharp@chromium.org | 07fa759 | 2013-01-11 18:19:30 +0000 | [diff] [blame] | 68 | |
maruel@chromium.org | 9958e4a | 2013-09-17 00:01:48 +0000 | [diff] [blame] | 69 | |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 70 | # A list of already compressed extension types that should not receive any |
| 71 | # compression before being uploaded. |
| 72 | ALREADY_COMPRESSED_TYPES = [ |
Marc-Antoine Ruel | 7f234c8 | 2014-08-06 21:55:18 -0400 | [diff] [blame] | 73 | '7z', 'avi', 'cur', 'gif', 'h264', 'jar', 'jpeg', 'jpg', 'mp4', 'pdf', |
| 74 | 'png', 'wav', 'zip', |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 75 | ] |
| 76 | |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 77 | |
maruel@chromium.org | 4160164 | 2013-09-18 19:40:46 +0000 | [diff] [blame] | 78 | # The delay (in seconds) to wait between logging statements when retrieving |
| 79 | # the required files. This is intended to let the user (or buildbot) know that |
| 80 | # the program is still running. |
| 81 | DELAY_BETWEEN_UPDATES_IN_SECS = 30 |
| 82 | |
| 83 | |
Marc-Antoine Ruel | ac54cb4 | 2013-11-18 14:05:35 -0500 | [diff] [blame] | 84 | DEFAULT_BLACKLIST = ( |
| 85 | # Temporary vim or python files. |
| 86 | r'^.+\.(?:pyc|swp)$', |
| 87 | # .git or .svn directory. |
| 88 | r'^(?:.+' + re.escape(os.path.sep) + r'|)\.(?:git|svn)$', |
| 89 | ) |
| 90 | |
| 91 | |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 92 | class Error(Exception): |
| 93 | """Generic runtime error.""" |
| 94 | pass |
| 95 | |
| 96 | |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 97 | class Aborted(Error): |
| 98 | """Operation aborted.""" |
| 99 | pass |
| 100 | |
| 101 | |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 102 | class AlreadyExists(Error): |
| 103 | """File already exists.""" |
| 104 | |
| 105 | |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 106 | 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] | 107 | """Yields file content in chunks of |chunk_size| starting from |offset|.""" |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 108 | with fs.open(path, 'rb') as f: |
Vadim Shtayura | f0cb97a | 2013-12-05 13:57:49 -0800 | [diff] [blame] | 109 | if offset: |
| 110 | f.seek(offset) |
maruel@chromium.org | 8750e4b | 2013-09-18 02:37:57 +0000 | [diff] [blame] | 111 | while True: |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 112 | data = f.read(chunk_size) |
maruel@chromium.org | 8750e4b | 2013-09-18 02:37:57 +0000 | [diff] [blame] | 113 | if not data: |
| 114 | break |
| 115 | yield data |
| 116 | |
| 117 | |
tansell | 9e04a8d | 2016-07-28 09:31:59 -0700 | [diff] [blame] | 118 | def fileobj_path(fileobj): |
| 119 | """Return file system path for file like object or None. |
| 120 | |
| 121 | The returned path is guaranteed to exist and can be passed to file system |
| 122 | operations like copy. |
| 123 | """ |
| 124 | name = getattr(fileobj, 'name', None) |
| 125 | if name is None: |
| 126 | return |
| 127 | |
| 128 | # If the file like object was created using something like open("test.txt") |
| 129 | # name will end up being a str (such as a function outside our control, like |
| 130 | # the standard library). We want all our paths to be unicode objects, so we |
| 131 | # decode it. |
| 132 | if not isinstance(name, unicode): |
Marc-Antoine Ruel | d8464b1 | 2017-12-04 15:59:41 -0500 | [diff] [blame] | 133 | # We incorrectly assume that UTF-8 is used everywhere. |
| 134 | name = name.decode('utf-8') |
tansell | 9e04a8d | 2016-07-28 09:31:59 -0700 | [diff] [blame] | 135 | |
tansell | 26de79e | 2016-11-13 18:41:11 -0800 | [diff] [blame] | 136 | # fs.exists requires an absolute path, otherwise it will fail with an |
| 137 | # assertion error. |
| 138 | if not os.path.isabs(name): |
| 139 | return |
| 140 | |
tansell | 9e04a8d | 2016-07-28 09:31:59 -0700 | [diff] [blame] | 141 | if fs.exists(name): |
| 142 | return name |
| 143 | |
| 144 | |
| 145 | # TODO(tansell): Replace fileobj_copy with shutil.copyfileobj once proper file |
| 146 | # wrappers have been created. |
| 147 | def fileobj_copy( |
| 148 | dstfileobj, srcfileobj, size=-1, |
| 149 | chunk_size=isolated_format.DISK_FILE_CHUNK): |
| 150 | """Copy data from srcfileobj to dstfileobj. |
| 151 | |
| 152 | Providing size means exactly that amount of data will be copied (if there |
| 153 | isn't enough data, an IOError exception is thrown). Otherwise all data until |
| 154 | the EOF marker will be copied. |
| 155 | """ |
| 156 | if size == -1 and hasattr(srcfileobj, 'tell'): |
| 157 | if srcfileobj.tell() != 0: |
| 158 | raise IOError('partial file but not using size') |
| 159 | |
| 160 | written = 0 |
| 161 | while written != size: |
| 162 | readsize = chunk_size |
| 163 | if size > 0: |
| 164 | readsize = min(readsize, size-written) |
| 165 | data = srcfileobj.read(readsize) |
| 166 | if not data: |
| 167 | if size == -1: |
| 168 | break |
| 169 | raise IOError('partial file, got %s, wanted %s' % (written, size)) |
| 170 | dstfileobj.write(data) |
| 171 | written += len(data) |
| 172 | |
| 173 | |
| 174 | def putfile(srcfileobj, dstpath, file_mode=None, size=-1, use_symlink=False): |
| 175 | """Put srcfileobj at the given dstpath with given mode. |
| 176 | |
| 177 | The function aims to do this as efficiently as possible while still allowing |
| 178 | any possible file like object be given. |
| 179 | |
| 180 | Creating a tree of hardlinks has a few drawbacks: |
| 181 | - tmpfs cannot be used for the scratch space. The tree has to be on the same |
| 182 | partition as the cache. |
| 183 | - involves a write to the inode, which advances ctime, cause a metadata |
| 184 | writeback (causing disk seeking). |
| 185 | - cache ctime cannot be used to detect modifications / corruption. |
| 186 | - Some file systems (NTFS) have a 64k limit on the number of hardlink per |
| 187 | partition. This is why the function automatically fallbacks to copying the |
| 188 | file content. |
| 189 | - /proc/sys/fs/protected_hardlinks causes an additional check to ensure the |
| 190 | same owner is for all hardlinks. |
| 191 | - Anecdotal report that ext2 is known to be potentially faulty on high rate |
| 192 | of hardlink creation. |
| 193 | |
| 194 | Creating a tree of symlinks has a few drawbacks: |
| 195 | - Tasks running the equivalent of os.path.realpath() will get the naked path |
| 196 | and may fail. |
| 197 | - Windows: |
| 198 | - Symlinks are reparse points: |
| 199 | https://msdn.microsoft.com/library/windows/desktop/aa365460.aspx |
| 200 | https://msdn.microsoft.com/library/windows/desktop/aa363940.aspx |
| 201 | - Symbolic links are Win32 paths, not NT paths. |
| 202 | https://googleprojectzero.blogspot.com/2016/02/the-definitive-guide-on-win32-to-nt.html |
| 203 | - Symbolic links are supported on Windows 7 and later only. |
| 204 | - SeCreateSymbolicLinkPrivilege is needed, which is not present by |
| 205 | default. |
| 206 | - SeCreateSymbolicLinkPrivilege is *stripped off* by UAC when a restricted |
| 207 | RID is present in the token; |
| 208 | https://msdn.microsoft.com/en-us/library/bb530410.aspx |
| 209 | """ |
| 210 | srcpath = fileobj_path(srcfileobj) |
| 211 | if srcpath and size == -1: |
| 212 | readonly = file_mode is None or ( |
| 213 | file_mode & (stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)) |
| 214 | |
| 215 | if readonly: |
| 216 | # If the file is read only we can link the file |
| 217 | if use_symlink: |
| 218 | link_mode = file_path.SYMLINK_WITH_FALLBACK |
| 219 | else: |
| 220 | link_mode = file_path.HARDLINK_WITH_FALLBACK |
| 221 | else: |
| 222 | # If not read only, we must copy the file |
| 223 | link_mode = file_path.COPY |
| 224 | |
| 225 | file_path.link_file(dstpath, srcpath, link_mode) |
| 226 | else: |
| 227 | # Need to write out the file |
| 228 | with fs.open(dstpath, 'wb') as dstfileobj: |
| 229 | fileobj_copy(dstfileobj, srcfileobj, size) |
| 230 | |
| 231 | assert fs.exists(dstpath) |
| 232 | |
| 233 | # file_mode of 0 is actually valid, so need explicit check. |
| 234 | if file_mode is not None: |
| 235 | fs.chmod(dstpath, file_mode) |
| 236 | |
| 237 | |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 238 | def zip_compress(content_generator, level=7): |
| 239 | """Reads chunks from |content_generator| and yields zip compressed chunks.""" |
| 240 | compressor = zlib.compressobj(level) |
| 241 | for chunk in content_generator: |
| 242 | compressed = compressor.compress(chunk) |
| 243 | if compressed: |
| 244 | yield compressed |
| 245 | tail = compressor.flush(zlib.Z_FINISH) |
| 246 | if tail: |
| 247 | yield tail |
| 248 | |
| 249 | |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 250 | def zip_decompress( |
| 251 | content_generator, chunk_size=isolated_format.DISK_FILE_CHUNK): |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 252 | """Reads zipped data from |content_generator| and yields decompressed data. |
| 253 | |
| 254 | Decompresses data in small chunks (no larger than |chunk_size|) so that |
| 255 | zip bomb file doesn't cause zlib to preallocate huge amount of memory. |
| 256 | |
| 257 | Raises IOError if data is corrupted or incomplete. |
| 258 | """ |
| 259 | decompressor = zlib.decompressobj() |
| 260 | compressed_size = 0 |
| 261 | try: |
| 262 | for chunk in content_generator: |
| 263 | compressed_size += len(chunk) |
| 264 | data = decompressor.decompress(chunk, chunk_size) |
| 265 | if data: |
| 266 | yield data |
| 267 | while decompressor.unconsumed_tail: |
| 268 | data = decompressor.decompress(decompressor.unconsumed_tail, chunk_size) |
| 269 | if data: |
| 270 | yield data |
| 271 | tail = decompressor.flush() |
| 272 | if tail: |
| 273 | yield tail |
| 274 | except zlib.error as e: |
| 275 | raise IOError( |
| 276 | 'Corrupted zip stream (read %d bytes) - %s' % (compressed_size, e)) |
| 277 | # Ensure all data was read and decompressed. |
| 278 | if decompressor.unused_data or decompressor.unconsumed_tail: |
| 279 | raise IOError('Not all data was decompressed') |
| 280 | |
| 281 | |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 282 | def get_zip_compression_level(filename): |
| 283 | """Given a filename calculates the ideal zip compression level to use.""" |
| 284 | file_ext = os.path.splitext(filename)[1].lower() |
| 285 | # TODO(csharp): Profile to find what compression level works best. |
| 286 | return 0 if file_ext in ALREADY_COMPRESSED_TYPES else 7 |
| 287 | |
| 288 | |
maruel@chromium.org | af25485 | 2013-09-17 17:48:14 +0000 | [diff] [blame] | 289 | def create_directories(base_directory, files): |
| 290 | """Creates the directory structure needed by the given list of files.""" |
| 291 | logging.debug('create_directories(%s, %d)', base_directory, len(files)) |
| 292 | # Creates the tree of directories to create. |
| 293 | directories = set(os.path.dirname(f) for f in files) |
| 294 | for item in list(directories): |
| 295 | while item: |
| 296 | directories.add(item) |
| 297 | item = os.path.dirname(item) |
| 298 | for d in sorted(directories): |
| 299 | if d: |
aludwin | 606aa1f | 2016-10-31 18:41:30 -0700 | [diff] [blame] | 300 | abs_d = os.path.join(base_directory, d) |
| 301 | if not fs.isdir(abs_d): |
| 302 | fs.mkdir(abs_d) |
maruel@chromium.org | af25485 | 2013-09-17 17:48:14 +0000 | [diff] [blame] | 303 | |
| 304 | |
Marc-Antoine Ruel | ccafe0e | 2013-11-08 16:15:36 -0500 | [diff] [blame] | 305 | def create_symlinks(base_directory, files): |
| 306 | """Creates any symlinks needed by the given set of files.""" |
maruel@chromium.org | af25485 | 2013-09-17 17:48:14 +0000 | [diff] [blame] | 307 | for filepath, properties in files: |
| 308 | if 'l' not in properties: |
| 309 | continue |
| 310 | if sys.platform == 'win32': |
Marc-Antoine Ruel | ccafe0e | 2013-11-08 16:15:36 -0500 | [diff] [blame] | 311 | # TODO(maruel): Create symlink via the win32 api. |
maruel@chromium.org | af25485 | 2013-09-17 17:48:14 +0000 | [diff] [blame] | 312 | logging.warning('Ignoring symlink %s', filepath) |
| 313 | continue |
| 314 | outfile = os.path.join(base_directory, filepath) |
nodir | 90bc8dc | 2016-06-15 13:35:21 -0700 | [diff] [blame] | 315 | try: |
| 316 | os.symlink(properties['l'], outfile) # pylint: disable=E1101 |
| 317 | except OSError as e: |
| 318 | if e.errno == errno.EEXIST: |
| 319 | raise AlreadyExists('File %s already exists.' % outfile) |
| 320 | raise |
maruel@chromium.org | af25485 | 2013-09-17 17:48:14 +0000 | [diff] [blame] | 321 | |
| 322 | |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 323 | class FileItem(isolate_storage.Item): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 324 | """A file to push to Storage. |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 325 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 326 | Its digest and size may be provided in advance, if known. Otherwise they will |
| 327 | be derived from the file content. |
| 328 | """ |
| 329 | |
| 330 | def __init__(self, path, digest=None, size=None, high_priority=False): |
| 331 | super(FileItem, self).__init__( |
| 332 | digest, |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 333 | size if size is not None else fs.stat(path).st_size, |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 334 | high_priority) |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 335 | self.path = path |
| 336 | self.compression_level = get_zip_compression_level(path) |
| 337 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 338 | def content(self): |
| 339 | return file_read(self.path) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 340 | |
| 341 | |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 342 | class BufferItem(isolate_storage.Item): |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 343 | """A byte buffer to push to Storage.""" |
| 344 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 345 | def __init__(self, buf, high_priority=False): |
| 346 | super(BufferItem, self).__init__(None, len(buf), high_priority) |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 347 | self.buffer = buf |
| 348 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 349 | def content(self): |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 350 | return [self.buffer] |
| 351 | |
| 352 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 353 | class Storage(object): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 354 | """Efficiently downloads or uploads large set of files via StorageApi. |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 355 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 356 | Implements compression support, parallel 'contains' checks, parallel uploads |
| 357 | and more. |
| 358 | |
| 359 | Works only within single namespace (and thus hashing algorithm and compression |
| 360 | scheme are fixed). |
| 361 | |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 362 | Spawns multiple internal threads. Thread safe, but not fork safe. Modifies |
| 363 | signal handlers table to handle Ctrl+C. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 364 | """ |
| 365 | |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 366 | def __init__(self, storage_api): |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 367 | self._storage_api = storage_api |
| 368 | self._cpu_thread_pool = None |
| 369 | self._net_thread_pool = None |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 370 | self._aborted = False |
| 371 | self._prev_sig_handlers = {} |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 372 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 373 | @property |
Marc-Antoine Ruel | b851313 | 2018-11-20 19:48:53 +0000 | [diff] [blame] | 374 | def server_ref(self): |
| 375 | """Shortcut to get the server_ref from storage_api. |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 376 | |
Marc-Antoine Ruel | b851313 | 2018-11-20 19:48:53 +0000 | [diff] [blame] | 377 | This can be used to get the underlying hash_algo. |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 378 | """ |
Marc-Antoine Ruel | b851313 | 2018-11-20 19:48:53 +0000 | [diff] [blame] | 379 | return self._storage_api.server_ref |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 380 | |
| 381 | @property |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 382 | def cpu_thread_pool(self): |
| 383 | """ThreadPool for CPU-bound tasks like zipping.""" |
| 384 | if self._cpu_thread_pool is None: |
Marc-Antoine Ruel | bdad118 | 2015-02-06 16:04:35 -0500 | [diff] [blame] | 385 | threads = max(threading_utils.num_processors(), 2) |
| 386 | if sys.maxsize <= 2L**32: |
| 387 | # On 32 bits userland, do not try to use more than 16 threads. |
| 388 | threads = min(threads, 16) |
| 389 | self._cpu_thread_pool = threading_utils.ThreadPool(2, threads, 0, 'zip') |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 390 | return self._cpu_thread_pool |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 391 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 392 | @property |
| 393 | def net_thread_pool(self): |
| 394 | """AutoRetryThreadPool for IO-bound tasks, retries IOError.""" |
| 395 | if self._net_thread_pool is None: |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 396 | self._net_thread_pool = threading_utils.IOAutoRetryThreadPool() |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 397 | return self._net_thread_pool |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 398 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 399 | def close(self): |
| 400 | """Waits for all pending tasks to finish.""" |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 401 | logging.info('Waiting for all threads to die...') |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 402 | if self._cpu_thread_pool: |
| 403 | self._cpu_thread_pool.join() |
| 404 | self._cpu_thread_pool.close() |
| 405 | self._cpu_thread_pool = None |
| 406 | if self._net_thread_pool: |
| 407 | self._net_thread_pool.join() |
| 408 | self._net_thread_pool.close() |
| 409 | self._net_thread_pool = None |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 410 | logging.info('Done.') |
| 411 | |
| 412 | def abort(self): |
| 413 | """Cancels any pending or future operations.""" |
| 414 | # This is not strictly theadsafe, but in the worst case the logging message |
| 415 | # will be printed twice. Not a big deal. In other places it is assumed that |
| 416 | # unprotected reads and writes to _aborted are serializable (it is true |
| 417 | # for python) and thus no locking is used. |
| 418 | if not self._aborted: |
| 419 | logging.warning('Aborting... It can take a while.') |
| 420 | self._aborted = True |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 421 | |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 422 | def __enter__(self): |
| 423 | """Context manager interface.""" |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 424 | assert not self._prev_sig_handlers, self._prev_sig_handlers |
| 425 | for s in (signal.SIGINT, signal.SIGTERM): |
| 426 | 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] | 427 | return self |
| 428 | |
| 429 | def __exit__(self, _exc_type, _exc_value, _traceback): |
| 430 | """Context manager interface.""" |
| 431 | self.close() |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 432 | while self._prev_sig_handlers: |
| 433 | s, h = self._prev_sig_handlers.popitem() |
| 434 | signal.signal(s, h) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 435 | return False |
| 436 | |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 437 | def upload_items(self, items): |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 438 | """Uploads a generator of Item to the isolate server. |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 439 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 440 | 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] | 441 | |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 442 | It uses 3 threads internally: |
| 443 | - One to create batches based on a timeout |
| 444 | - One to dispatch the /contains RPC and field the missing entries |
| 445 | - One to field the /push RPC |
| 446 | |
| 447 | The main threads enumerates 'items' and pushes to the first thread. Then it |
| 448 | join() all the threads, waiting for them to complete. |
| 449 | |
| 450 | (enumerate items of Item, this can be slow as disk is traversed) |
| 451 | | |
| 452 | v |
| 453 | _create_items_batches_thread Thread #1 |
| 454 | (generates list(Item), every 3s or 20~100 items) |
| 455 | | |
| 456 | v |
| 457 | _do_lookups_thread Thread #2 |
| 458 | | | |
| 459 | v v |
| 460 | (missing) (was on server) |
| 461 | | |
| 462 | v |
| 463 | _handle_missing_thread Thread #3 |
| 464 | | |
| 465 | v |
| 466 | (upload Item, append to uploaded) |
| 467 | |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 468 | Arguments: |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 469 | items: list of isolate_storage.Item instances that represents data to |
| 470 | upload. |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 471 | |
| 472 | Returns: |
| 473 | List of items that were uploaded. All other items are already there. |
| 474 | """ |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 475 | incoming = Queue.Queue() |
| 476 | batches_to_lookup = Queue.Queue() |
| 477 | missing = Queue.Queue() |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 478 | uploaded = [] |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 479 | |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 480 | def _create_items_batches_thread(): |
| 481 | """Creates batches for /contains RPC lookup from individual items. |
| 482 | |
| 483 | Input: incoming |
| 484 | Output: batches_to_lookup |
| 485 | """ |
| 486 | try: |
| 487 | batch_size_index = 0 |
| 488 | batch_size = ITEMS_PER_CONTAINS_QUERIES[batch_size_index] |
| 489 | batch = [] |
| 490 | while not self._aborted: |
| 491 | try: |
| 492 | item = incoming.get(True, timeout=3) |
| 493 | if item: |
| 494 | batch.append(item) |
| 495 | except Queue.Empty: |
| 496 | item = False |
| 497 | if len(batch) == batch_size or (not item and batch): |
| 498 | if len(batch) == batch_size: |
| 499 | batch_size_index += 1 |
| 500 | batch_size = ITEMS_PER_CONTAINS_QUERIES[ |
| 501 | min(batch_size_index, len(ITEMS_PER_CONTAINS_QUERIES)-1)] |
| 502 | batches_to_lookup.put(batch) |
| 503 | batch = [] |
| 504 | if item is None: |
| 505 | break |
| 506 | finally: |
| 507 | # Unblock the next pipeline. |
| 508 | batches_to_lookup.put(None) |
| 509 | |
| 510 | def _do_lookups_thread(): |
| 511 | """Enqueues all the /contains RPCs and emits the missing items. |
| 512 | |
| 513 | Input: batches_to_lookup |
| 514 | Output: missing, to_upload |
| 515 | """ |
| 516 | try: |
| 517 | channel = threading_utils.TaskChannel() |
| 518 | def _contains(b): |
| 519 | if self._aborted: |
| 520 | raise Aborted() |
| 521 | return self._storage_api.contains(b) |
| 522 | |
| 523 | pending_contains = 0 |
| 524 | while not self._aborted: |
| 525 | batch = batches_to_lookup.get() |
| 526 | if batch is None: |
| 527 | break |
| 528 | self.net_thread_pool.add_task_with_channel( |
| 529 | channel, threading_utils.PRIORITY_HIGH, _contains, batch) |
| 530 | pending_contains += 1 |
| 531 | while pending_contains and not self._aborted: |
| 532 | try: |
Marc-Antoine Ruel | 4494b6c | 2018-11-28 21:00:41 +0000 | [diff] [blame] | 533 | v = channel.next(timeout=0) |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 534 | except threading_utils.TaskChannel.Timeout: |
| 535 | break |
| 536 | pending_contains -= 1 |
| 537 | for missing_item, push_state in v.iteritems(): |
| 538 | missing.put((missing_item, push_state)) |
| 539 | while pending_contains and not self._aborted: |
Marc-Antoine Ruel | 4494b6c | 2018-11-28 21:00:41 +0000 | [diff] [blame] | 540 | for missing_item, push_state in channel.next().iteritems(): |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 541 | missing.put((missing_item, push_state)) |
| 542 | pending_contains -= 1 |
| 543 | finally: |
| 544 | # Unblock the next pipeline. |
| 545 | missing.put((None, None)) |
| 546 | |
| 547 | def _handle_missing_thread(): |
| 548 | """Sends the missing items to the uploader. |
| 549 | |
| 550 | Input: missing |
| 551 | Output: uploaded |
| 552 | """ |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 553 | with threading_utils.DeadlockDetector(DEADLOCK_TIMEOUT) as detector: |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 554 | channel = threading_utils.TaskChannel() |
| 555 | pending_upload = 0 |
| 556 | while not self._aborted: |
| 557 | try: |
| 558 | missing_item, push_state = missing.get(True, timeout=5) |
| 559 | if missing_item is None: |
| 560 | break |
| 561 | self._async_push(channel, missing_item, push_state) |
| 562 | pending_upload += 1 |
| 563 | except Queue.Empty: |
| 564 | pass |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 565 | detector.ping() |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 566 | while not self._aborted and pending_upload: |
| 567 | try: |
Marc-Antoine Ruel | 4494b6c | 2018-11-28 21:00:41 +0000 | [diff] [blame] | 568 | item = channel.next(timeout=0) |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 569 | except threading_utils.TaskChannel.Timeout: |
| 570 | break |
| 571 | uploaded.append(item) |
| 572 | pending_upload -= 1 |
| 573 | logging.debug( |
| 574 | 'Uploaded %d; %d pending: %s (%d)', |
| 575 | len(uploaded), pending_upload, item.digest, item.size) |
| 576 | while not self._aborted and pending_upload: |
Marc-Antoine Ruel | 4494b6c | 2018-11-28 21:00:41 +0000 | [diff] [blame] | 577 | item = channel.next() |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 578 | uploaded.append(item) |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 579 | pending_upload -= 1 |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 580 | logging.debug( |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 581 | 'Uploaded %d; %d pending: %s (%d)', |
| 582 | len(uploaded), pending_upload, item.digest, item.size) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 583 | |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 584 | threads = [ |
| 585 | threading.Thread(target=_create_items_batches_thread), |
| 586 | threading.Thread(target=_do_lookups_thread), |
| 587 | threading.Thread(target=_handle_missing_thread), |
| 588 | ] |
| 589 | for t in threads: |
| 590 | t.start() |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 591 | |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 592 | try: |
| 593 | # For each digest keep only first isolate_storage.Item that matches it. |
| 594 | # All other items are just indistinguishable copies from the point of view |
| 595 | # of isolate server (it doesn't care about paths at all, only content and |
| 596 | # digests). |
| 597 | seen = {} |
| 598 | try: |
| 599 | # TODO(maruel): Reorder the items as a priority queue, with larger items |
| 600 | # being processed first. This is, before hashing the data. |
| 601 | # This must be done in the primary thread since items can be a |
| 602 | # generator. |
| 603 | for item in items: |
| 604 | # This is I/O heavy. |
| 605 | item.prepare(self.server_ref.hash_algo) |
| 606 | if seen.setdefault(item.digest, item) is item: |
| 607 | incoming.put(item) |
| 608 | finally: |
| 609 | incoming.put(None) |
| 610 | finally: |
| 611 | for t in threads: |
| 612 | t.join() |
| 613 | |
| 614 | logging.info('All %s files are uploaded', len(uploaded)) |
| 615 | _print_upload_stats(seen.values(), uploaded) |
vadimsh@chromium.org | f24e5c3 | 2013-10-11 21:16:21 +0000 | [diff] [blame] | 616 | return uploaded |
| 617 | |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 618 | def _async_push(self, channel, item, push_state): |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 619 | """Starts asynchronous push to the server in a parallel thread. |
| 620 | |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 621 | Can be used only after |item| was checked for presence on a server with a |
| 622 | /contains RPC. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 623 | |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 624 | Arguments: |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 625 | channel: TaskChannel that receives back |item| when upload ends. |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 626 | item: item to upload as instance of isolate_storage.Item class. |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 627 | push_state: push state returned by storage_api.contains(). It contains |
| 628 | storage specific information describing how to upload the item (for |
| 629 | example in case of cloud storage, it is signed upload URLs). |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 630 | |
| 631 | Returns: |
| 632 | None, but |channel| later receives back |item| when upload ends. |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 633 | """ |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 634 | # Thread pool task priority. |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 635 | priority = ( |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 636 | threading_utils.PRIORITY_HIGH if item.high_priority |
| 637 | else threading_utils.PRIORITY_MED) |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 638 | |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 639 | def _push(content): |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 640 | """Pushes an isolate_storage.Item and returns it to |channel|.""" |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 641 | if self._aborted: |
| 642 | raise Aborted() |
Marc-Antoine Ruel | b851313 | 2018-11-20 19:48:53 +0000 | [diff] [blame] | 643 | item.prepare(self.server_ref.hash_algo) |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 644 | self._storage_api.push(item, push_state, content) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 645 | return item |
| 646 | |
Wei Huang | 1a38fbe | 2017-11-28 22:55:22 -0500 | [diff] [blame] | 647 | # If zipping is not required, just start a push task. Don't pass 'content' |
| 648 | # so that it can create a new generator when it retries on failures. |
Marc-Antoine Ruel | b851313 | 2018-11-20 19:48:53 +0000 | [diff] [blame] | 649 | if not self.server_ref.is_with_compression: |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 650 | 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] | 651 | return |
| 652 | |
| 653 | # If zipping is enabled, zip in a separate thread. |
| 654 | def zip_and_push(): |
| 655 | # TODO(vadimsh): Implement streaming uploads. Before it's done, assemble |
| 656 | # content right here. It will block until all file is zipped. |
| 657 | try: |
Vadim Shtayura | f9e401b | 2014-10-15 18:19:37 +0400 | [diff] [blame] | 658 | if self._aborted: |
| 659 | raise Aborted() |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 660 | stream = zip_compress(item.content(), item.compression_level) |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 661 | data = ''.join(stream) |
| 662 | except Exception as exc: |
| 663 | logging.error('Failed to zip \'%s\': %s', item, exc) |
Vadim Shtayura | 0ffc409 | 2013-11-20 17:49:52 -0800 | [diff] [blame] | 664 | channel.send_exception() |
vadimsh@chromium.org | 7cdf1c0 | 2013-09-25 00:24:16 +0000 | [diff] [blame] | 665 | return |
Wei Huang | 1a38fbe | 2017-11-28 22:55:22 -0500 | [diff] [blame] | 666 | # Pass '[data]' explicitly because the compressed data is not same as the |
| 667 | # one provided by 'item'. Since '[data]' is a list, it can safely be |
| 668 | # reused during retries. |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 669 | self.net_thread_pool.add_task_with_channel( |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 670 | channel, priority, _push, [data]) |
vadimsh@chromium.org | bcb966b | 2013-10-01 18:14:18 +0000 | [diff] [blame] | 671 | self.cpu_thread_pool.add_task(priority, zip_and_push) |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 672 | |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 673 | def push(self, item, push_state): |
| 674 | """Synchronously pushes a single item to the server. |
| 675 | |
| 676 | If you need to push many items at once, consider using 'upload_items' or |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 677 | '_async_push' with instance of TaskChannel. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 678 | |
| 679 | Arguments: |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 680 | item: item to upload as instance of isolate_storage.Item class. |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 681 | push_state: push state returned by storage_api.contains(). It contains |
| 682 | storage specific information describing how to upload the item (for |
| 683 | example in case of cloud storage, it is signed upload URLs). |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 684 | |
| 685 | Returns: |
| 686 | Pushed item (same object as |item|). |
| 687 | """ |
| 688 | channel = threading_utils.TaskChannel() |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 689 | with threading_utils.DeadlockDetector(DEADLOCK_TIMEOUT): |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 690 | self._async_push(channel, item, push_state) |
Marc-Antoine Ruel | 4494b6c | 2018-11-28 21:00:41 +0000 | [diff] [blame] | 691 | pushed = channel.next() |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 692 | assert pushed is item |
| 693 | return item |
| 694 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 695 | def async_fetch(self, channel, priority, digest, size, sink): |
| 696 | """Starts asynchronous fetch from the server in a parallel thread. |
| 697 | |
| 698 | Arguments: |
| 699 | channel: TaskChannel that receives back |digest| when download ends. |
| 700 | priority: thread pool task priority for the fetch. |
| 701 | digest: hex digest of an item to download. |
| 702 | size: expected size of the item (after decompression). |
| 703 | sink: function that will be called as sink(generator). |
| 704 | """ |
| 705 | def fetch(): |
| 706 | try: |
| 707 | # Prepare reading pipeline. |
Adrian Ludwin | b4ebc09 | 2017-09-13 07:46:24 -0400 | [diff] [blame] | 708 | stream = self._storage_api.fetch(digest, size, 0) |
Marc-Antoine Ruel | b851313 | 2018-11-20 19:48:53 +0000 | [diff] [blame] | 709 | if self.server_ref.is_with_compression: |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 710 | stream = zip_decompress(stream, isolated_format.DISK_FILE_CHUNK) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 711 | # Run |stream| through verifier that will assert its size. |
Marc-Antoine Ruel | b851313 | 2018-11-20 19:48:53 +0000 | [diff] [blame] | 712 | verifier = FetchStreamVerifier( |
| 713 | stream, self.server_ref.hash_algo, digest, size) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 714 | # Verified stream goes to |sink|. |
| 715 | sink(verifier.run()) |
| 716 | except Exception as err: |
Vadim Shtayura | 0ffc409 | 2013-11-20 17:49:52 -0800 | [diff] [blame] | 717 | logging.error('Failed to fetch %s: %s', digest, err) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 718 | raise |
| 719 | return digest |
| 720 | |
| 721 | # Don't bother with zip_thread_pool for decompression. Decompression is |
| 722 | # really fast and most probably IO bound anyway. |
| 723 | self.net_thread_pool.add_task_with_channel(channel, priority, fetch) |
| 724 | |
vadimsh@chromium.org | 35122be | 2013-09-19 02:48:00 +0000 | [diff] [blame] | 725 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 726 | class FetchQueue(object): |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 727 | """Fetches items from Storage and places them into ContentAddressedCache. |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 728 | |
| 729 | It manages multiple concurrent fetch operations. Acts as a bridge between |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 730 | Storage and ContentAddressedCache so that Storage and ContentAddressedCache |
| 731 | don't depend on each other at all. |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 732 | """ |
| 733 | |
| 734 | def __init__(self, storage, cache): |
| 735 | self.storage = storage |
| 736 | self.cache = cache |
| 737 | self._channel = threading_utils.TaskChannel() |
| 738 | self._pending = set() |
| 739 | self._accessed = set() |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 740 | self._fetched = set(cache) |
Marc-Antoine Ruel | 2d63154 | 2018-04-19 20:28:09 -0400 | [diff] [blame] | 741 | # Pending digests that the caller waits for, see wait_on()/wait(). |
| 742 | self._waiting_on = set() |
| 743 | # Already fetched digests the caller waits for which are not yet returned by |
| 744 | # wait(). |
| 745 | self._waiting_on_ready = set() |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 746 | |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 747 | def add( |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 748 | self, |
| 749 | digest, |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 750 | size=local_caching.UNKNOWN_FILE_SIZE, |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 751 | priority=threading_utils.PRIORITY_MED): |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 752 | """Starts asynchronous fetch of item |digest|.""" |
| 753 | # Fetching it now? |
| 754 | if digest in self._pending: |
| 755 | return |
| 756 | |
| 757 | # Mark this file as in use, verify_all_cached will later ensure it is still |
| 758 | # in cache. |
| 759 | self._accessed.add(digest) |
| 760 | |
| 761 | # Already fetched? Notify cache to update item's LRU position. |
| 762 | if digest in self._fetched: |
| 763 | # 'touch' returns True if item is in cache and not corrupted. |
| 764 | if self.cache.touch(digest, size): |
| 765 | return |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 766 | logging.error('%s is corrupted', digest) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 767 | self._fetched.remove(digest) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 768 | |
| 769 | # TODO(maruel): It should look at the free disk space, the current cache |
| 770 | # size and the size of the new item on every new item: |
| 771 | # - Trim the cache as more entries are listed when free disk space is low, |
| 772 | # otherwise if the amount of data downloaded during the run > free disk |
| 773 | # space, it'll crash. |
| 774 | # - Make sure there's enough free disk space to fit all dependencies of |
| 775 | # this run! If not, abort early. |
| 776 | |
| 777 | # Start fetching. |
| 778 | self._pending.add(digest) |
| 779 | self.storage.async_fetch( |
| 780 | self._channel, priority, digest, size, |
| 781 | functools.partial(self.cache.write, digest)) |
| 782 | |
Marc-Antoine Ruel | 2d63154 | 2018-04-19 20:28:09 -0400 | [diff] [blame] | 783 | def wait_on(self, digest): |
| 784 | """Updates digests to be waited on by 'wait'.""" |
| 785 | # Calculate once the already fetched items. These will be retrieved first. |
| 786 | if digest in self._fetched: |
| 787 | self._waiting_on_ready.add(digest) |
| 788 | else: |
| 789 | self._waiting_on.add(digest) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 790 | |
Marc-Antoine Ruel | 2d63154 | 2018-04-19 20:28:09 -0400 | [diff] [blame] | 791 | def wait(self): |
| 792 | """Waits until any of waited-on items is retrieved. |
| 793 | |
| 794 | Once this happens, it is remove from the waited-on set and returned. |
| 795 | |
| 796 | This function is called in two waves. The first wave it is done for HIGH |
| 797 | priority items, the isolated files themselves. The second wave it is called |
| 798 | for all the files. |
| 799 | |
| 800 | If the waited-on set is empty, raises RuntimeError. |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 801 | """ |
| 802 | # Flush any already fetched items. |
Marc-Antoine Ruel | 2d63154 | 2018-04-19 20:28:09 -0400 | [diff] [blame] | 803 | if self._waiting_on_ready: |
| 804 | return self._waiting_on_ready.pop() |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 805 | |
Marc-Antoine Ruel | 2d63154 | 2018-04-19 20:28:09 -0400 | [diff] [blame] | 806 | assert self._waiting_on, 'Needs items to wait on' |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 807 | |
Marc-Antoine Ruel | 2d63154 | 2018-04-19 20:28:09 -0400 | [diff] [blame] | 808 | # Wait for one waited-on item to be fetched. |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 809 | while self._pending: |
Marc-Antoine Ruel | 4494b6c | 2018-11-28 21:00:41 +0000 | [diff] [blame] | 810 | digest = self._channel.next() |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 811 | self._pending.remove(digest) |
| 812 | self._fetched.add(digest) |
Marc-Antoine Ruel | 2d63154 | 2018-04-19 20:28:09 -0400 | [diff] [blame] | 813 | if digest in self._waiting_on: |
| 814 | self._waiting_on.remove(digest) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 815 | return digest |
| 816 | |
| 817 | # Should never reach this point due to assert above. |
| 818 | raise RuntimeError('Impossible state') |
| 819 | |
Marc-Antoine Ruel | 2d63154 | 2018-04-19 20:28:09 -0400 | [diff] [blame] | 820 | @property |
| 821 | def wait_queue_empty(self): |
| 822 | """Returns True if there is no digest left for wait() to return.""" |
| 823 | return not self._waiting_on and not self._waiting_on_ready |
| 824 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 825 | def inject_local_file(self, path, algo): |
| 826 | """Adds local file to the cache as if it was fetched from storage.""" |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 827 | with fs.open(path, 'rb') as f: |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 828 | data = f.read() |
| 829 | digest = algo(data).hexdigest() |
| 830 | self.cache.write(digest, [data]) |
| 831 | self._fetched.add(digest) |
| 832 | return digest |
| 833 | |
| 834 | @property |
| 835 | def pending_count(self): |
| 836 | """Returns number of items to be fetched.""" |
| 837 | return len(self._pending) |
| 838 | |
| 839 | def verify_all_cached(self): |
| 840 | """True if all accessed items are in cache.""" |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 841 | # Not thread safe, but called after all work is done. |
| 842 | return self._accessed.issubset(self.cache) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 843 | |
| 844 | |
| 845 | class FetchStreamVerifier(object): |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 846 | """Verifies that fetched file is valid before passing it to the |
| 847 | ContentAddressedCache. |
| 848 | """ |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 849 | |
Adrian Ludwin | 6d2a834 | 2017-08-15 19:56:54 -0400 | [diff] [blame] | 850 | def __init__(self, stream, hasher, expected_digest, expected_size): |
| 851 | """Initializes the verifier. |
| 852 | |
| 853 | Arguments: |
| 854 | * stream: an iterable yielding chunks of content |
| 855 | * hasher: an object from hashlib that supports update() and hexdigest() |
| 856 | (eg, hashlib.sha1). |
| 857 | * expected_digest: if the entire stream is piped through hasher and then |
| 858 | summarized via hexdigest(), this should be the result. That is, it |
| 859 | should be a hex string like 'abc123'. |
| 860 | * expected_size: either the expected size of the stream, or |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 861 | local_caching.UNKNOWN_FILE_SIZE. |
Adrian Ludwin | 6d2a834 | 2017-08-15 19:56:54 -0400 | [diff] [blame] | 862 | """ |
Marc-Antoine Ruel | df4976d | 2015-04-15 19:56:21 -0400 | [diff] [blame] | 863 | assert stream is not None |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 864 | self.stream = stream |
Adrian Ludwin | 6d2a834 | 2017-08-15 19:56:54 -0400 | [diff] [blame] | 865 | self.expected_digest = expected_digest |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 866 | self.expected_size = expected_size |
| 867 | self.current_size = 0 |
Adrian Ludwin | 6d2a834 | 2017-08-15 19:56:54 -0400 | [diff] [blame] | 868 | self.rolling_hash = hasher() |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 869 | |
| 870 | def run(self): |
| 871 | """Generator that yields same items as |stream|. |
| 872 | |
| 873 | Verifies |stream| is complete before yielding a last chunk to consumer. |
| 874 | |
| 875 | Also wraps IOError produced by consumer into MappingError exceptions since |
| 876 | otherwise Storage will retry fetch on unrelated local cache errors. |
| 877 | """ |
| 878 | # Read one chunk ahead, keep it in |stored|. |
| 879 | # That way a complete stream can be verified before pushing last chunk |
| 880 | # to consumer. |
| 881 | stored = None |
| 882 | for chunk in self.stream: |
| 883 | assert chunk is not None |
| 884 | if stored is not None: |
| 885 | self._inspect_chunk(stored, is_last=False) |
| 886 | try: |
| 887 | yield stored |
| 888 | except IOError as exc: |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 889 | raise isolated_format.MappingError( |
| 890 | 'Failed to store an item in cache: %s' % exc) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 891 | stored = chunk |
| 892 | if stored is not None: |
| 893 | self._inspect_chunk(stored, is_last=True) |
| 894 | try: |
| 895 | yield stored |
| 896 | except IOError as exc: |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 897 | raise isolated_format.MappingError( |
| 898 | 'Failed to store an item in cache: %s' % exc) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 899 | |
| 900 | def _inspect_chunk(self, chunk, is_last): |
| 901 | """Called for each fetched chunk before passing it to consumer.""" |
| 902 | self.current_size += len(chunk) |
Adrian Ludwin | 6d2a834 | 2017-08-15 19:56:54 -0400 | [diff] [blame] | 903 | self.rolling_hash.update(chunk) |
| 904 | if not is_last: |
| 905 | return |
| 906 | |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 907 | if ((self.expected_size != local_caching.UNKNOWN_FILE_SIZE) and |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 908 | (self.expected_size != self.current_size)): |
Adrian Ludwin | 6d2a834 | 2017-08-15 19:56:54 -0400 | [diff] [blame] | 909 | msg = 'Incorrect file size: want %d, got %d' % ( |
| 910 | self.expected_size, self.current_size) |
Adrian Ludwin | 6d2a834 | 2017-08-15 19:56:54 -0400 | [diff] [blame] | 911 | raise IOError(msg) |
| 912 | |
| 913 | actual_digest = self.rolling_hash.hexdigest() |
| 914 | if self.expected_digest != actual_digest: |
| 915 | msg = 'Incorrect digest: want %s, got %s' % ( |
| 916 | self.expected_digest, actual_digest) |
Adrian Ludwin | 21920d5 | 2017-08-22 09:34:19 -0400 | [diff] [blame] | 917 | raise IOError(msg) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 918 | |
| 919 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 920 | class IsolatedBundle(object): |
| 921 | """Fetched and parsed .isolated file with all dependencies.""" |
| 922 | |
Takuto Ikuta | 1e6072c | 2018-11-06 20:42:43 +0000 | [diff] [blame] | 923 | def __init__(self, filter_cb): |
| 924 | """ |
| 925 | filter_cb: callback function to filter downloaded content. |
| 926 | When filter_cb is not None, Isolated file is downloaded iff |
| 927 | filter_cb(filepath) returns True. |
| 928 | """ |
| 929 | |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 930 | self.command = [] |
| 931 | self.files = {} |
| 932 | self.read_only = None |
| 933 | self.relative_cwd = None |
| 934 | # The main .isolated file, a IsolatedFile instance. |
| 935 | self.root = None |
| 936 | |
Takuto Ikuta | 1e6072c | 2018-11-06 20:42:43 +0000 | [diff] [blame] | 937 | self._filter_cb = filter_cb |
| 938 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 939 | def fetch(self, fetch_queue, root_isolated_hash, algo): |
| 940 | """Fetches the .isolated and all the included .isolated. |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 941 | |
| 942 | It enables support for "included" .isolated files. They are processed in |
| 943 | strict order but fetched asynchronously from the cache. This is important so |
| 944 | that a file in an included .isolated file that is overridden by an embedding |
| 945 | .isolated file is not fetched needlessly. The includes are fetched in one |
| 946 | pass and the files are fetched as soon as all the ones on the left-side |
| 947 | of the tree were fetched. |
| 948 | |
| 949 | The prioritization is very important here for nested .isolated files. |
| 950 | 'includes' have the highest priority and the algorithm is optimized for both |
| 951 | deep and wide trees. A deep one is a long link of .isolated files referenced |
| 952 | one at a time by one item in 'includes'. A wide one has a large number of |
| 953 | 'includes' in a single .isolated file. 'left' is defined as an included |
| 954 | .isolated file earlier in the 'includes' list. So the order of the elements |
| 955 | in 'includes' is important. |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 956 | |
| 957 | As a side effect this method starts asynchronous fetch of all data files |
| 958 | by adding them to |fetch_queue|. It doesn't wait for data files to finish |
| 959 | fetching though. |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 960 | """ |
| 961 | self.root = isolated_format.IsolatedFile(root_isolated_hash, algo) |
| 962 | |
| 963 | # Isolated files being retrieved now: hash -> IsolatedFile instance. |
| 964 | pending = {} |
| 965 | # Set of hashes of already retrieved items to refuse recursive includes. |
| 966 | seen = set() |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 967 | # Set of IsolatedFile's whose data files have already being fetched. |
| 968 | processed = set() |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 969 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 970 | def retrieve_async(isolated_file): |
Marc-Antoine Ruel | 2d63154 | 2018-04-19 20:28:09 -0400 | [diff] [blame] | 971 | """Retrieves an isolated file included by the root bundle.""" |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 972 | h = isolated_file.obj_hash |
| 973 | if h in seen: |
| 974 | raise isolated_format.IsolatedError( |
| 975 | 'IsolatedFile %s is retrieved recursively' % h) |
| 976 | assert h not in pending |
| 977 | seen.add(h) |
| 978 | pending[h] = isolated_file |
Marc-Antoine Ruel | 2d63154 | 2018-04-19 20:28:09 -0400 | [diff] [blame] | 979 | # This isolated item is being added dynamically, notify FetchQueue. |
| 980 | fetch_queue.wait_on(h) |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 981 | fetch_queue.add(h, priority=threading_utils.PRIORITY_HIGH) |
| 982 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 983 | # Start fetching root *.isolated file (single file, not the whole bundle). |
| 984 | retrieve_async(self.root) |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 985 | |
| 986 | while pending: |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 987 | # Wait until some *.isolated file is fetched, parse it. |
Marc-Antoine Ruel | 2d63154 | 2018-04-19 20:28:09 -0400 | [diff] [blame] | 988 | item_hash = fetch_queue.wait() |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 989 | item = pending.pop(item_hash) |
tansell | 9e04a8d | 2016-07-28 09:31:59 -0700 | [diff] [blame] | 990 | with fetch_queue.cache.getfileobj(item_hash) as f: |
| 991 | item.load(f.read()) |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 992 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 993 | # Start fetching included *.isolated files. |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 994 | for new_child in item.children: |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 995 | retrieve_async(new_child) |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 996 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 997 | # Always fetch *.isolated files in traversal order, waiting if necessary |
| 998 | # until next to-be-processed node loads. "Waiting" is done by yielding |
| 999 | # back to the outer loop, that waits until some *.isolated is loaded. |
| 1000 | for node in isolated_format.walk_includes(self.root): |
| 1001 | if node not in processed: |
| 1002 | # Not visited, and not yet loaded -> wait for it to load. |
| 1003 | if not node.is_loaded: |
| 1004 | break |
| 1005 | # Not visited and loaded -> process it and continue the traversal. |
| 1006 | self._start_fetching_files(node, fetch_queue) |
| 1007 | processed.add(node) |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1008 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1009 | # All *.isolated files should be processed by now and only them. |
| 1010 | all_isolateds = set(isolated_format.walk_includes(self.root)) |
| 1011 | assert all_isolateds == processed, (all_isolateds, processed) |
Marc-Antoine Ruel | 2d63154 | 2018-04-19 20:28:09 -0400 | [diff] [blame] | 1012 | assert fetch_queue.wait_queue_empty, 'FetchQueue should have been emptied' |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1013 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1014 | # Extract 'command' and other bundle properties. |
| 1015 | for node in isolated_format.walk_includes(self.root): |
| 1016 | self._update_self(node) |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1017 | self.relative_cwd = self.relative_cwd or '' |
| 1018 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1019 | def _start_fetching_files(self, isolated, fetch_queue): |
| 1020 | """Starts fetching files from |isolated| that are not yet being fetched. |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1021 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1022 | Modifies self.files. |
| 1023 | """ |
maruel | 10bea7b | 2016-12-07 05:03:49 -0800 | [diff] [blame] | 1024 | files = isolated.data.get('files', {}) |
| 1025 | logging.debug('fetch_files(%s, %d)', isolated.obj_hash, len(files)) |
| 1026 | for filepath, properties in files.iteritems(): |
Takuto Ikuta | 1e6072c | 2018-11-06 20:42:43 +0000 | [diff] [blame] | 1027 | if self._filter_cb and not self._filter_cb(filepath): |
| 1028 | continue |
| 1029 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1030 | # Root isolated has priority on the files being mapped. In particular, |
| 1031 | # overridden files must not be fetched. |
| 1032 | if filepath not in self.files: |
| 1033 | self.files[filepath] = properties |
tansell | 9e04a8d | 2016-07-28 09:31:59 -0700 | [diff] [blame] | 1034 | |
| 1035 | # Make sure if the isolated is read only, the mode doesn't have write |
| 1036 | # bits. |
| 1037 | if 'm' in properties and self.read_only: |
| 1038 | properties['m'] &= ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH) |
| 1039 | |
| 1040 | # Preemptively request hashed files. |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1041 | if 'h' in properties: |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1042 | fetch_queue.add( |
| 1043 | properties['h'], properties['s'], threading_utils.PRIORITY_MED) |
| 1044 | |
| 1045 | def _update_self(self, node): |
| 1046 | """Extracts bundle global parameters from loaded *.isolated file. |
| 1047 | |
| 1048 | Will be called with each loaded *.isolated file in order of traversal of |
| 1049 | isolated include graph (see isolated_format.walk_includes). |
| 1050 | """ |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1051 | # Grabs properties. |
| 1052 | if not self.command and node.data.get('command'): |
| 1053 | # Ensure paths are correctly separated on windows. |
| 1054 | self.command = node.data['command'] |
| 1055 | if self.command: |
| 1056 | self.command[0] = self.command[0].replace('/', os.path.sep) |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1057 | if self.read_only is None and node.data.get('read_only') is not None: |
| 1058 | self.read_only = node.data['read_only'] |
| 1059 | if (self.relative_cwd is None and |
| 1060 | node.data.get('relative_cwd') is not None): |
| 1061 | self.relative_cwd = node.data['relative_cwd'] |
| 1062 | |
| 1063 | |
Marc-Antoine Ruel | b851313 | 2018-11-20 19:48:53 +0000 | [diff] [blame] | 1064 | def get_storage(server_ref): |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1065 | """Returns Storage class that can upload and download from |namespace|. |
| 1066 | |
| 1067 | Arguments: |
Marc-Antoine Ruel | b851313 | 2018-11-20 19:48:53 +0000 | [diff] [blame] | 1068 | server_ref: isolate_storage.ServerRef instance. |
Vadim Shtayura | bcff74f | 2014-02-27 16:19:34 -0800 | [diff] [blame] | 1069 | |
| 1070 | Returns: |
| 1071 | Instance of Storage. |
| 1072 | """ |
Marc-Antoine Ruel | b851313 | 2018-11-20 19:48:53 +0000 | [diff] [blame] | 1073 | assert isinstance(server_ref, isolate_storage.ServerRef), repr(server_ref) |
| 1074 | return Storage(isolate_storage.get_storage_api(server_ref)) |
maruel@chromium.org | dedbf49 | 2013-09-12 20:42:11 +0000 | [diff] [blame] | 1075 | |
maruel@chromium.org | dedbf49 | 2013-09-12 20:42:11 +0000 | [diff] [blame] | 1076 | |
Takuto Ikuta | 1e6072c | 2018-11-06 20:42:43 +0000 | [diff] [blame] | 1077 | def fetch_isolated(isolated_hash, storage, cache, outdir, use_symlinks, |
| 1078 | filter_cb=None): |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1079 | """Aggressively downloads the .isolated file(s), then download all the files. |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1080 | |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1081 | Arguments: |
| 1082 | isolated_hash: hash of the root *.isolated file. |
| 1083 | storage: Storage class that communicates with isolate storage. |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 1084 | cache: ContentAddressedCache class that knows how to store and map files |
| 1085 | locally. |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1086 | outdir: Output directory to map file tree to. |
maruel | 4409e30 | 2016-07-19 14:25:51 -0700 | [diff] [blame] | 1087 | use_symlinks: Use symlinks instead of hardlinks when True. |
Takuto Ikuta | 1e6072c | 2018-11-06 20:42:43 +0000 | [diff] [blame] | 1088 | filter_cb: filter that works as whitelist for downloaded files. |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1089 | |
| 1090 | Returns: |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1091 | IsolatedBundle object that holds details about loaded *.isolated file. |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1092 | """ |
Marc-Antoine Ruel | 4e8cd18 | 2014-06-18 13:27:17 -0400 | [diff] [blame] | 1093 | logging.debug( |
maruel | 4409e30 | 2016-07-19 14:25:51 -0700 | [diff] [blame] | 1094 | 'fetch_isolated(%s, %s, %s, %s, %s)', |
| 1095 | isolated_hash, storage, cache, outdir, use_symlinks) |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 1096 | # Hash algorithm to use, defined by namespace |storage| is using. |
Marc-Antoine Ruel | b851313 | 2018-11-20 19:48:53 +0000 | [diff] [blame] | 1097 | algo = storage.server_ref.hash_algo |
Marc-Antoine Ruel | e79ddbf | 2018-06-13 18:33:07 +0000 | [diff] [blame] | 1098 | fetch_queue = FetchQueue(storage, cache) |
Takuto Ikuta | 1e6072c | 2018-11-06 20:42:43 +0000 | [diff] [blame] | 1099 | bundle = IsolatedBundle(filter_cb) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1100 | |
Marc-Antoine Ruel | e79ddbf | 2018-06-13 18:33:07 +0000 | [diff] [blame] | 1101 | with tools.Profiler('GetIsolateds'): |
| 1102 | # Optionally support local files by manually adding them to cache. |
| 1103 | if not isolated_format.is_valid_hash(isolated_hash, algo): |
| 1104 | logging.debug('%s is not a valid hash, assuming a file ' |
| 1105 | '(algo was %s, hash size was %d)', |
| 1106 | isolated_hash, algo(), algo().digest_size) |
| 1107 | path = unicode(os.path.abspath(isolated_hash)) |
| 1108 | try: |
| 1109 | isolated_hash = fetch_queue.inject_local_file(path, algo) |
| 1110 | except IOError as e: |
| 1111 | raise isolated_format.MappingError( |
| 1112 | '%s doesn\'t seem to be a valid file. Did you intent to pass a ' |
| 1113 | 'valid hash (error: %s)?' % (isolated_hash, e)) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1114 | |
Marc-Antoine Ruel | e79ddbf | 2018-06-13 18:33:07 +0000 | [diff] [blame] | 1115 | # Load all *.isolated and start loading rest of the files. |
| 1116 | bundle.fetch(fetch_queue, isolated_hash, algo) |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1117 | |
Marc-Antoine Ruel | e79ddbf | 2018-06-13 18:33:07 +0000 | [diff] [blame] | 1118 | with tools.Profiler('GetRest'): |
| 1119 | # Create file system hierarchy. |
| 1120 | file_path.ensure_tree(outdir) |
| 1121 | create_directories(outdir, bundle.files) |
| 1122 | create_symlinks(outdir, bundle.files.iteritems()) |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1123 | |
Marc-Antoine Ruel | e79ddbf | 2018-06-13 18:33:07 +0000 | [diff] [blame] | 1124 | # Ensure working directory exists. |
| 1125 | cwd = os.path.normpath(os.path.join(outdir, bundle.relative_cwd)) |
| 1126 | file_path.ensure_tree(cwd) |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1127 | |
Marc-Antoine Ruel | e79ddbf | 2018-06-13 18:33:07 +0000 | [diff] [blame] | 1128 | # Multimap: digest -> list of pairs (path, props). |
| 1129 | remaining = {} |
| 1130 | for filepath, props in bundle.files.iteritems(): |
| 1131 | if 'h' in props: |
| 1132 | remaining.setdefault(props['h'], []).append((filepath, props)) |
| 1133 | fetch_queue.wait_on(props['h']) |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1134 | |
Marc-Antoine Ruel | e79ddbf | 2018-06-13 18:33:07 +0000 | [diff] [blame] | 1135 | # Now block on the remaining files to be downloaded and mapped. |
| 1136 | logging.info('Retrieving remaining files (%d of them)...', |
| 1137 | fetch_queue.pending_count) |
| 1138 | last_update = time.time() |
| 1139 | with threading_utils.DeadlockDetector(DEADLOCK_TIMEOUT) as detector: |
| 1140 | while remaining: |
| 1141 | detector.ping() |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1142 | |
Marc-Antoine Ruel | e79ddbf | 2018-06-13 18:33:07 +0000 | [diff] [blame] | 1143 | # Wait for any item to finish fetching to cache. |
| 1144 | digest = fetch_queue.wait() |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1145 | |
Marc-Antoine Ruel | e79ddbf | 2018-06-13 18:33:07 +0000 | [diff] [blame] | 1146 | # Create the files in the destination using item in cache as the |
| 1147 | # source. |
| 1148 | for filepath, props in remaining.pop(digest): |
| 1149 | fullpath = os.path.join(outdir, filepath) |
tansell | 9e04a8d | 2016-07-28 09:31:59 -0700 | [diff] [blame] | 1150 | |
Marc-Antoine Ruel | e79ddbf | 2018-06-13 18:33:07 +0000 | [diff] [blame] | 1151 | with cache.getfileobj(digest) as srcfileobj: |
| 1152 | filetype = props.get('t', 'basic') |
tansell | e4288c3 | 2016-07-28 09:45:40 -0700 | [diff] [blame] | 1153 | |
Marc-Antoine Ruel | e79ddbf | 2018-06-13 18:33:07 +0000 | [diff] [blame] | 1154 | if filetype == 'basic': |
| 1155 | # Ignore all bits apart from the user. |
| 1156 | file_mode = (props.get('m') or 0500) & 0700 |
| 1157 | if bundle.read_only: |
| 1158 | # Enforce read-only if the root bundle does. |
| 1159 | file_mode &= 0500 |
| 1160 | putfile( |
| 1161 | srcfileobj, fullpath, file_mode, |
| 1162 | use_symlink=use_symlinks) |
tansell | e4288c3 | 2016-07-28 09:45:40 -0700 | [diff] [blame] | 1163 | |
Marc-Antoine Ruel | e79ddbf | 2018-06-13 18:33:07 +0000 | [diff] [blame] | 1164 | elif filetype == 'tar': |
| 1165 | basedir = os.path.dirname(fullpath) |
| 1166 | with tarfile.TarFile(fileobj=srcfileobj, encoding='utf-8') as t: |
| 1167 | for ti in t: |
| 1168 | if not ti.isfile(): |
| 1169 | logging.warning( |
| 1170 | 'Path(%r) is nonfile (%s), skipped', |
| 1171 | ti.name, ti.type) |
| 1172 | continue |
| 1173 | # Handle files created on Windows fetched on POSIX and the |
| 1174 | # reverse. |
| 1175 | other_sep = '/' if os.path.sep == '\\' else '\\' |
| 1176 | name = ti.name.replace(other_sep, os.path.sep) |
| 1177 | fp = os.path.normpath(os.path.join(basedir, name)) |
| 1178 | if not fp.startswith(basedir): |
| 1179 | logging.error( |
| 1180 | 'Path(%r) is outside root directory', |
| 1181 | fp) |
| 1182 | ifd = t.extractfile(ti) |
| 1183 | file_path.ensure_tree(os.path.dirname(fp)) |
| 1184 | file_mode = ti.mode & 0700 |
| 1185 | if bundle.read_only: |
| 1186 | # Enforce read-only if the root bundle does. |
| 1187 | file_mode &= 0500 |
| 1188 | putfile(ifd, fp, file_mode, ti.size) |
tansell | 26de79e | 2016-11-13 18:41:11 -0800 | [diff] [blame] | 1189 | |
Marc-Antoine Ruel | e79ddbf | 2018-06-13 18:33:07 +0000 | [diff] [blame] | 1190 | else: |
| 1191 | raise isolated_format.IsolatedError( |
| 1192 | 'Unknown file type %r', filetype) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1193 | |
Marc-Antoine Ruel | e79ddbf | 2018-06-13 18:33:07 +0000 | [diff] [blame] | 1194 | # Report progress. |
| 1195 | duration = time.time() - last_update |
| 1196 | if duration > DELAY_BETWEEN_UPDATES_IN_SECS: |
| 1197 | msg = '%d files remaining...' % len(remaining) |
| 1198 | sys.stdout.write(msg + '\n') |
| 1199 | sys.stdout.flush() |
| 1200 | logging.info(msg) |
| 1201 | last_update = time.time() |
| 1202 | assert fetch_queue.wait_queue_empty, 'FetchQueue should have been emptied' |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1203 | |
Marc-Antoine Ruel | e955837 | 2018-08-03 03:41:22 +0000 | [diff] [blame] | 1204 | # Save the cache right away to not loose the state of the new objects. |
| 1205 | cache.save() |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1206 | # Cache could evict some items we just tried to fetch, it's a fatal error. |
| 1207 | if not fetch_queue.verify_all_cached(): |
Marc-Antoine Ruel | dddf617 | 2018-01-23 14:25:43 -0500 | [diff] [blame] | 1208 | free_disk = file_path.get_free_space(cache.cache_dir) |
| 1209 | msg = ( |
| 1210 | 'Cache is too small to hold all requested files.\n' |
| 1211 | ' %s\n cache=%dbytes, %d items; %sb free_space') % ( |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 1212 | cache.policies, cache.total_size, len(cache), free_disk) |
Marc-Antoine Ruel | dddf617 | 2018-01-23 14:25:43 -0500 | [diff] [blame] | 1213 | raise isolated_format.MappingError(msg) |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 1214 | return bundle |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1215 | |
| 1216 | |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 1217 | def _directory_to_metadata(root, algo, blacklist): |
Marc-Antoine Ruel | cc802b0 | 2018-11-28 21:05:01 +0000 | [diff] [blame] | 1218 | """Yields every file and/or symlink found. |
| 1219 | |
| 1220 | Yields: |
| 1221 | tuple(FileItem, relpath, metadata) |
| 1222 | For a symlink, FileItem is None. |
| 1223 | """ |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1224 | root = file_path.get_native_path_case(root) |
Marc-Antoine Ruel | cc802b0 | 2018-11-28 21:05:01 +0000 | [diff] [blame] | 1225 | for relpath in isolated_format.expand_directory_and_symlink( |
| 1226 | root, |
| 1227 | u'.' + os.path.sep, |
| 1228 | blacklist, |
| 1229 | follow_symlinks=(sys.platform != 'win32')): |
| 1230 | # Immediately hash the file. We need the hash to construct the isolated |
| 1231 | # file. |
| 1232 | # TODO(maruel): This should be done lazily? |
| 1233 | meta = isolated_format.file_to_metadata( |
kjlubick | 80596f0 | 2017-04-28 08:13:19 -0700 | [diff] [blame] | 1234 | os.path.join(root, relpath), {}, 0, algo, False) |
Marc-Antoine Ruel | cc802b0 | 2018-11-28 21:05:01 +0000 | [diff] [blame] | 1235 | meta.pop('t') |
| 1236 | item = None |
| 1237 | if 'h' in meta: |
| 1238 | item = FileItem( |
| 1239 | path=os.path.join(root, relpath), |
| 1240 | digest=meta['h'], |
| 1241 | size=meta['s'], |
| 1242 | high_priority=relpath.endswith('.isolated')) |
| 1243 | yield item, relpath, meta |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1244 | |
| 1245 | |
Marc-Antoine Ruel | b69069b | 2018-11-28 20:50:40 +0000 | [diff] [blame] | 1246 | def _print_upload_stats(items, missing): |
| 1247 | """Prints upload stats.""" |
| 1248 | total = len(items) |
| 1249 | total_size = sum(f.size for f in items) |
| 1250 | logging.info( |
| 1251 | 'Total: %6d, %9.1fkiB', total, total_size / 1024.) |
| 1252 | cache_hit = set(items).difference(missing) |
| 1253 | cache_hit_size = sum(f.size for f in cache_hit) |
| 1254 | logging.info( |
| 1255 | 'cache hit: %6d, %9.1fkiB, %6.2f%% files, %6.2f%% size', |
| 1256 | len(cache_hit), |
| 1257 | cache_hit_size / 1024., |
| 1258 | len(cache_hit) * 100. / total, |
| 1259 | cache_hit_size * 100. / total_size if total_size else 0) |
| 1260 | cache_miss = missing |
| 1261 | cache_miss_size = sum(f.size for f in cache_miss) |
| 1262 | logging.info( |
| 1263 | 'cache miss: %6d, %9.1fkiB, %6.2f%% files, %6.2f%% size', |
| 1264 | len(cache_miss), |
| 1265 | cache_miss_size / 1024., |
| 1266 | len(cache_miss) * 100. / total, |
| 1267 | cache_miss_size * 100. / total_size if total_size else 0) |
| 1268 | |
| 1269 | |
Marc-Antoine Ruel | d0868ec | 2018-11-28 20:47:29 +0000 | [diff] [blame] | 1270 | def _enqueue_dir(dirpath, blacklist, tempdir, hash_algo, hash_algo_name): |
| 1271 | """Called by archive_files_to_storage for a directory. |
| 1272 | |
| 1273 | Create an .isolated file. |
Marc-Antoine Ruel | cc802b0 | 2018-11-28 21:05:01 +0000 | [diff] [blame] | 1274 | |
| 1275 | Yields: |
| 1276 | FileItem for every file found, plus one for the isolated file itself. |
Marc-Antoine Ruel | d0868ec | 2018-11-28 20:47:29 +0000 | [diff] [blame] | 1277 | """ |
Marc-Antoine Ruel | cc802b0 | 2018-11-28 21:05:01 +0000 | [diff] [blame] | 1278 | files = {} |
| 1279 | for item, relpath, meta in _directory_to_metadata( |
| 1280 | dirpath, hash_algo, blacklist): |
Marc-Antoine Ruel | 9cd5ef0 | 2018-11-29 23:47:34 +0000 | [diff] [blame^] | 1281 | # item is None for a symlink. |
Marc-Antoine Ruel | cc802b0 | 2018-11-28 21:05:01 +0000 | [diff] [blame] | 1282 | files[relpath] = meta |
Marc-Antoine Ruel | 9cd5ef0 | 2018-11-29 23:47:34 +0000 | [diff] [blame^] | 1283 | if item: |
Marc-Antoine Ruel | cc802b0 | 2018-11-28 21:05:01 +0000 | [diff] [blame] | 1284 | yield item |
| 1285 | |
| 1286 | data = { |
| 1287 | 'algo': hash_algo_name, |
| 1288 | 'files': files, |
| 1289 | 'version': isolated_format.ISOLATED_FILE_VERSION, |
| 1290 | } |
Marc-Antoine Ruel | d0868ec | 2018-11-28 20:47:29 +0000 | [diff] [blame] | 1291 | # TODO(maruel): Stop putting to disk. |
| 1292 | handle, isolated = tempfile.mkstemp(dir=tempdir, suffix=u'.isolated') |
| 1293 | os.close(handle) |
Marc-Antoine Ruel | d0868ec | 2018-11-28 20:47:29 +0000 | [diff] [blame] | 1294 | isolated_format.save_isolated(isolated, data) |
Marc-Antoine Ruel | cc802b0 | 2018-11-28 21:05:01 +0000 | [diff] [blame] | 1295 | yield FileItem( |
| 1296 | path=isolated, |
| 1297 | digest=isolated_format.hash_file(isolated, hash_algo), |
| 1298 | size=fs.stat(isolated).st_size, |
| 1299 | high_priority=True) |
Marc-Antoine Ruel | d0868ec | 2018-11-28 20:47:29 +0000 | [diff] [blame] | 1300 | |
| 1301 | |
Vadim Shtayura | e0ab190 | 2014-04-29 10:55:27 -0700 | [diff] [blame] | 1302 | def archive_files_to_storage(storage, files, blacklist): |
Marc-Antoine Ruel | d0868ec | 2018-11-28 20:47:29 +0000 | [diff] [blame] | 1303 | """Stores every entries into remote storage and returns stats. |
Marc-Antoine Ruel | 2283ad1 | 2014-02-09 11:14:57 -0500 | [diff] [blame] | 1304 | |
| 1305 | Arguments: |
| 1306 | storage: a Storage object that communicates with the remote object store. |
Marc-Antoine Ruel | d0868ec | 2018-11-28 20:47:29 +0000 | [diff] [blame] | 1307 | files: iterable of files to upload. If a directory is specified (with a |
| 1308 | trailing slash), a .isolated file is created and its hash is returned. |
| 1309 | Duplicates are skipped. |
Marc-Antoine Ruel | 2283ad1 | 2014-02-09 11:14:57 -0500 | [diff] [blame] | 1310 | blacklist: function that returns True if a file should be omitted. |
maruel | 064c0a3 | 2016-04-05 11:47:15 -0700 | [diff] [blame] | 1311 | |
| 1312 | Returns: |
Marc-Antoine Ruel | d0868ec | 2018-11-28 20:47:29 +0000 | [diff] [blame] | 1313 | tuple(OrderedDict(path: hash), list(FileItem cold), list(FileItem hot)). |
maruel | 064c0a3 | 2016-04-05 11:47:15 -0700 | [diff] [blame] | 1314 | 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] | 1315 | """ |
Marc-Antoine Ruel | d0868ec | 2018-11-28 20:47:29 +0000 | [diff] [blame] | 1316 | # Dict of path to hash. |
| 1317 | results = collections.OrderedDict() |
Marc-Antoine Ruel | cc802b0 | 2018-11-28 21:05:01 +0000 | [diff] [blame] | 1318 | hash_algo = storage.server_ref.hash_algo |
| 1319 | hash_algo_name = storage.server_ref.hash_algo_name |
Marc-Antoine Ruel | d0868ec | 2018-11-28 20:47:29 +0000 | [diff] [blame] | 1320 | # TODO(maruel): Stop needing a temporary directory. |
| 1321 | tempdir = tempfile.mkdtemp(prefix=u'isolateserver') |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1322 | try: |
Marc-Antoine Ruel | cc802b0 | 2018-11-28 21:05:01 +0000 | [diff] [blame] | 1323 | # Generator of FileItem to pass to upload_items() concurrent operation. |
| 1324 | channel = threading_utils.TaskChannel() |
| 1325 | uploaded_digests = set() |
| 1326 | def _upload_items(): |
| 1327 | results = storage.upload_items(channel) |
| 1328 | uploaded_digests.update(f.digest for f in results) |
| 1329 | t = threading.Thread(target=_upload_items) |
| 1330 | t.start() |
| 1331 | |
| 1332 | # Keep track locally of the items to determine cold and hot items. |
| 1333 | items_found = [] |
| 1334 | try: |
| 1335 | for f in files: |
| 1336 | assert isinstance(f, unicode), repr(f) |
| 1337 | if f in results: |
| 1338 | # Duplicate |
| 1339 | continue |
| 1340 | try: |
| 1341 | h = None |
| 1342 | filepath = os.path.abspath(f) |
| 1343 | if fs.isdir(filepath): |
| 1344 | # Uploading a whole directory. |
| 1345 | for item in _enqueue_dir( |
| 1346 | filepath, blacklist, tempdir, hash_algo, hash_algo_name): |
| 1347 | channel.send_result(item) |
| 1348 | items_found.append(item) |
| 1349 | # The very last item will be the isolated file. |
| 1350 | h = item.digest |
| 1351 | elif fs.isfile(filepath): |
| 1352 | h = isolated_format.hash_file(filepath, hash_algo) |
| 1353 | item = FileItem( |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1354 | path=filepath, |
| 1355 | digest=h, |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1356 | size=fs.stat(filepath).st_size, |
Marc-Antoine Ruel | cc802b0 | 2018-11-28 21:05:01 +0000 | [diff] [blame] | 1357 | high_priority=f.endswith('.isolated')) |
| 1358 | channel.send_result(item) |
| 1359 | items_found.append(item) |
| 1360 | else: |
| 1361 | raise Error('%s is neither a file or directory.' % f) |
| 1362 | results[f] = h |
| 1363 | except OSError: |
| 1364 | raise Error('Failed to process %s.' % f) |
| 1365 | finally: |
| 1366 | # Stops the generator, so _upload_items() can exit. |
| 1367 | channel.send_done() |
| 1368 | t.join() |
Marc-Antoine Ruel | b851313 | 2018-11-20 19:48:53 +0000 | [diff] [blame] | 1369 | |
Marc-Antoine Ruel | d0868ec | 2018-11-28 20:47:29 +0000 | [diff] [blame] | 1370 | cold = [] |
| 1371 | hot = [] |
Marc-Antoine Ruel | cc802b0 | 2018-11-28 21:05:01 +0000 | [diff] [blame] | 1372 | for i in items_found: |
| 1373 | # Note that multiple FileItem may have the same .digest. |
| 1374 | if i.digest in uploaded_digests: |
Marc-Antoine Ruel | d0868ec | 2018-11-28 20:47:29 +0000 | [diff] [blame] | 1375 | cold.append(i) |
| 1376 | else: |
| 1377 | hot.append(i) |
maruel | 064c0a3 | 2016-04-05 11:47:15 -0700 | [diff] [blame] | 1378 | return results, cold, hot |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1379 | finally: |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1380 | if tempdir and fs.isdir(tempdir): |
Marc-Antoine Ruel | e4ad07e | 2014-10-15 20:22:29 -0400 | [diff] [blame] | 1381 | file_path.rmtree(tempdir) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1382 | |
| 1383 | |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 1384 | @subcommand.usage('<file1..fileN> or - to read from stdin') |
| 1385 | def CMDarchive(parser, args): |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1386 | """Archives data to the server. |
| 1387 | |
| 1388 | If a directory is specified, a .isolated file is created the whole directory |
| 1389 | is uploaded. Then this .isolated file can be included in another one to run |
| 1390 | commands. |
| 1391 | |
| 1392 | The commands output each file that was processed with its content hash. For |
| 1393 | directories, the .isolated generated for the directory is listed as the |
| 1394 | directory entry itself. |
| 1395 | """ |
Marc-Antoine Ruel | f7d737d | 2014-12-10 15:36:29 -0500 | [diff] [blame] | 1396 | add_isolate_server_options(parser) |
Marc-Antoine Ruel | 1f8ba35 | 2014-11-04 15:55:03 -0500 | [diff] [blame] | 1397 | add_archive_options(parser) |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 1398 | options, files = parser.parse_args(args) |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 1399 | process_isolate_server_options(parser, options, True, True) |
Marc-Antoine Ruel | b851313 | 2018-11-20 19:48:53 +0000 | [diff] [blame] | 1400 | server_ref = isolate_storage.ServerRef( |
| 1401 | options.isolate_server, options.namespace) |
Marc-Antoine Ruel | d0868ec | 2018-11-28 20:47:29 +0000 | [diff] [blame] | 1402 | if files == ['-']: |
| 1403 | files = (l.rstrip('\n\r') for l in sys.stdin) |
| 1404 | if not files: |
| 1405 | parser.error('Nothing to upload') |
| 1406 | files = (f.decode('utf-8') for f in files) |
| 1407 | blacklist = tools.gen_blacklist(options.blacklist) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1408 | try: |
Marc-Antoine Ruel | d0868ec | 2018-11-28 20:47:29 +0000 | [diff] [blame] | 1409 | with get_storage(server_ref) as storage: |
| 1410 | results, _cold, _hot = archive_files_to_storage(storage, files, blacklist) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 1411 | except (Error, local_caching.NoMoreSpace) as e: |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1412 | parser.error(e.args[0]) |
Marc-Antoine Ruel | d0868ec | 2018-11-28 20:47:29 +0000 | [diff] [blame] | 1413 | print('\n'.join('%s %s' % (h, f) for f, h in results.iteritems())) |
Marc-Antoine Ruel | fcc3cd8 | 2013-11-19 16:31:38 -0500 | [diff] [blame] | 1414 | return 0 |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 1415 | |
| 1416 | |
| 1417 | def CMDdownload(parser, args): |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 1418 | """Download data from the server. |
| 1419 | |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1420 | It can either download individual files or a complete tree from a .isolated |
| 1421 | file. |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 1422 | """ |
Marc-Antoine Ruel | f7d737d | 2014-12-10 15:36:29 -0500 | [diff] [blame] | 1423 | add_isolate_server_options(parser) |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 1424 | parser.add_option( |
Marc-Antoine Ruel | 185ded4 | 2015-01-28 20:49:18 -0500 | [diff] [blame] | 1425 | '-s', '--isolated', metavar='HASH', |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1426 | help='hash of an isolated file, .isolated file content is discarded, use ' |
| 1427 | '--file if you need it') |
| 1428 | parser.add_option( |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 1429 | '-f', '--file', metavar='HASH DEST', default=[], action='append', nargs=2, |
| 1430 | help='hash and destination of a file, can be used multiple times') |
| 1431 | parser.add_option( |
Marc-Antoine Ruel | f90861c | 2015-03-24 20:54:49 -0400 | [diff] [blame] | 1432 | '-t', '--target', metavar='DIR', default='download', |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 1433 | help='destination directory') |
maruel | 4409e30 | 2016-07-19 14:25:51 -0700 | [diff] [blame] | 1434 | parser.add_option( |
| 1435 | '--use-symlinks', action='store_true', |
| 1436 | help='Use symlinks instead of hardlinks') |
Marc-Antoine Ruel | a57d7db | 2014-10-15 20:31:19 -0400 | [diff] [blame] | 1437 | add_cache_options(parser) |
maruel@chromium.org | b7e79a2 | 2013-09-13 01:24:56 +0000 | [diff] [blame] | 1438 | options, args = parser.parse_args(args) |
| 1439 | if args: |
| 1440 | parser.error('Unsupported arguments: %s' % args) |
Marc-Antoine Ruel | 5028ba2 | 2017-08-25 17:37:51 -0400 | [diff] [blame] | 1441 | if not file_path.enable_symlink(): |
| 1442 | logging.error('Symlink support is not enabled') |
Marc-Antoine Ruel | f7d737d | 2014-12-10 15:36:29 -0500 | [diff] [blame] | 1443 | |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 1444 | process_isolate_server_options(parser, options, True, True) |
maruel@chromium.org | 4f2ebe4 | 2013-09-19 13:09:08 +0000 | [diff] [blame] | 1445 | if bool(options.isolated) == bool(options.file): |
| 1446 | parser.error('Use one of --isolated or --file, and only one.') |
maruel | 4409e30 | 2016-07-19 14:25:51 -0700 | [diff] [blame] | 1447 | if not options.cache and options.use_symlinks: |
| 1448 | 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] | 1449 | |
John Abd-El-Malek | e3a8501 | 2018-05-29 20:10:44 -0700 | [diff] [blame] | 1450 | cache = process_cache_options(options, trim=True) |
maruel | 2e8d0f5 | 2016-07-16 07:51:29 -0700 | [diff] [blame] | 1451 | cache.cleanup() |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1452 | options.target = unicode(os.path.abspath(options.target)) |
Marc-Antoine Ruel | f90861c | 2015-03-24 20:54:49 -0400 | [diff] [blame] | 1453 | if options.isolated: |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 1454 | if (fs.isfile(options.target) or |
| 1455 | (fs.isdir(options.target) and fs.listdir(options.target))): |
Marc-Antoine Ruel | f90861c | 2015-03-24 20:54:49 -0400 | [diff] [blame] | 1456 | parser.error( |
| 1457 | '--target \'%s\' exists, please use another target' % options.target) |
Marc-Antoine Ruel | b851313 | 2018-11-20 19:48:53 +0000 | [diff] [blame] | 1458 | server_ref = isolate_storage.ServerRef( |
| 1459 | options.isolate_server, options.namespace) |
| 1460 | with get_storage(server_ref) as storage: |
Vadim Shtayura | 3172be5 | 2013-12-03 12:49:05 -0800 | [diff] [blame] | 1461 | # Fetching individual files. |
| 1462 | if options.file: |
Marc-Antoine Ruel | a57d7db | 2014-10-15 20:31:19 -0400 | [diff] [blame] | 1463 | # TODO(maruel): Enable cache in this case too. |
Vadim Shtayura | 3172be5 | 2013-12-03 12:49:05 -0800 | [diff] [blame] | 1464 | channel = threading_utils.TaskChannel() |
| 1465 | pending = {} |
| 1466 | for digest, dest in options.file: |
Marc-Antoine Ruel | cf51ea9 | 2017-10-24 17:28:43 -0700 | [diff] [blame] | 1467 | dest = unicode(dest) |
Vadim Shtayura | 3172be5 | 2013-12-03 12:49:05 -0800 | [diff] [blame] | 1468 | pending[digest] = dest |
| 1469 | storage.async_fetch( |
| 1470 | channel, |
Vadim Shtayura | 3148e07 | 2014-09-02 18:51:52 -0700 | [diff] [blame] | 1471 | threading_utils.PRIORITY_MED, |
Vadim Shtayura | 3172be5 | 2013-12-03 12:49:05 -0800 | [diff] [blame] | 1472 | digest, |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 1473 | local_caching.UNKNOWN_FILE_SIZE, |
| 1474 | functools.partial( |
| 1475 | local_caching.file_write, os.path.join(options.target, dest))) |
Vadim Shtayura | 3172be5 | 2013-12-03 12:49:05 -0800 | [diff] [blame] | 1476 | while pending: |
Marc-Antoine Ruel | 4494b6c | 2018-11-28 21:00:41 +0000 | [diff] [blame] | 1477 | fetched = channel.next() |
Vadim Shtayura | 3172be5 | 2013-12-03 12:49:05 -0800 | [diff] [blame] | 1478 | dest = pending.pop(fetched) |
| 1479 | logging.info('%s: %s', fetched, dest) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1480 | |
Vadim Shtayura | 3172be5 | 2013-12-03 12:49:05 -0800 | [diff] [blame] | 1481 | # Fetching whole isolated tree. |
| 1482 | if options.isolated: |
Marc-Antoine Ruel | e79ddbf | 2018-06-13 18:33:07 +0000 | [diff] [blame] | 1483 | bundle = fetch_isolated( |
| 1484 | isolated_hash=options.isolated, |
| 1485 | storage=storage, |
| 1486 | cache=cache, |
| 1487 | outdir=options.target, |
| 1488 | use_symlinks=options.use_symlinks) |
| 1489 | cache.trim() |
Marc-Antoine Ruel | a57d7db | 2014-10-15 20:31:19 -0400 | [diff] [blame] | 1490 | if bundle.command: |
| 1491 | rel = os.path.join(options.target, bundle.relative_cwd) |
| 1492 | print('To run this test please run from the directory %s:' % |
| 1493 | os.path.join(options.target, rel)) |
| 1494 | print(' ' + ' '.join(bundle.command)) |
vadimsh@chromium.org | 7b5dae3 | 2013-10-03 16:59:59 +0000 | [diff] [blame] | 1495 | |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 1496 | return 0 |
| 1497 | |
| 1498 | |
Marc-Antoine Ruel | 1f8ba35 | 2014-11-04 15:55:03 -0500 | [diff] [blame] | 1499 | def add_archive_options(parser): |
| 1500 | parser.add_option( |
| 1501 | '--blacklist', |
| 1502 | action='append', default=list(DEFAULT_BLACKLIST), |
| 1503 | help='List of regexp to use as blacklist filter when uploading ' |
| 1504 | 'directories') |
| 1505 | |
| 1506 | |
Marc-Antoine Ruel | f7d737d | 2014-12-10 15:36:29 -0500 | [diff] [blame] | 1507 | def add_isolate_server_options(parser): |
| 1508 | """Adds --isolate-server and --namespace options to parser.""" |
Marc-Antoine Ruel | 1687b5e | 2014-02-06 17:47:53 -0500 | [diff] [blame] | 1509 | parser.add_option( |
| 1510 | '-I', '--isolate-server', |
| 1511 | metavar='URL', default=os.environ.get('ISOLATE_SERVER', ''), |
Marc-Antoine Ruel | 8806e62 | 2014-02-12 14:15:53 -0500 | [diff] [blame] | 1512 | help='URL of the Isolate Server to use. Defaults to the environment ' |
| 1513 | 'variable ISOLATE_SERVER if set. No need to specify https://, this ' |
| 1514 | 'is assumed.') |
Marc-Antoine Ruel | 1687b5e | 2014-02-06 17:47:53 -0500 | [diff] [blame] | 1515 | parser.add_option( |
aludwin | d7b7b7e | 2017-06-29 16:38:50 -0700 | [diff] [blame] | 1516 | '--grpc-proxy', help='gRPC proxy by which to communicate to Isolate') |
aludwin | 8117830 | 2016-11-30 17:18:49 -0800 | [diff] [blame] | 1517 | parser.add_option( |
Marc-Antoine Ruel | 1687b5e | 2014-02-06 17:47:53 -0500 | [diff] [blame] | 1518 | '--namespace', default='default-gzip', |
| 1519 | help='The namespace to use on the Isolate Server, default: %default') |
| 1520 | |
| 1521 | |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 1522 | def process_isolate_server_options( |
| 1523 | parser, options, set_exception_handler, required): |
| 1524 | """Processes the --isolate-server option. |
Marc-Antoine Ruel | f7d737d | 2014-12-10 15:36:29 -0500 | [diff] [blame] | 1525 | |
| 1526 | Returns the identity as determined by the server. |
Marc-Antoine Ruel | 1687b5e | 2014-02-06 17:47:53 -0500 | [diff] [blame] | 1527 | """ |
| 1528 | if not options.isolate_server: |
nodir | 55be77b | 2016-05-03 09:39:57 -0700 | [diff] [blame] | 1529 | if required: |
| 1530 | parser.error('--isolate-server is required.') |
| 1531 | return |
| 1532 | |
aludwin | d7b7b7e | 2017-06-29 16:38:50 -0700 | [diff] [blame] | 1533 | if options.grpc_proxy: |
| 1534 | isolate_storage.set_grpc_proxy(options.grpc_proxy) |
aludwin | 8117830 | 2016-11-30 17:18:49 -0800 | [diff] [blame] | 1535 | else: |
| 1536 | try: |
| 1537 | options.isolate_server = net.fix_url(options.isolate_server) |
| 1538 | except ValueError as e: |
| 1539 | parser.error('--isolate-server %s' % e) |
Marc-Antoine Ruel | e290ada | 2014-12-10 19:48:49 -0500 | [diff] [blame] | 1540 | if set_exception_handler: |
| 1541 | on_error.report_on_exception_exit(options.isolate_server) |
Marc-Antoine Ruel | f7d737d | 2014-12-10 15:36:29 -0500 | [diff] [blame] | 1542 | try: |
| 1543 | return auth.ensure_logged_in(options.isolate_server) |
| 1544 | except ValueError as e: |
| 1545 | parser.error(str(e)) |
Marc-Antoine Ruel | 8806e62 | 2014-02-12 14:15:53 -0500 | [diff] [blame] | 1546 | |
Marc-Antoine Ruel | 1687b5e | 2014-02-06 17:47:53 -0500 | [diff] [blame] | 1547 | |
Marc-Antoine Ruel | a57d7db | 2014-10-15 20:31:19 -0400 | [diff] [blame] | 1548 | def add_cache_options(parser): |
| 1549 | cache_group = optparse.OptionGroup(parser, 'Cache management') |
| 1550 | cache_group.add_option( |
Marc-Antoine Ruel | 5aeb3bb | 2018-06-16 13:11:02 +0000 | [diff] [blame] | 1551 | '--cache', metavar='DIR', default='cache', |
Marc-Antoine Ruel | a57d7db | 2014-10-15 20:31:19 -0400 | [diff] [blame] | 1552 | help='Directory to keep a local cache of the files. Accelerates download ' |
| 1553 | 'by reusing already downloaded files. Default=%default') |
| 1554 | cache_group.add_option( |
| 1555 | '--max-cache-size', |
| 1556 | type='int', |
| 1557 | metavar='NNN', |
maruel | 7158610 | 2016-01-29 11:44:09 -0800 | [diff] [blame] | 1558 | default=50*1024*1024*1024, |
Marc-Antoine Ruel | a57d7db | 2014-10-15 20:31:19 -0400 | [diff] [blame] | 1559 | help='Trim if the cache gets larger than this value, default=%default') |
| 1560 | cache_group.add_option( |
| 1561 | '--min-free-space', |
| 1562 | type='int', |
| 1563 | metavar='NNN', |
| 1564 | default=2*1024*1024*1024, |
| 1565 | help='Trim if disk free space becomes lower than this value, ' |
| 1566 | 'default=%default') |
| 1567 | cache_group.add_option( |
| 1568 | '--max-items', |
| 1569 | type='int', |
| 1570 | metavar='NNN', |
| 1571 | default=100000, |
| 1572 | help='Trim if more than this number of items are in the cache ' |
| 1573 | 'default=%default') |
| 1574 | parser.add_option_group(cache_group) |
| 1575 | |
| 1576 | |
John Abd-El-Malek | e3a8501 | 2018-05-29 20:10:44 -0700 | [diff] [blame] | 1577 | def process_cache_options(options, trim, **kwargs): |
Marc-Antoine Ruel | a57d7db | 2014-10-15 20:31:19 -0400 | [diff] [blame] | 1578 | if options.cache: |
Marc-Antoine Ruel | 34f5f28 | 2018-05-16 16:04:31 -0400 | [diff] [blame] | 1579 | policies = local_caching.CachePolicies( |
| 1580 | options.max_cache_size, |
| 1581 | options.min_free_space, |
| 1582 | options.max_items, |
| 1583 | # 3 weeks. |
| 1584 | max_age_secs=21*24*60*60) |
Marc-Antoine Ruel | a57d7db | 2014-10-15 20:31:19 -0400 | [diff] [blame] | 1585 | |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 1586 | # |options.cache| path may not exist until DiskContentAddressedCache() |
| 1587 | # instance is created. |
Marc-Antoine Ruel | b851313 | 2018-11-20 19:48:53 +0000 | [diff] [blame] | 1588 | server_ref = isolate_storage.ServerRef( |
| 1589 | options.isolate_server, options.namespace) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 1590 | return local_caching.DiskContentAddressedCache( |
Marc-Antoine Ruel | 3c979cb | 2015-03-11 13:43:28 -0400 | [diff] [blame] | 1591 | unicode(os.path.abspath(options.cache)), |
Marc-Antoine Ruel | a57d7db | 2014-10-15 20:31:19 -0400 | [diff] [blame] | 1592 | policies, |
Marc-Antoine Ruel | b851313 | 2018-11-20 19:48:53 +0000 | [diff] [blame] | 1593 | server_ref.hash_algo(), # pylint: disable=not-callable |
John Abd-El-Malek | e3a8501 | 2018-05-29 20:10:44 -0700 | [diff] [blame] | 1594 | trim, |
maruel | e6fc938 | 2017-05-04 09:03:48 -0700 | [diff] [blame] | 1595 | **kwargs) |
Marc-Antoine Ruel | a57d7db | 2014-10-15 20:31:19 -0400 | [diff] [blame] | 1596 | else: |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 1597 | return local_caching.MemoryContentAddressedCache() |
Marc-Antoine Ruel | a57d7db | 2014-10-15 20:31:19 -0400 | [diff] [blame] | 1598 | |
| 1599 | |
Marc-Antoine Ruel | f74cffe | 2015-07-15 15:21:34 -0400 | [diff] [blame] | 1600 | class OptionParserIsolateServer(logging_utils.OptionParserWithLogging): |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 1601 | def __init__(self, **kwargs): |
Marc-Antoine Ruel | f74cffe | 2015-07-15 15:21:34 -0400 | [diff] [blame] | 1602 | logging_utils.OptionParserWithLogging.__init__( |
Marc-Antoine Ruel | ac54cb4 | 2013-11-18 14:05:35 -0500 | [diff] [blame] | 1603 | self, |
| 1604 | version=__version__, |
| 1605 | prog=os.path.basename(sys.modules[__name__].__file__), |
| 1606 | **kwargs) |
Vadim Shtayura | e34e13a | 2014-02-02 11:23:26 -0800 | [diff] [blame] | 1607 | auth.add_auth_options(self) |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 1608 | |
| 1609 | def parse_args(self, *args, **kwargs): |
Marc-Antoine Ruel | f74cffe | 2015-07-15 15:21:34 -0400 | [diff] [blame] | 1610 | options, args = logging_utils.OptionParserWithLogging.parse_args( |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 1611 | self, *args, **kwargs) |
Vadim Shtayura | 5d1efce | 2014-02-04 10:55:43 -0800 | [diff] [blame] | 1612 | auth.process_auth_options(self, options) |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 1613 | return options, args |
| 1614 | |
| 1615 | |
| 1616 | def main(args): |
| 1617 | dispatcher = subcommand.CommandDispatcher(__name__) |
Marc-Antoine Ruel | cfb6085 | 2014-07-02 15:22:00 -0400 | [diff] [blame] | 1618 | return dispatcher.execute(OptionParserIsolateServer(), args) |
maruel@chromium.org | c6f9006 | 2012-11-07 18:32:22 +0000 | [diff] [blame] | 1619 | |
| 1620 | |
| 1621 | if __name__ == '__main__': |
maruel | 8e4e40c | 2016-05-30 06:21:07 -0700 | [diff] [blame] | 1622 | subprocess42.inhibit_os_error_reporting() |
maruel@chromium.org | fb78d43 | 2013-08-28 21:22:40 +0000 | [diff] [blame] | 1623 | fix_encoding.fix_encoding() |
| 1624 | tools.disable_buffering() |
| 1625 | colorama.init() |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 1626 | sys.exit(main(sys.argv[1:])) |