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