blob: 99cd11b3d8b423d3f369ad796179987761ea4d3d [file] [log] [blame]
maruel@chromium.orgc6f90062012-11-07 18:32:22 +00001#!/usr/bin/env python
Marc-Antoine Ruel8add1242013-11-05 17:28:27 -05002# Copyright 2013 The Swarming Authors. All rights reserved.
Marc-Antoine Ruele98b1122013-11-05 20:27:57 -05003# Use of this source code is governed under the Apache License, Version 2.0 that
4# can be found in the LICENSE file.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +00005
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05006"""Archives a set of files or directories to a server."""
maruel@chromium.orgc6f90062012-11-07 18:32:22 +00007
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -05008__version__ = '0.3.2'
maruel@chromium.orgfb78d432013-08-28 21:22:40 +00009
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +000010import functools
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000011import hashlib
maruel@chromium.org41601642013-09-18 19:40:46 +000012import json
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000013import logging
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000014import os
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +000015import re
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -050016import shutil
17import stat
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000018import sys
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -050019import tempfile
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +000020import threading
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000021import time
maruel@chromium.orge82112e2013-04-24 14:41:55 +000022import urllib
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -050023import urlparse
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +000024import zlib
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000025
maruel@chromium.orgfb78d432013-08-28 21:22:40 +000026from third_party import colorama
27from third_party.depot_tools import fix_encoding
28from third_party.depot_tools import subcommand
29
Marc-Antoine Ruel37989932013-11-19 16:28:08 -050030from utils import file_path
vadimsh@chromium.org6b706212013-08-28 15:03:46 +000031from utils import net
vadimsh@chromium.orgb074b162013-08-22 17:55:46 +000032from utils import threading_utils
vadimsh@chromium.orga4326472013-08-24 02:05:41 +000033from utils import tools
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000034
Vadim Shtayurae34e13a2014-02-02 11:23:26 -080035import auth
36
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000037
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +000038# Version of isolate protocol passed to the server in /handshake request.
39ISOLATE_PROTOCOL_VERSION = '1.0'
Marc-Antoine Ruel1c1edd62013-12-06 09:13:13 -050040# Version stored and expected in .isolated files.
Marc-Antoine Ruel05199462014-03-13 15:40:48 -040041ISOLATED_FILE_VERSION = '1.4'
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000042
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +000043
44# The number of files to check the isolate server per /pre-upload query.
vadimsh@chromium.orgeea52422013-08-21 19:35:54 +000045# All files are sorted by likelihood of a change in the file content
46# (currently file size is used to estimate this: larger the file -> larger the
47# possibility it has changed). Then first ITEMS_PER_CONTAINS_QUERIES[0] files
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +000048# are taken and send to '/pre-upload', then next ITEMS_PER_CONTAINS_QUERIES[1],
vadimsh@chromium.orgeea52422013-08-21 19:35:54 +000049# and so on. Numbers here is a trade-off; the more per request, the lower the
50# effect of HTTP round trip latency and TCP-level chattiness. On the other hand,
51# larger values cause longer lookups, increasing the initial latency to start
52# uploading, which is especially an issue for large files. This value is
53# optimized for the "few thousands files to look up with minimal number of large
54# files missing" case.
55ITEMS_PER_CONTAINS_QUERIES = [20, 20, 50, 50, 50, 100]
csharp@chromium.org07fa7592013-01-11 18:19:30 +000056
maruel@chromium.org9958e4a2013-09-17 00:01:48 +000057
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +000058# A list of already compressed extension types that should not receive any
59# compression before being uploaded.
60ALREADY_COMPRESSED_TYPES = [
61 '7z', 'avi', 'cur', 'gif', 'h264', 'jar', 'jpeg', 'jpg', 'pdf', 'png',
62 'wav', 'zip'
63]
64
maruel@chromium.orgc6f90062012-11-07 18:32:22 +000065
maruel@chromium.orgdedbf492013-09-12 20:42:11 +000066# The file size to be used when we don't know the correct file size,
67# generally used for .isolated files.
68UNKNOWN_FILE_SIZE = None
69
70
maruel@chromium.org8750e4b2013-09-18 02:37:57 +000071# Chunk size to use when doing disk I/O.
72DISK_FILE_CHUNK = 1024 * 1024
73
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +000074# Chunk size to use when reading from network stream.
75NET_IO_FILE_CHUNK = 16 * 1024
76
maruel@chromium.org8750e4b2013-09-18 02:37:57 +000077
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +000078# Read timeout in seconds for downloads from isolate storage. If there's no
79# response from the server within this timeout whole download will be aborted.
80DOWNLOAD_READ_TIMEOUT = 60
81
maruel@chromium.org4f2ebe42013-09-19 13:09:08 +000082# Maximum expected delay (in seconds) between successive file fetches
83# in run_tha_test. If it takes longer than that, a deadlock might be happening
84# and all stack frames for all threads are dumped to log.
85DEADLOCK_TIMEOUT = 5 * 60
86
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +000087
maruel@chromium.org41601642013-09-18 19:40:46 +000088# The delay (in seconds) to wait between logging statements when retrieving
89# the required files. This is intended to let the user (or buildbot) know that
90# the program is still running.
91DELAY_BETWEEN_UPDATES_IN_SECS = 30
92
93
maruel@chromium.org385d73d2013-09-19 18:33:21 +000094# Sadly, hashlib uses 'sha1' instead of the standard 'sha-1' so explicitly
95# specify the names here.
96SUPPORTED_ALGOS = {
97 'md5': hashlib.md5,
98 'sha-1': hashlib.sha1,
99 'sha-512': hashlib.sha512,
100}
101
102
103# Used for serialization.
104SUPPORTED_ALGOS_REVERSE = dict((v, k) for k, v in SUPPORTED_ALGOS.iteritems())
105
106
Marc-Antoine Ruelac54cb42013-11-18 14:05:35 -0500107DEFAULT_BLACKLIST = (
108 # Temporary vim or python files.
109 r'^.+\.(?:pyc|swp)$',
110 # .git or .svn directory.
111 r'^(?:.+' + re.escape(os.path.sep) + r'|)\.(?:git|svn)$',
112)
113
114
115# Chromium-specific.
116DEFAULT_BLACKLIST += (
117 r'^.+\.(?:run_test_cases)$',
118 r'^(?:.+' + re.escape(os.path.sep) + r'|)testserver\.log$',
119)
120
121
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -0500122class Error(Exception):
123 """Generic runtime error."""
124 pass
125
126
maruel@chromium.orgdedbf492013-09-12 20:42:11 +0000127class ConfigError(ValueError):
128 """Generic failure to load a .isolated file."""
129 pass
130
131
132class MappingError(OSError):
133 """Failed to recreate the tree."""
134 pass
135
136
maruel@chromium.org7b844a62013-09-17 13:04:59 +0000137def is_valid_hash(value, algo):
138 """Returns if the value is a valid hash for the corresponding algorithm."""
139 size = 2 * algo().digest_size
140 return bool(re.match(r'^[a-fA-F0-9]{%d}$' % size, value))
141
142
143def hash_file(filepath, algo):
144 """Calculates the hash of a file without reading it all in memory at once.
145
146 |algo| should be one of hashlib hashing algorithm.
147 """
148 digest = algo()
maruel@chromium.org037758d2012-12-10 17:59:46 +0000149 with open(filepath, 'rb') as f:
150 while True:
maruel@chromium.org8750e4b2013-09-18 02:37:57 +0000151 chunk = f.read(DISK_FILE_CHUNK)
maruel@chromium.org037758d2012-12-10 17:59:46 +0000152 if not chunk:
153 break
154 digest.update(chunk)
155 return digest.hexdigest()
156
157
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000158def stream_read(stream, chunk_size):
159 """Reads chunks from |stream| and yields them."""
160 while True:
161 data = stream.read(chunk_size)
162 if not data:
163 break
164 yield data
165
166
Vadim Shtayuraf0cb97a2013-12-05 13:57:49 -0800167def file_read(filepath, chunk_size=DISK_FILE_CHUNK, offset=0):
168 """Yields file content in chunks of |chunk_size| starting from |offset|."""
maruel@chromium.org8750e4b2013-09-18 02:37:57 +0000169 with open(filepath, 'rb') as f:
Vadim Shtayuraf0cb97a2013-12-05 13:57:49 -0800170 if offset:
171 f.seek(offset)
maruel@chromium.org8750e4b2013-09-18 02:37:57 +0000172 while True:
vadimsh@chromium.org35122be2013-09-19 02:48:00 +0000173 data = f.read(chunk_size)
maruel@chromium.org8750e4b2013-09-18 02:37:57 +0000174 if not data:
175 break
176 yield data
177
178
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000179def file_write(filepath, content_generator):
180 """Writes file content as generated by content_generator.
181
maruel@chromium.org8750e4b2013-09-18 02:37:57 +0000182 Creates the intermediary directory as needed.
183
184 Returns the number of bytes written.
185
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000186 Meant to be mocked out in unit tests.
187 """
188 filedir = os.path.dirname(filepath)
189 if not os.path.isdir(filedir):
190 os.makedirs(filedir)
maruel@chromium.org8750e4b2013-09-18 02:37:57 +0000191 total = 0
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000192 with open(filepath, 'wb') as f:
193 for d in content_generator:
maruel@chromium.org8750e4b2013-09-18 02:37:57 +0000194 total += len(d)
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000195 f.write(d)
maruel@chromium.org8750e4b2013-09-18 02:37:57 +0000196 return total
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000197
198
vadimsh@chromium.org35122be2013-09-19 02:48:00 +0000199def zip_compress(content_generator, level=7):
200 """Reads chunks from |content_generator| and yields zip compressed chunks."""
201 compressor = zlib.compressobj(level)
202 for chunk in content_generator:
203 compressed = compressor.compress(chunk)
204 if compressed:
205 yield compressed
206 tail = compressor.flush(zlib.Z_FINISH)
207 if tail:
208 yield tail
209
210
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000211def zip_decompress(content_generator, chunk_size=DISK_FILE_CHUNK):
212 """Reads zipped data from |content_generator| and yields decompressed data.
213
214 Decompresses data in small chunks (no larger than |chunk_size|) so that
215 zip bomb file doesn't cause zlib to preallocate huge amount of memory.
216
217 Raises IOError if data is corrupted or incomplete.
218 """
219 decompressor = zlib.decompressobj()
220 compressed_size = 0
221 try:
222 for chunk in content_generator:
223 compressed_size += len(chunk)
224 data = decompressor.decompress(chunk, chunk_size)
225 if data:
226 yield data
227 while decompressor.unconsumed_tail:
228 data = decompressor.decompress(decompressor.unconsumed_tail, chunk_size)
229 if data:
230 yield data
231 tail = decompressor.flush()
232 if tail:
233 yield tail
234 except zlib.error as e:
235 raise IOError(
236 'Corrupted zip stream (read %d bytes) - %s' % (compressed_size, e))
237 # Ensure all data was read and decompressed.
238 if decompressor.unused_data or decompressor.unconsumed_tail:
239 raise IOError('Not all data was decompressed')
240
241
vadimsh@chromium.org35122be2013-09-19 02:48:00 +0000242def get_zip_compression_level(filename):
243 """Given a filename calculates the ideal zip compression level to use."""
244 file_ext = os.path.splitext(filename)[1].lower()
245 # TODO(csharp): Profile to find what compression level works best.
246 return 0 if file_ext in ALREADY_COMPRESSED_TYPES else 7
247
248
maruel@chromium.orgaf254852013-09-17 17:48:14 +0000249def create_directories(base_directory, files):
250 """Creates the directory structure needed by the given list of files."""
251 logging.debug('create_directories(%s, %d)', base_directory, len(files))
252 # Creates the tree of directories to create.
253 directories = set(os.path.dirname(f) for f in files)
254 for item in list(directories):
255 while item:
256 directories.add(item)
257 item = os.path.dirname(item)
258 for d in sorted(directories):
259 if d:
260 os.mkdir(os.path.join(base_directory, d))
261
262
Marc-Antoine Ruelccafe0e2013-11-08 16:15:36 -0500263def create_symlinks(base_directory, files):
264 """Creates any symlinks needed by the given set of files."""
maruel@chromium.orgaf254852013-09-17 17:48:14 +0000265 for filepath, properties in files:
266 if 'l' not in properties:
267 continue
268 if sys.platform == 'win32':
Marc-Antoine Ruelccafe0e2013-11-08 16:15:36 -0500269 # TODO(maruel): Create symlink via the win32 api.
maruel@chromium.orgaf254852013-09-17 17:48:14 +0000270 logging.warning('Ignoring symlink %s', filepath)
271 continue
272 outfile = os.path.join(base_directory, filepath)
Marc-Antoine Ruelccafe0e2013-11-08 16:15:36 -0500273 # os.symlink() doesn't exist on Windows.
maruel@chromium.orgaf254852013-09-17 17:48:14 +0000274 os.symlink(properties['l'], outfile) # pylint: disable=E1101
maruel@chromium.orgaf254852013-09-17 17:48:14 +0000275
276
maruel@chromium.orge45728d2013-09-16 23:23:22 +0000277def is_valid_file(filepath, size):
maruel@chromium.orgdedbf492013-09-12 20:42:11 +0000278 """Determines if the given files appears valid.
279
280 Currently it just checks the file's size.
281 """
282 if size == UNKNOWN_FILE_SIZE:
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +0000283 return os.path.isfile(filepath)
maruel@chromium.orgdedbf492013-09-12 20:42:11 +0000284 actual_size = os.stat(filepath).st_size
285 if size != actual_size:
286 logging.warning(
287 'Found invalid item %s; %d != %d',
288 os.path.basename(filepath), actual_size, size)
289 return False
290 return True
291
292
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +0000293class WorkerPool(threading_utils.AutoRetryThreadPool):
294 """Thread pool that automatically retries on IOError and runs a preconfigured
295 function.
296 """
297 # Initial and maximum number of worker threads.
298 INITIAL_WORKERS = 2
299 MAX_WORKERS = 16
300 RETRIES = 5
301
302 def __init__(self):
303 super(WorkerPool, self).__init__(
304 [IOError],
305 self.RETRIES,
306 self.INITIAL_WORKERS,
307 self.MAX_WORKERS,
308 0,
309 'remote')
maruel@chromium.orge45728d2013-09-16 23:23:22 +0000310
311
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000312class Item(object):
313 """An item to push to Storage.
314
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800315 Its digest and size may be provided in advance, if known. Otherwise they will
316 be derived from content(). If digest is provided, it MUST correspond to
317 hash algorithm used by Storage.
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000318
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800319 When used with Storage, Item starts its life in a main thread, travels
320 to 'contains' thread, then to 'push' thread and then finally back to
321 the main thread. It is never used concurrently from multiple threads.
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000322 """
323
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800324 def __init__(self, digest=None, size=None, high_priority=False):
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000325 self.digest = digest
326 self.size = size
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800327 self.high_priority = high_priority
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000328 self.compression_level = 6
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000329
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800330 def content(self):
331 """Iterable with content of this item as byte string (str) chunks."""
332 raise NotImplementedError()
333
334 def prepare(self, hash_algo):
335 """Ensures self.digest and self.size are set.
336
337 Uses content() as a source of data to calculate them. Does nothing if digest
338 and size is already known.
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000339
340 Arguments:
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800341 hash_algo: hash algorithm to use to calculate digest.
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000342 """
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800343 if self.digest is None or self.size is None:
344 digest = hash_algo()
345 total = 0
346 for chunk in self.content():
347 digest.update(chunk)
348 total += len(chunk)
349 self.digest = digest.hexdigest()
350 self.size = total
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000351
352
353class FileItem(Item):
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800354 """A file to push to Storage.
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000355
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800356 Its digest and size may be provided in advance, if known. Otherwise they will
357 be derived from the file content.
358 """
359
360 def __init__(self, path, digest=None, size=None, high_priority=False):
361 super(FileItem, self).__init__(
362 digest,
363 size if size is not None else os.stat(path).st_size,
364 high_priority)
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000365 self.path = path
366 self.compression_level = get_zip_compression_level(path)
367
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800368 def content(self):
369 return file_read(self.path)
maruel@chromium.orgc6f90062012-11-07 18:32:22 +0000370
371
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000372class BufferItem(Item):
373 """A byte buffer to push to Storage."""
374
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800375 def __init__(self, buf, high_priority=False):
376 super(BufferItem, self).__init__(None, len(buf), high_priority)
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000377 self.buffer = buf
378
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800379 def content(self):
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000380 return [self.buffer]
381
382
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000383class Storage(object):
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800384 """Efficiently downloads or uploads large set of files via StorageApi.
vadimsh@chromium.org35122be2013-09-19 02:48:00 +0000385
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800386 Implements compression support, parallel 'contains' checks, parallel uploads
387 and more.
388
389 Works only within single namespace (and thus hashing algorithm and compression
390 scheme are fixed).
391
392 Spawns multiple internal threads. Thread safe, but not fork safe.
393 """
394
Vadim Shtayurae0ab1902014-04-29 10:55:27 -0700395 def __init__(self, storage_api):
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000396 self._storage_api = storage_api
Vadim Shtayurae0ab1902014-04-29 10:55:27 -0700397 self._use_zip = is_namespace_with_compression(storage_api.namespace)
398 self._hash_algo = get_hash_algo(storage_api.namespace)
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000399 self._cpu_thread_pool = None
400 self._net_thread_pool = None
vadimsh@chromium.org35122be2013-09-19 02:48:00 +0000401
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000402 @property
Vadim Shtayurae0ab1902014-04-29 10:55:27 -0700403 def hash_algo(self):
404 """Hashing algorithm used to name files in storage based on their content.
405
406 Defined by |namespace|. See also 'get_hash_algo'.
407 """
408 return self._hash_algo
409
410 @property
411 def location(self):
412 """Location of a backing store that this class is using.
413
414 Exact meaning depends on the storage_api type. For IsolateServer it is
415 an URL of isolate server, for FileSystem is it a path in file system.
416 """
417 return self._storage_api.location
418
419 @property
420 def namespace(self):
421 """Isolate namespace used by this storage.
422
423 Indirectly defines hashing scheme and compression method used.
424 """
425 return self._storage_api.namespace
426
427 @property
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000428 def cpu_thread_pool(self):
429 """ThreadPool for CPU-bound tasks like zipping."""
430 if self._cpu_thread_pool is None:
431 self._cpu_thread_pool = threading_utils.ThreadPool(
432 2, max(threading_utils.num_processors(), 2), 0, 'zip')
433 return self._cpu_thread_pool
vadimsh@chromium.org35122be2013-09-19 02:48:00 +0000434
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000435 @property
436 def net_thread_pool(self):
437 """AutoRetryThreadPool for IO-bound tasks, retries IOError."""
438 if self._net_thread_pool is None:
439 self._net_thread_pool = WorkerPool()
440 return self._net_thread_pool
vadimsh@chromium.org35122be2013-09-19 02:48:00 +0000441
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000442 def close(self):
443 """Waits for all pending tasks to finish."""
444 if self._cpu_thread_pool:
445 self._cpu_thread_pool.join()
446 self._cpu_thread_pool.close()
447 self._cpu_thread_pool = None
448 if self._net_thread_pool:
449 self._net_thread_pool.join()
450 self._net_thread_pool.close()
451 self._net_thread_pool = None
vadimsh@chromium.org35122be2013-09-19 02:48:00 +0000452
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000453 def __enter__(self):
454 """Context manager interface."""
455 return self
456
457 def __exit__(self, _exc_type, _exc_value, _traceback):
458 """Context manager interface."""
459 self.close()
460 return False
461
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000462 def upload_items(self, items):
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800463 """Uploads a bunch of items to the isolate server.
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000464
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800465 It figures out what items are missing from the server and uploads only them.
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000466
467 Arguments:
468 items: list of Item instances that represents data to upload.
469
470 Returns:
471 List of items that were uploaded. All other items are already there.
472 """
473 # TODO(vadimsh): Optimize special case of len(items) == 1 that is frequently
474 # used by swarming.py. There's no need to spawn multiple threads and try to
475 # do stuff in parallel: there's nothing to parallelize. 'contains' check and
476 # 'push' should be performed sequentially in the context of current thread.
477
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800478 # Ensure all digests are calculated.
479 for item in items:
Vadim Shtayurae0ab1902014-04-29 10:55:27 -0700480 item.prepare(self._hash_algo)
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800481
vadimsh@chromium.org672cd2b2013-10-08 17:49:33 +0000482 # For each digest keep only first Item that matches it. All other items
483 # are just indistinguishable copies from the point of view of isolate
484 # server (it doesn't care about paths at all, only content and digests).
485 seen = {}
486 duplicates = 0
487 for item in items:
488 if seen.setdefault(item.digest, item) is not item:
489 duplicates += 1
490 items = seen.values()
491 if duplicates:
492 logging.info('Skipped %d duplicated files', duplicates)
493
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000494 # Enqueue all upload tasks.
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000495 missing = set()
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000496 uploaded = []
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800497 channel = threading_utils.TaskChannel()
498 for missing_item, push_state in self.get_missing_items(items):
499 missing.add(missing_item)
500 self.async_push(channel, missing_item, push_state)
501
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000502 # No need to spawn deadlock detector thread if there's nothing to upload.
503 if missing:
504 with threading_utils.DeadlockDetector(DEADLOCK_TIMEOUT) as detector:
505 # Wait for all started uploads to finish.
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000506 while len(uploaded) != len(missing):
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000507 detector.ping()
508 item = channel.pull()
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000509 uploaded.append(item)
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000510 logging.debug(
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000511 'Uploaded %d / %d: %s', len(uploaded), len(missing), item.digest)
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000512 logging.info('All files are uploaded')
513
514 # Print stats.
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000515 total = len(items)
516 total_size = sum(f.size for f in items)
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000517 logging.info(
518 'Total: %6d, %9.1fkb',
519 total,
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000520 total_size / 1024.)
521 cache_hit = set(items) - missing
522 cache_hit_size = sum(f.size for f in cache_hit)
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000523 logging.info(
524 'cache hit: %6d, %9.1fkb, %6.2f%% files, %6.2f%% size',
525 len(cache_hit),
526 cache_hit_size / 1024.,
527 len(cache_hit) * 100. / total,
528 cache_hit_size * 100. / total_size if total_size else 0)
529 cache_miss = missing
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000530 cache_miss_size = sum(f.size for f in cache_miss)
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000531 logging.info(
532 'cache miss: %6d, %9.1fkb, %6.2f%% files, %6.2f%% size',
533 len(cache_miss),
534 cache_miss_size / 1024.,
535 len(cache_miss) * 100. / total,
536 cache_miss_size * 100. / total_size if total_size else 0)
537
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000538 return uploaded
539
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800540 def get_fetch_url(self, item):
541 """Returns an URL that can be used to fetch given item once it's uploaded.
542
543 Note that if namespace uses compression, data at given URL is compressed.
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000544
545 Arguments:
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800546 item: Item to get fetch URL for.
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000547
548 Returns:
549 An URL or None if underlying protocol doesn't support this.
550 """
Vadim Shtayurae0ab1902014-04-29 10:55:27 -0700551 item.prepare(self._hash_algo)
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800552 return self._storage_api.get_fetch_url(item.digest)
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000553
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800554 def async_push(self, channel, item, push_state):
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000555 """Starts asynchronous push to the server in a parallel thread.
556
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800557 Can be used only after |item| was checked for presence on a server with
558 'get_missing_items' call. 'get_missing_items' returns |push_state| object
559 that contains storage specific information describing how to upload
560 the item (for example in case of cloud storage, it is signed upload URLs).
561
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000562 Arguments:
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +0000563 channel: TaskChannel that receives back |item| when upload ends.
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000564 item: item to upload as instance of Item class.
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800565 push_state: push state returned by 'get_missing_items' call for |item|.
566
567 Returns:
568 None, but |channel| later receives back |item| when upload ends.
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000569 """
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800570 # Thread pool task priority.
571 priority = WorkerPool.HIGH if item.high_priority else WorkerPool.MED
572
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +0000573 def push(content):
Marc-Antoine Ruel095a8be2014-03-21 14:58:19 -0400574 """Pushes an Item and returns it to |channel|."""
Vadim Shtayurae0ab1902014-04-29 10:55:27 -0700575 item.prepare(self._hash_algo)
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800576 self._storage_api.push(item, push_state, content)
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000577 return item
578
579 # If zipping is not required, just start a push task.
Vadim Shtayurae0ab1902014-04-29 10:55:27 -0700580 if not self._use_zip:
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800581 self.net_thread_pool.add_task_with_channel(
582 channel, priority, push, item.content())
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000583 return
584
585 # If zipping is enabled, zip in a separate thread.
586 def zip_and_push():
587 # TODO(vadimsh): Implement streaming uploads. Before it's done, assemble
588 # content right here. It will block until all file is zipped.
589 try:
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800590 stream = zip_compress(item.content(), item.compression_level)
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000591 data = ''.join(stream)
592 except Exception as exc:
593 logging.error('Failed to zip \'%s\': %s', item, exc)
Vadim Shtayura0ffc4092013-11-20 17:49:52 -0800594 channel.send_exception()
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000595 return
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +0000596 self.net_thread_pool.add_task_with_channel(
597 channel, priority, push, [data])
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000598 self.cpu_thread_pool.add_task(priority, zip_and_push)
vadimsh@chromium.org35122be2013-09-19 02:48:00 +0000599
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800600 def push(self, item, push_state):
601 """Synchronously pushes a single item to the server.
602
603 If you need to push many items at once, consider using 'upload_items' or
604 'async_push' with instance of TaskChannel.
605
606 Arguments:
607 item: item to upload as instance of Item class.
608 push_state: push state returned by 'get_missing_items' call for |item|.
609
610 Returns:
611 Pushed item (same object as |item|).
612 """
613 channel = threading_utils.TaskChannel()
614 with threading_utils.DeadlockDetector(DEADLOCK_TIMEOUT):
615 self.async_push(channel, item, push_state)
616 pushed = channel.pull()
617 assert pushed is item
618 return item
619
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +0000620 def async_fetch(self, channel, priority, digest, size, sink):
621 """Starts asynchronous fetch from the server in a parallel thread.
622
623 Arguments:
624 channel: TaskChannel that receives back |digest| when download ends.
625 priority: thread pool task priority for the fetch.
626 digest: hex digest of an item to download.
627 size: expected size of the item (after decompression).
628 sink: function that will be called as sink(generator).
629 """
630 def fetch():
631 try:
632 # Prepare reading pipeline.
633 stream = self._storage_api.fetch(digest)
Vadim Shtayurae0ab1902014-04-29 10:55:27 -0700634 if self._use_zip:
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +0000635 stream = zip_decompress(stream, DISK_FILE_CHUNK)
636 # Run |stream| through verifier that will assert its size.
637 verifier = FetchStreamVerifier(stream, size)
638 # Verified stream goes to |sink|.
639 sink(verifier.run())
640 except Exception as err:
Vadim Shtayura0ffc4092013-11-20 17:49:52 -0800641 logging.error('Failed to fetch %s: %s', digest, err)
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +0000642 raise
643 return digest
644
645 # Don't bother with zip_thread_pool for decompression. Decompression is
646 # really fast and most probably IO bound anyway.
647 self.net_thread_pool.add_task_with_channel(channel, priority, fetch)
648
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000649 def get_missing_items(self, items):
650 """Yields items that are missing from the server.
vadimsh@chromium.org35122be2013-09-19 02:48:00 +0000651
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000652 Issues multiple parallel queries via StorageApi's 'contains' method.
vadimsh@chromium.org35122be2013-09-19 02:48:00 +0000653
654 Arguments:
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000655 items: a list of Item objects to check.
vadimsh@chromium.org35122be2013-09-19 02:48:00 +0000656
657 Yields:
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800658 For each missing item it yields a pair (item, push_state), where:
659 * item - Item object that is missing (one of |items|).
660 * push_state - opaque object that contains storage specific information
661 describing how to upload the item (for example in case of cloud
662 storage, it is signed upload URLs). It can later be passed to
663 'async_push'.
vadimsh@chromium.org35122be2013-09-19 02:48:00 +0000664 """
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000665 channel = threading_utils.TaskChannel()
666 pending = 0
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800667
668 # Ensure all digests are calculated.
669 for item in items:
Vadim Shtayurae0ab1902014-04-29 10:55:27 -0700670 item.prepare(self._hash_algo)
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800671
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000672 # Enqueue all requests.
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800673 for batch in batch_items_for_check(items):
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000674 self.net_thread_pool.add_task_with_channel(channel, WorkerPool.HIGH,
675 self._storage_api.contains, batch)
676 pending += 1
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800677
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000678 # Yield results as they come in.
679 for _ in xrange(pending):
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800680 for missing_item, push_state in channel.pull().iteritems():
681 yield missing_item, push_state
vadimsh@chromium.org35122be2013-09-19 02:48:00 +0000682
vadimsh@chromium.org35122be2013-09-19 02:48:00 +0000683
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800684def batch_items_for_check(items):
685 """Splits list of items to check for existence on the server into batches.
vadimsh@chromium.org35122be2013-09-19 02:48:00 +0000686
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800687 Each batch corresponds to a single 'exists?' query to the server via a call
688 to StorageApi's 'contains' method.
vadimsh@chromium.org35122be2013-09-19 02:48:00 +0000689
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800690 Arguments:
691 items: a list of Item objects.
692
693 Yields:
694 Batches of items to query for existence in a single operation,
695 each batch is a list of Item objects.
696 """
697 batch_count = 0
698 batch_size_limit = ITEMS_PER_CONTAINS_QUERIES[0]
699 next_queries = []
700 for item in sorted(items, key=lambda x: x.size, reverse=True):
701 next_queries.append(item)
702 if len(next_queries) == batch_size_limit:
vadimsh@chromium.org35122be2013-09-19 02:48:00 +0000703 yield next_queries
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800704 next_queries = []
705 batch_count += 1
706 batch_size_limit = ITEMS_PER_CONTAINS_QUERIES[
707 min(batch_count, len(ITEMS_PER_CONTAINS_QUERIES) - 1)]
708 if next_queries:
709 yield next_queries
vadimsh@chromium.org35122be2013-09-19 02:48:00 +0000710
711
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +0000712class FetchQueue(object):
713 """Fetches items from Storage and places them into LocalCache.
714
715 It manages multiple concurrent fetch operations. Acts as a bridge between
716 Storage and LocalCache so that Storage and LocalCache don't depend on each
717 other at all.
718 """
719
720 def __init__(self, storage, cache):
721 self.storage = storage
722 self.cache = cache
723 self._channel = threading_utils.TaskChannel()
724 self._pending = set()
725 self._accessed = set()
726 self._fetched = cache.cached_set()
727
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800728 def add(self, digest, size=UNKNOWN_FILE_SIZE, priority=WorkerPool.MED):
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +0000729 """Starts asynchronous fetch of item |digest|."""
730 # Fetching it now?
731 if digest in self._pending:
732 return
733
734 # Mark this file as in use, verify_all_cached will later ensure it is still
735 # in cache.
736 self._accessed.add(digest)
737
738 # Already fetched? Notify cache to update item's LRU position.
739 if digest in self._fetched:
740 # 'touch' returns True if item is in cache and not corrupted.
741 if self.cache.touch(digest, size):
742 return
743 # Item is corrupted, remove it from cache and fetch it again.
744 self._fetched.remove(digest)
745 self.cache.evict(digest)
746
747 # TODO(maruel): It should look at the free disk space, the current cache
748 # size and the size of the new item on every new item:
749 # - Trim the cache as more entries are listed when free disk space is low,
750 # otherwise if the amount of data downloaded during the run > free disk
751 # space, it'll crash.
752 # - Make sure there's enough free disk space to fit all dependencies of
753 # this run! If not, abort early.
754
755 # Start fetching.
756 self._pending.add(digest)
757 self.storage.async_fetch(
758 self._channel, priority, digest, size,
759 functools.partial(self.cache.write, digest))
760
761 def wait(self, digests):
762 """Starts a loop that waits for at least one of |digests| to be retrieved.
763
764 Returns the first digest retrieved.
765 """
766 # Flush any already fetched items.
767 for digest in digests:
768 if digest in self._fetched:
769 return digest
770
771 # Ensure all requested items are being fetched now.
772 assert all(digest in self._pending for digest in digests), (
773 digests, self._pending)
774
775 # Wait for some requested item to finish fetching.
776 while self._pending:
777 digest = self._channel.pull()
778 self._pending.remove(digest)
779 self._fetched.add(digest)
780 if digest in digests:
781 return digest
782
783 # Should never reach this point due to assert above.
784 raise RuntimeError('Impossible state')
785
786 def inject_local_file(self, path, algo):
787 """Adds local file to the cache as if it was fetched from storage."""
788 with open(path, 'rb') as f:
789 data = f.read()
790 digest = algo(data).hexdigest()
791 self.cache.write(digest, [data])
792 self._fetched.add(digest)
793 return digest
794
795 @property
796 def pending_count(self):
797 """Returns number of items to be fetched."""
798 return len(self._pending)
799
800 def verify_all_cached(self):
801 """True if all accessed items are in cache."""
802 return self._accessed.issubset(self.cache.cached_set())
803
804
805class FetchStreamVerifier(object):
806 """Verifies that fetched file is valid before passing it to the LocalCache."""
807
808 def __init__(self, stream, expected_size):
809 self.stream = stream
810 self.expected_size = expected_size
811 self.current_size = 0
812
813 def run(self):
814 """Generator that yields same items as |stream|.
815
816 Verifies |stream| is complete before yielding a last chunk to consumer.
817
818 Also wraps IOError produced by consumer into MappingError exceptions since
819 otherwise Storage will retry fetch on unrelated local cache errors.
820 """
821 # Read one chunk ahead, keep it in |stored|.
822 # That way a complete stream can be verified before pushing last chunk
823 # to consumer.
824 stored = None
825 for chunk in self.stream:
826 assert chunk is not None
827 if stored is not None:
828 self._inspect_chunk(stored, is_last=False)
829 try:
830 yield stored
831 except IOError as exc:
832 raise MappingError('Failed to store an item in cache: %s' % exc)
833 stored = chunk
834 if stored is not None:
835 self._inspect_chunk(stored, is_last=True)
836 try:
837 yield stored
838 except IOError as exc:
839 raise MappingError('Failed to store an item in cache: %s' % exc)
840
841 def _inspect_chunk(self, chunk, is_last):
842 """Called for each fetched chunk before passing it to consumer."""
843 self.current_size += len(chunk)
844 if (is_last and (self.expected_size != UNKNOWN_FILE_SIZE) and
845 (self.expected_size != self.current_size)):
846 raise IOError('Incorrect file size: expected %d, got %d' % (
847 self.expected_size, self.current_size))
848
849
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000850class StorageApi(object):
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800851 """Interface for classes that implement low-level storage operations.
852
853 StorageApi is oblivious of compression and hashing scheme used. This details
854 are handled in higher level Storage class.
855
856 Clients should generally not use StorageApi directly. Storage class is
857 preferred since it implements compression and upload optimizations.
858 """
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000859
Vadim Shtayurae0ab1902014-04-29 10:55:27 -0700860 @property
861 def location(self):
862 """Location of a backing store that this class is using.
863
864 Exact meaning depends on the type. For IsolateServer it is an URL of isolate
865 server, for FileSystem is it a path in file system.
866 """
867 raise NotImplementedError()
868
869 @property
870 def namespace(self):
871 """Isolate namespace used by this storage.
872
873 Indirectly defines hashing scheme and compression method used.
874 """
875 raise NotImplementedError()
876
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +0000877 def get_fetch_url(self, digest):
878 """Returns an URL that can be used to fetch an item with given digest.
879
880 Arguments:
881 digest: hex digest of item to fetch.
882
883 Returns:
884 An URL or None if the protocol doesn't support this.
885 """
886 raise NotImplementedError()
887
Vadim Shtayuraf0cb97a2013-12-05 13:57:49 -0800888 def fetch(self, digest, offset=0):
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000889 """Fetches an object and yields its content.
890
891 Arguments:
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000892 digest: hash digest of item to download.
Vadim Shtayuraf0cb97a2013-12-05 13:57:49 -0800893 offset: offset (in bytes) from the start of the file to resume fetch from.
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000894
895 Yields:
896 Chunks of downloaded item (as str objects).
897 """
898 raise NotImplementedError()
899
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800900 def push(self, item, push_state, content=None):
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000901 """Uploads an |item| with content generated by |content| generator.
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000902
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800903 |item| MUST go through 'contains' call to get |push_state| before it can
904 be pushed to the storage.
905
906 To be clear, here is one possible usage:
907 all_items = [... all items to push as Item subclasses ...]
908 for missing_item, push_state in storage_api.contains(all_items).items():
909 storage_api.push(missing_item, push_state)
910
911 When pushing to a namespace with compression, data that should be pushed
912 and data provided by the item is not the same. In that case |content| is
913 not None and it yields chunks of compressed data (using item.content() as
914 a source of original uncompressed data). This is implemented by Storage
915 class.
916
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000917 Arguments:
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000918 item: Item object that holds information about an item being pushed.
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800919 push_state: push state object as returned by 'contains' call.
920 content: a generator that yields chunks to push, item.content() if None.
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000921
922 Returns:
923 None.
924 """
925 raise NotImplementedError()
926
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000927 def contains(self, items):
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800928 """Checks for |items| on the server, prepares missing ones for upload.
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000929
930 Arguments:
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800931 items: list of Item objects to check for presence.
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000932
933 Returns:
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800934 A dict missing Item -> opaque push state object to be passed to 'push'.
935 See doc string for 'push'.
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +0000936 """
937 raise NotImplementedError()
938
939
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800940class _IsolateServerPushState(object):
941 """Per-item state passed from IsolateServer.contains to IsolateServer.push.
Mike Frysinger27f03da2014-02-12 16:47:01 -0500942
943 Note this needs to be a global class to support pickling.
944 """
945
946 def __init__(self, upload_url, finalize_url):
947 self.upload_url = upload_url
948 self.finalize_url = finalize_url
949 self.uploaded = False
950 self.finalized = False
951
952
vadimsh@chromium.org35122be2013-09-19 02:48:00 +0000953class IsolateServer(StorageApi):
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000954 """StorageApi implementation that downloads and uploads to Isolate Server.
955
956 It uploads and downloads directly from Google Storage whenever appropriate.
Vadim Shtayurabcff74f2014-02-27 16:19:34 -0800957 Works only within single namespace.
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000958 """
959
maruel@chromium.org3e42ce82013-09-12 18:36:59 +0000960 def __init__(self, base_url, namespace):
vadimsh@chromium.org35122be2013-09-19 02:48:00 +0000961 super(IsolateServer, self).__init__()
maruel@chromium.org3e42ce82013-09-12 18:36:59 +0000962 assert base_url.startswith('http'), base_url
Vadim Shtayurae0ab1902014-04-29 10:55:27 -0700963 self._base_url = base_url.rstrip('/')
964 self._namespace = namespace
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000965 self._lock = threading.Lock()
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000966 self._server_caps = None
967
968 @staticmethod
969 def _generate_handshake_request():
970 """Returns a dict to be sent as handshake request body."""
971 # TODO(vadimsh): Set 'pusher' and 'fetcher' according to intended usage.
972 return {
973 'client_app_version': __version__,
974 'fetcher': True,
975 'protocol_version': ISOLATE_PROTOCOL_VERSION,
976 'pusher': True,
977 }
978
979 @staticmethod
980 def _validate_handshake_response(caps):
981 """Validates and normalizes handshake response."""
982 logging.info('Protocol version: %s', caps['protocol_version'])
983 logging.info('Server version: %s', caps['server_app_version'])
984 if caps.get('error'):
985 raise MappingError(caps['error'])
986 if not caps['access_token']:
987 raise ValueError('access_token is missing')
988 return caps
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +0000989
990 @property
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +0000991 def _server_capabilities(self):
992 """Performs handshake with the server if not yet done.
993
994 Returns:
995 Server capabilities dictionary as returned by /handshake endpoint.
996
997 Raises:
998 MappingError if server rejects the handshake.
999 """
maruel@chromium.org3e42ce82013-09-12 18:36:59 +00001000 # TODO(maruel): Make this request much earlier asynchronously while the
1001 # files are being enumerated.
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001002
1003 # TODO(vadimsh): Put |namespace| in the URL so that server can apply
1004 # namespace-level ACLs to this call.
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +00001005 with self._lock:
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001006 if self._server_caps is None:
1007 request_body = json.dumps(
1008 self._generate_handshake_request(), separators=(',', ':'))
1009 response = net.url_read(
Vadim Shtayurae0ab1902014-04-29 10:55:27 -07001010 url=self._base_url + '/content-gs/handshake',
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001011 data=request_body,
1012 content_type='application/json',
1013 method='POST')
1014 if response is None:
1015 raise MappingError('Failed to perform handshake.')
1016 try:
1017 caps = json.loads(response)
1018 if not isinstance(caps, dict):
1019 raise ValueError('Expecting JSON dict')
1020 self._server_caps = self._validate_handshake_response(caps)
1021 except (ValueError, KeyError, TypeError) as exc:
1022 # KeyError exception has very confusing str conversion: it's just a
1023 # missing key value and nothing else. So print exception class name
1024 # as well.
1025 raise MappingError('Invalid handshake response (%s): %s' % (
1026 exc.__class__.__name__, exc))
1027 return self._server_caps
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +00001028
Vadim Shtayurae0ab1902014-04-29 10:55:27 -07001029 @property
1030 def location(self):
1031 return self._base_url
1032
1033 @property
1034 def namespace(self):
1035 return self._namespace
1036
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +00001037 def get_fetch_url(self, digest):
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001038 assert isinstance(digest, basestring)
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +00001039 return '%s/content-gs/retrieve/%s/%s' % (
Vadim Shtayurae0ab1902014-04-29 10:55:27 -07001040 self._base_url, self._namespace, digest)
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +00001041
Vadim Shtayuraf0cb97a2013-12-05 13:57:49 -08001042 def fetch(self, digest, offset=0):
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +00001043 source_url = self.get_fetch_url(digest)
Vadim Shtayuraf0cb97a2013-12-05 13:57:49 -08001044 logging.debug('download_file(%s, %d)', source_url, offset)
maruel@chromium.orge45728d2013-09-16 23:23:22 +00001045
maruel@chromium.orge45728d2013-09-16 23:23:22 +00001046 connection = net.url_open(
Vadim Shtayuraf0cb97a2013-12-05 13:57:49 -08001047 source_url,
Vadim Shtayuraf0cb97a2013-12-05 13:57:49 -08001048 read_timeout=DOWNLOAD_READ_TIMEOUT,
1049 headers={'Range': 'bytes=%d-' % offset} if offset else None)
1050
maruel@chromium.orge45728d2013-09-16 23:23:22 +00001051 if not connection:
Vadim Shtayurae34e13a2014-02-02 11:23:26 -08001052 raise IOError('Request failed - %s' % source_url)
Vadim Shtayuraf0cb97a2013-12-05 13:57:49 -08001053
1054 # If |offset| is used, verify server respects it by checking Content-Range.
1055 if offset:
1056 content_range = connection.get_header('Content-Range')
1057 if not content_range:
1058 raise IOError('Missing Content-Range header')
1059
1060 # 'Content-Range' format is 'bytes <offset>-<last_byte_index>/<size>'.
1061 # According to a spec, <size> can be '*' meaning "Total size of the file
1062 # is not known in advance".
1063 try:
1064 match = re.match(r'bytes (\d+)-(\d+)/(\d+|\*)', content_range)
1065 if not match:
1066 raise ValueError()
1067 content_offset = int(match.group(1))
1068 last_byte_index = int(match.group(2))
1069 size = None if match.group(3) == '*' else int(match.group(3))
1070 except ValueError:
1071 raise IOError('Invalid Content-Range header: %s' % content_range)
1072
1073 # Ensure returned offset equals requested one.
1074 if offset != content_offset:
1075 raise IOError('Expecting offset %d, got %d (Content-Range is %s)' % (
1076 offset, content_offset, content_range))
1077
1078 # Ensure entire tail of the file is returned.
1079 if size is not None and last_byte_index + 1 != size:
1080 raise IOError('Incomplete response. Content-Range: %s' % content_range)
1081
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00001082 return stream_read(connection, NET_IO_FILE_CHUNK)
maruel@chromium.orge45728d2013-09-16 23:23:22 +00001083
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001084 def push(self, item, push_state, content=None):
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001085 assert isinstance(item, Item)
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001086 assert item.digest is not None
1087 assert item.size is not None
1088 assert isinstance(push_state, _IsolateServerPushState)
1089 assert not push_state.finalized
1090
1091 # Default to item.content().
1092 content = item.content() if content is None else content
1093
1094 # Do not iterate byte by byte over 'str'. Push it all as a single chunk.
1095 if isinstance(content, basestring):
1096 assert not isinstance(content, unicode), 'Unicode string is not allowed'
1097 content = [content]
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +00001098
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001099 # TODO(vadimsh): Do not read from |content| generator when retrying push.
1100 # If |content| is indeed a generator, it can not be re-winded back
1101 # to the beginning of the stream. A retry will find it exhausted. A possible
1102 # solution is to wrap |content| generator with some sort of caching
1103 # restartable generator. It should be done alongside streaming support
1104 # implementation.
1105
1106 # This push operation may be a retry after failed finalization call below,
1107 # no need to reupload contents in that case.
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001108 if not push_state.uploaded:
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001109 # A cheezy way to avoid memcpy of (possibly huge) file, until streaming
1110 # upload support is implemented.
1111 if isinstance(content, list) and len(content) == 1:
1112 content = content[0]
1113 else:
1114 content = ''.join(content)
1115 # PUT file to |upload_url|.
1116 response = net.url_read(
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001117 url=push_state.upload_url,
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001118 data=content,
1119 content_type='application/octet-stream',
1120 method='PUT')
1121 if response is None:
1122 raise IOError('Failed to upload a file %s to %s' % (
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001123 item.digest, push_state.upload_url))
1124 push_state.uploaded = True
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +00001125 else:
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001126 logging.info(
1127 'A file %s already uploaded, retrying finalization only', item.digest)
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +00001128
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001129 # Optionally notify the server that it's done.
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001130 if push_state.finalize_url:
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001131 # TODO(vadimsh): Calculate MD5 or CRC32C sum while uploading a file and
1132 # send it to isolated server. That way isolate server can verify that
1133 # the data safely reached Google Storage (GS provides MD5 and CRC32C of
1134 # stored files).
1135 response = net.url_read(
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001136 url=push_state.finalize_url,
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001137 data='',
1138 content_type='application/json',
1139 method='POST')
1140 if response is None:
1141 raise IOError('Failed to finalize an upload of %s' % item.digest)
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001142 push_state.finalized = True
maruel@chromium.orgd1e20c92013-09-17 20:54:26 +00001143
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001144 def contains(self, items):
1145 logging.info('Checking existence of %d files...', len(items))
maruel@chromium.orgd1e20c92013-09-17 20:54:26 +00001146
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001147 # Ensure all items were initialized with 'prepare' call. Storage does that.
1148 assert all(i.digest is not None and i.size is not None for i in items)
1149
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001150 # Request body is a json encoded list of dicts.
1151 body = [
1152 {
1153 'h': item.digest,
1154 's': item.size,
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001155 'i': int(item.high_priority),
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001156 } for item in items
vadimsh@chromium.org35122be2013-09-19 02:48:00 +00001157 ]
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001158
1159 query_url = '%s/content-gs/pre-upload/%s?token=%s' % (
Vadim Shtayurae0ab1902014-04-29 10:55:27 -07001160 self._base_url,
1161 self._namespace,
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001162 urllib.quote(self._server_capabilities['access_token']))
1163 response_body = net.url_read(
1164 url=query_url,
1165 data=json.dumps(body, separators=(',', ':')),
1166 content_type='application/json',
1167 method='POST')
1168 if response_body is None:
1169 raise MappingError('Failed to execute /pre-upload query')
1170
1171 # Response body is a list of push_urls (or null if file is already present).
1172 try:
1173 response = json.loads(response_body)
1174 if not isinstance(response, list):
1175 raise ValueError('Expecting response with json-encoded list')
1176 if len(response) != len(items):
1177 raise ValueError(
1178 'Incorrect number of items in the list, expected %d, '
1179 'but got %d' % (len(items), len(response)))
1180 except ValueError as err:
1181 raise MappingError(
1182 'Invalid response from server: %s, body is %s' % (err, response_body))
1183
1184 # Pick Items that are missing, attach _PushState to them.
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001185 missing_items = {}
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001186 for i, push_urls in enumerate(response):
1187 if push_urls:
1188 assert len(push_urls) == 2, str(push_urls)
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001189 missing_items[items[i]] = _IsolateServerPushState(
1190 push_urls[0], push_urls[1])
vadimsh@chromium.org35122be2013-09-19 02:48:00 +00001191 logging.info('Queried %d files, %d cache hit',
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001192 len(items), len(items) - len(missing_items))
1193 return missing_items
maruel@chromium.orgc6f90062012-11-07 18:32:22 +00001194
1195
vadimsh@chromium.org35122be2013-09-19 02:48:00 +00001196class FileSystem(StorageApi):
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +00001197 """StorageApi implementation that fetches data from the file system.
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +00001198
1199 The common use case is a NFS/CIFS file server that is mounted locally that is
1200 used to fetch the file on a local partition.
1201 """
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001202
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001203 # Used for push_state instead of None. That way caller is forced to
1204 # call 'contains' before 'push'. Naively passing None in 'push' will not work.
1205 _DUMMY_PUSH_STATE = object()
1206
Vadim Shtayurae0ab1902014-04-29 10:55:27 -07001207 def __init__(self, base_path, namespace):
vadimsh@chromium.org35122be2013-09-19 02:48:00 +00001208 super(FileSystem, self).__init__()
Vadim Shtayurae0ab1902014-04-29 10:55:27 -07001209 self._base_path = base_path
1210 self._namespace = namespace
1211
1212 @property
1213 def location(self):
1214 return self._base_path
1215
1216 @property
1217 def namespace(self):
1218 return self._namespace
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +00001219
vadimsh@chromium.orgf24e5c32013-10-11 21:16:21 +00001220 def get_fetch_url(self, digest):
1221 return None
1222
Vadim Shtayuraf0cb97a2013-12-05 13:57:49 -08001223 def fetch(self, digest, offset=0):
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001224 assert isinstance(digest, basestring)
Vadim Shtayurae0ab1902014-04-29 10:55:27 -07001225 return file_read(os.path.join(self._base_path, digest), offset=offset)
maruel@chromium.orge45728d2013-09-16 23:23:22 +00001226
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001227 def push(self, item, push_state, content=None):
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001228 assert isinstance(item, Item)
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001229 assert item.digest is not None
1230 assert item.size is not None
1231 assert push_state is self._DUMMY_PUSH_STATE
1232 content = item.content() if content is None else content
1233 if isinstance(content, basestring):
1234 assert not isinstance(content, unicode), 'Unicode string is not allowed'
1235 content = [content]
Vadim Shtayurae0ab1902014-04-29 10:55:27 -07001236 file_write(os.path.join(self._base_path, item.digest), content)
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +00001237
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001238 def contains(self, items):
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001239 assert all(i.digest is not None and i.size is not None for i in items)
1240 return dict(
1241 (item, self._DUMMY_PUSH_STATE) for item in items
Vadim Shtayurae0ab1902014-04-29 10:55:27 -07001242 if not os.path.exists(os.path.join(self._base_path, item.digest))
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001243 )
vadimsh@chromium.org35122be2013-09-19 02:48:00 +00001244
1245
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00001246class LocalCache(object):
1247 """Local cache that stores objects fetched via Storage.
1248
1249 It can be accessed concurrently from multiple threads, so it should protect
1250 its internal state with some lock.
1251 """
Marc-Antoine Ruel2283ad12014-02-09 11:14:57 -05001252 cache_dir = None
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00001253
1254 def __enter__(self):
1255 """Context manager interface."""
1256 return self
1257
1258 def __exit__(self, _exc_type, _exec_value, _traceback):
1259 """Context manager interface."""
1260 return False
1261
1262 def cached_set(self):
1263 """Returns a set of all cached digests (always a new object)."""
1264 raise NotImplementedError()
1265
1266 def touch(self, digest, size):
1267 """Ensures item is not corrupted and updates its LRU position.
1268
1269 Arguments:
1270 digest: hash digest of item to check.
1271 size: expected size of this item.
1272
1273 Returns:
1274 True if item is in cache and not corrupted.
1275 """
1276 raise NotImplementedError()
1277
1278 def evict(self, digest):
1279 """Removes item from cache if it's there."""
1280 raise NotImplementedError()
1281
1282 def read(self, digest):
1283 """Returns contents of the cached item as a single str."""
1284 raise NotImplementedError()
1285
1286 def write(self, digest, content):
1287 """Reads data from |content| generator and stores it in cache."""
1288 raise NotImplementedError()
1289
Marc-Antoine Ruelfb199cf2013-11-12 15:38:12 -05001290 def hardlink(self, digest, dest, file_mode):
1291 """Ensures file at |dest| has same content as cached |digest|.
1292
1293 If file_mode is provided, it is used to set the executable bit if
1294 applicable.
1295 """
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00001296 raise NotImplementedError()
1297
1298
1299class MemoryCache(LocalCache):
1300 """LocalCache implementation that stores everything in memory."""
1301
Vadim Shtayurae3fbd102014-04-29 17:05:21 -07001302 def __init__(self, file_mode_mask=0500):
1303 """Args:
1304 file_mode_mask: bit mask to AND file mode with. Default value will make
1305 all mapped files to be read only.
1306 """
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00001307 super(MemoryCache, self).__init__()
Vadim Shtayurae3fbd102014-04-29 17:05:21 -07001308 self._file_mode_mask = file_mode_mask
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00001309 # Let's not assume dict is thread safe.
1310 self._lock = threading.Lock()
1311 self._contents = {}
1312
1313 def cached_set(self):
1314 with self._lock:
1315 return set(self._contents)
1316
1317 def touch(self, digest, size):
1318 with self._lock:
1319 return digest in self._contents
1320
1321 def evict(self, digest):
1322 with self._lock:
1323 self._contents.pop(digest, None)
1324
1325 def read(self, digest):
1326 with self._lock:
1327 return self._contents[digest]
1328
1329 def write(self, digest, content):
1330 # Assemble whole stream before taking the lock.
1331 data = ''.join(content)
1332 with self._lock:
1333 self._contents[digest] = data
1334
Marc-Antoine Ruelfb199cf2013-11-12 15:38:12 -05001335 def hardlink(self, digest, dest, file_mode):
1336 """Since data is kept in memory, there is no filenode to hardlink."""
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00001337 file_write(dest, [self.read(digest)])
Marc-Antoine Ruelfb199cf2013-11-12 15:38:12 -05001338 if file_mode is not None:
Vadim Shtayurae3fbd102014-04-29 17:05:21 -07001339 os.chmod(dest, file_mode & self._file_mode_mask)
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00001340
1341
vadimsh@chromium.org35122be2013-09-19 02:48:00 +00001342def get_hash_algo(_namespace):
1343 """Return hash algorithm class to use when uploading to given |namespace|."""
1344 # TODO(vadimsh): Implement this at some point.
1345 return hashlib.sha1
1346
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +00001347
vadimsh@chromium.org7cdf1c02013-09-25 00:24:16 +00001348def is_namespace_with_compression(namespace):
1349 """Returns True if given |namespace| stores compressed objects."""
1350 return namespace.endswith(('-gzip', '-deflate'))
1351
1352
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +00001353def get_storage_api(file_or_url, namespace):
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001354 """Returns an object that implements low-level StorageApi interface.
1355
1356 It is used by Storage to work with single isolate |namespace|. It should
1357 rarely be used directly by clients, see 'get_storage' for
1358 a better alternative.
1359
1360 Arguments:
1361 file_or_url: a file path to use file system based storage, or URL of isolate
1362 service to use shared cloud based storage.
1363 namespace: isolate namespace to operate in, also defines hashing and
1364 compression scheme used, i.e. namespace names that end with '-gzip'
1365 store compressed data.
1366
1367 Returns:
1368 Instance of StorageApi subclass.
1369 """
Marc-Antoine Ruel37989932013-11-19 16:28:08 -05001370 if file_path.is_url(file_or_url):
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +00001371 return IsolateServer(file_or_url, namespace)
1372 else:
Vadim Shtayurae0ab1902014-04-29 10:55:27 -07001373 return FileSystem(file_or_url, namespace)
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +00001374
1375
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00001376def get_storage(file_or_url, namespace):
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001377 """Returns Storage class that can upload and download from |namespace|.
1378
1379 Arguments:
1380 file_or_url: a file path to use file system based storage, or URL of isolate
1381 service to use shared cloud based storage.
1382 namespace: isolate namespace to operate in, also defines hashing and
1383 compression scheme used, i.e. namespace names that end with '-gzip'
1384 store compressed data.
1385
1386 Returns:
1387 Instance of Storage.
1388 """
Vadim Shtayurae0ab1902014-04-29 10:55:27 -07001389 return Storage(get_storage_api(file_or_url, namespace))
maruel@chromium.orgdedbf492013-09-12 20:42:11 +00001390
maruel@chromium.orgdedbf492013-09-12 20:42:11 +00001391
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05001392def expand_symlinks(indir, relfile):
1393 """Follows symlinks in |relfile|, but treating symlinks that point outside the
1394 build tree as if they were ordinary directories/files. Returns the final
1395 symlink-free target and a list of paths to symlinks encountered in the
1396 process.
1397
1398 The rule about symlinks outside the build tree is for the benefit of the
1399 Chromium OS ebuild, which symlinks the output directory to an unrelated path
1400 in the chroot.
1401
1402 Fails when a directory loop is detected, although in theory we could support
1403 that case.
1404 """
1405 is_directory = relfile.endswith(os.path.sep)
1406 done = indir
1407 todo = relfile.strip(os.path.sep)
1408 symlinks = []
1409
1410 while todo:
1411 pre_symlink, symlink, post_symlink = file_path.split_at_symlink(
1412 done, todo)
1413 if not symlink:
1414 todo = file_path.fix_native_path_case(done, todo)
1415 done = os.path.join(done, todo)
1416 break
1417 symlink_path = os.path.join(done, pre_symlink, symlink)
1418 post_symlink = post_symlink.lstrip(os.path.sep)
1419 # readlink doesn't exist on Windows.
1420 # pylint: disable=E1101
1421 target = os.path.normpath(os.path.join(done, pre_symlink))
1422 symlink_target = os.readlink(symlink_path)
1423 if os.path.isabs(symlink_target):
1424 # Absolute path are considered a normal directories. The use case is
1425 # generally someone who puts the output directory on a separate drive.
1426 target = symlink_target
1427 else:
1428 # The symlink itself could be using the wrong path case.
1429 target = file_path.fix_native_path_case(target, symlink_target)
1430
1431 if not os.path.exists(target):
1432 raise MappingError(
1433 'Symlink target doesn\'t exist: %s -> %s' % (symlink_path, target))
1434 target = file_path.get_native_path_case(target)
1435 if not file_path.path_starts_with(indir, target):
1436 done = symlink_path
1437 todo = post_symlink
1438 continue
1439 if file_path.path_starts_with(target, symlink_path):
1440 raise MappingError(
1441 'Can\'t map recursive symlink reference %s -> %s' %
1442 (symlink_path, target))
1443 logging.info('Found symlink: %s -> %s', symlink_path, target)
1444 symlinks.append(os.path.relpath(symlink_path, indir))
1445 # Treat the common prefix of the old and new paths as done, and start
1446 # scanning again.
1447 target = target.split(os.path.sep)
1448 symlink_path = symlink_path.split(os.path.sep)
1449 prefix_length = 0
1450 for target_piece, symlink_path_piece in zip(target, symlink_path):
1451 if target_piece == symlink_path_piece:
1452 prefix_length += 1
1453 else:
1454 break
1455 done = os.path.sep.join(target[:prefix_length])
1456 todo = os.path.join(
1457 os.path.sep.join(target[prefix_length:]), post_symlink)
1458
1459 relfile = os.path.relpath(done, indir)
1460 relfile = relfile.rstrip(os.path.sep) + is_directory * os.path.sep
1461 return relfile, symlinks
1462
1463
1464def expand_directory_and_symlink(indir, relfile, blacklist, follow_symlinks):
1465 """Expands a single input. It can result in multiple outputs.
1466
1467 This function is recursive when relfile is a directory.
1468
1469 Note: this code doesn't properly handle recursive symlink like one created
1470 with:
1471 ln -s .. foo
1472 """
1473 if os.path.isabs(relfile):
1474 raise MappingError('Can\'t map absolute path %s' % relfile)
1475
1476 infile = file_path.normpath(os.path.join(indir, relfile))
1477 if not infile.startswith(indir):
1478 raise MappingError('Can\'t map file %s outside %s' % (infile, indir))
1479
1480 filepath = os.path.join(indir, relfile)
1481 native_filepath = file_path.get_native_path_case(filepath)
1482 if filepath != native_filepath:
1483 # Special case './'.
1484 if filepath != native_filepath + '.' + os.path.sep:
1485 # Give up enforcing strict path case on OSX. Really, it's that sad. The
1486 # case where it happens is very specific and hard to reproduce:
1487 # get_native_path_case(
1488 # u'Foo.framework/Versions/A/Resources/Something.nib') will return
1489 # u'Foo.framework/Versions/A/resources/Something.nib', e.g. lowercase 'r'.
1490 #
1491 # Note that this is really something deep in OSX because running
1492 # ls Foo.framework/Versions/A
1493 # will print out 'Resources', while file_path.get_native_path_case()
1494 # returns a lower case 'r'.
1495 #
1496 # So *something* is happening under the hood resulting in the command 'ls'
1497 # and Carbon.File.FSPathMakeRef('path').FSRefMakePath() to disagree. We
1498 # have no idea why.
1499 if sys.platform != 'darwin':
1500 raise MappingError(
1501 'File path doesn\'t equal native file path\n%s != %s' %
1502 (filepath, native_filepath))
1503
1504 symlinks = []
1505 if follow_symlinks:
1506 relfile, symlinks = expand_symlinks(indir, relfile)
1507
1508 if relfile.endswith(os.path.sep):
1509 if not os.path.isdir(infile):
1510 raise MappingError(
1511 '%s is not a directory but ends with "%s"' % (infile, os.path.sep))
1512
1513 # Special case './'.
1514 if relfile.startswith('.' + os.path.sep):
1515 relfile = relfile[2:]
1516 outfiles = symlinks
1517 try:
1518 for filename in os.listdir(infile):
1519 inner_relfile = os.path.join(relfile, filename)
1520 if blacklist and blacklist(inner_relfile):
1521 continue
1522 if os.path.isdir(os.path.join(indir, inner_relfile)):
1523 inner_relfile += os.path.sep
1524 outfiles.extend(
1525 expand_directory_and_symlink(indir, inner_relfile, blacklist,
1526 follow_symlinks))
1527 return outfiles
1528 except OSError as e:
1529 raise MappingError(
1530 'Unable to iterate over directory %s.\n%s' % (infile, e))
1531 else:
1532 # Always add individual files even if they were blacklisted.
1533 if os.path.isdir(infile):
1534 raise MappingError(
1535 'Input directory %s must have a trailing slash' % infile)
1536
1537 if not os.path.isfile(infile):
1538 raise MappingError('Input file %s doesn\'t exist' % infile)
1539
1540 return symlinks + [relfile]
1541
1542
Marc-Antoine Ruel05199462014-03-13 15:40:48 -04001543def process_input(filepath, prevdict, read_only, algo):
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05001544 """Processes an input file, a dependency, and return meta data about it.
1545
1546 Behaviors:
1547 - Retrieves the file mode, file size, file timestamp, file link
1548 destination if it is a file link and calcultate the SHA-1 of the file's
1549 content if the path points to a file and not a symlink.
1550
1551 Arguments:
1552 filepath: File to act on.
1553 prevdict: the previous dictionary. It is used to retrieve the cached sha-1
1554 to skip recalculating the hash. Optional.
Marc-Antoine Ruel7124e392014-01-09 11:49:21 -05001555 read_only: If 1 or 2, the file mode is manipulated. In practice, only save
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05001556 one of 4 modes: 0755 (rwx), 0644 (rw), 0555 (rx), 0444 (r). On
1557 windows, mode is not set since all files are 'executable' by
1558 default.
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05001559 algo: Hashing algorithm used.
1560
1561 Returns:
1562 The necessary data to create a entry in the 'files' section of an .isolated
1563 file.
1564 """
1565 out = {}
1566 # TODO(csharp): Fix crbug.com/150823 and enable the touched logic again.
1567 # if prevdict.get('T') == True:
1568 # # The file's content is ignored. Skip the time and hard code mode.
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05001569 # out['s'] = 0
1570 # out['h'] = algo().hexdigest()
1571 # out['T'] = True
1572 # return out
1573
1574 # Always check the file stat and check if it is a link. The timestamp is used
1575 # to know if the file's content/symlink destination should be looked into.
1576 # E.g. only reuse from prevdict if the timestamp hasn't changed.
1577 # There is the risk of the file's timestamp being reset to its last value
1578 # manually while its content changed. We don't protect against that use case.
1579 try:
1580 filestats = os.lstat(filepath)
1581 except OSError:
1582 # The file is not present.
1583 raise MappingError('%s is missing' % filepath)
1584 is_link = stat.S_ISLNK(filestats.st_mode)
1585
Marc-Antoine Ruel05199462014-03-13 15:40:48 -04001586 if sys.platform != 'win32':
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05001587 # Ignore file mode on Windows since it's not really useful there.
1588 filemode = stat.S_IMODE(filestats.st_mode)
1589 # Remove write access for group and all access to 'others'.
1590 filemode &= ~(stat.S_IWGRP | stat.S_IRWXO)
1591 if read_only:
1592 filemode &= ~stat.S_IWUSR
1593 if filemode & stat.S_IXUSR:
1594 filemode |= stat.S_IXGRP
1595 else:
1596 filemode &= ~stat.S_IXGRP
1597 if not is_link:
1598 out['m'] = filemode
1599
1600 # Used to skip recalculating the hash or link destination. Use the most recent
1601 # update time.
1602 # TODO(maruel): Save it in the .state file instead of .isolated so the
1603 # .isolated file is deterministic.
1604 out['t'] = int(round(filestats.st_mtime))
1605
1606 if not is_link:
1607 out['s'] = filestats.st_size
1608 # If the timestamp wasn't updated and the file size is still the same, carry
1609 # on the sha-1.
1610 if (prevdict.get('t') == out['t'] and
1611 prevdict.get('s') == out['s']):
1612 # Reuse the previous hash if available.
1613 out['h'] = prevdict.get('h')
1614 if not out.get('h'):
1615 out['h'] = hash_file(filepath, algo)
1616 else:
1617 # If the timestamp wasn't updated, carry on the link destination.
1618 if prevdict.get('t') == out['t']:
1619 # Reuse the previous link destination if available.
1620 out['l'] = prevdict.get('l')
1621 if out.get('l') is None:
1622 # The link could be in an incorrect path case. In practice, this only
1623 # happen on OSX on case insensitive HFS.
1624 # TODO(maruel): It'd be better if it was only done once, in
1625 # expand_directory_and_symlink(), so it would not be necessary to do again
1626 # here.
1627 symlink_value = os.readlink(filepath) # pylint: disable=E1101
1628 filedir = file_path.get_native_path_case(os.path.dirname(filepath))
1629 native_dest = file_path.fix_native_path_case(filedir, symlink_value)
1630 out['l'] = os.path.relpath(native_dest, filedir)
1631 return out
1632
1633
1634def save_isolated(isolated, data):
1635 """Writes one or multiple .isolated files.
1636
1637 Note: this reference implementation does not create child .isolated file so it
1638 always returns an empty list.
1639
1640 Returns the list of child isolated files that are included by |isolated|.
1641 """
1642 # Make sure the data is valid .isolated data by 'reloading' it.
1643 algo = SUPPORTED_ALGOS[data['algo']]
Marc-Antoine Ruel05199462014-03-13 15:40:48 -04001644 load_isolated(json.dumps(data), algo)
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05001645 tools.write_json(isolated, data, True)
1646 return []
1647
1648
maruel@chromium.org7b844a62013-09-17 13:04:59 +00001649def upload_tree(base_url, indir, infiles, namespace):
maruel@chromium.orgc6f90062012-11-07 18:32:22 +00001650 """Uploads the given tree to the given url.
1651
1652 Arguments:
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +00001653 base_url: The base url, it is assume that |base_url|/has/ can be used to
1654 query if an element was already uploaded, and |base_url|/store/
1655 can be used to upload a new element.
1656 indir: Root directory the infiles are based in.
vadimsh@chromium.orgbcb966b2013-10-01 18:14:18 +00001657 infiles: dict of files to upload from |indir| to |base_url|.
csharp@chromium.org59c7bcf2012-11-21 21:13:18 +00001658 namespace: The namespace to use on the server.
maruel@chromium.orgc6f90062012-11-07 18:32:22 +00001659 """
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001660 logging.info('upload_tree(indir=%s, files=%d)', indir, len(infiles))
1661
1662 # Convert |indir| + |infiles| into a list of FileItem objects.
1663 # Filter out symlinks, since they are not represented by items on isolate
1664 # server side.
1665 items = [
1666 FileItem(
1667 path=os.path.join(indir, filepath),
1668 digest=metadata['h'],
1669 size=metadata['s'],
1670 high_priority=metadata.get('priority') == '0')
1671 for filepath, metadata in infiles.iteritems()
1672 if 'l' not in metadata
1673 ]
1674
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00001675 with get_storage(base_url, namespace) as storage:
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001676 storage.upload_items(items)
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +00001677 return 0
maruel@chromium.orgc6f90062012-11-07 18:32:22 +00001678
1679
Marc-Antoine Ruel05199462014-03-13 15:40:48 -04001680def load_isolated(content, algo):
maruel@chromium.org41601642013-09-18 19:40:46 +00001681 """Verifies the .isolated file is valid and loads this object with the json
1682 data.
maruel@chromium.org385d73d2013-09-19 18:33:21 +00001683
1684 Arguments:
1685 - content: raw serialized content to load.
maruel@chromium.org385d73d2013-09-19 18:33:21 +00001686 - algo: hashlib algorithm class. Used to confirm the algorithm matches the
1687 algorithm used on the Isolate Server.
maruel@chromium.org41601642013-09-18 19:40:46 +00001688 """
1689 try:
1690 data = json.loads(content)
1691 except ValueError:
1692 raise ConfigError('Failed to parse: %s...' % content[:100])
1693
1694 if not isinstance(data, dict):
1695 raise ConfigError('Expected dict, got %r' % data)
1696
maruel@chromium.org385d73d2013-09-19 18:33:21 +00001697 # Check 'version' first, since it could modify the parsing after.
Marc-Antoine Ruel05199462014-03-13 15:40:48 -04001698 value = data.get('version', '1.0')
maruel@chromium.org385d73d2013-09-19 18:33:21 +00001699 if not isinstance(value, basestring):
1700 raise ConfigError('Expected string, got %r' % value)
Marc-Antoine Ruel05199462014-03-13 15:40:48 -04001701 try:
1702 version = tuple(map(int, value.split('.')))
1703 except ValueError:
1704 raise ConfigError('Expected valid version, got %r' % value)
1705
1706 expected_version = tuple(map(int, ISOLATED_FILE_VERSION.split('.')))
1707 # Major version must match.
1708 if version[0] != expected_version[0]:
Marc-Antoine Ruel1c1edd62013-12-06 09:13:13 -05001709 raise ConfigError(
1710 'Expected compatible \'%s\' version, got %r' %
1711 (ISOLATED_FILE_VERSION, value))
maruel@chromium.org385d73d2013-09-19 18:33:21 +00001712
1713 if algo is None:
Marc-Antoine Ruelac54cb42013-11-18 14:05:35 -05001714 # TODO(maruel): Remove the default around Jan 2014.
maruel@chromium.org385d73d2013-09-19 18:33:21 +00001715 # Default the algorithm used in the .isolated file itself, falls back to
1716 # 'sha-1' if unspecified.
1717 algo = SUPPORTED_ALGOS_REVERSE[data.get('algo', 'sha-1')]
1718
maruel@chromium.org41601642013-09-18 19:40:46 +00001719 for key, value in data.iteritems():
maruel@chromium.org385d73d2013-09-19 18:33:21 +00001720 if key == 'algo':
1721 if not isinstance(value, basestring):
1722 raise ConfigError('Expected string, got %r' % value)
1723 if value not in SUPPORTED_ALGOS:
1724 raise ConfigError(
1725 'Expected one of \'%s\', got %r' %
1726 (', '.join(sorted(SUPPORTED_ALGOS)), value))
1727 if value != SUPPORTED_ALGOS_REVERSE[algo]:
1728 raise ConfigError(
1729 'Expected \'%s\', got %r' % (SUPPORTED_ALGOS_REVERSE[algo], value))
1730
1731 elif key == 'command':
maruel@chromium.org41601642013-09-18 19:40:46 +00001732 if not isinstance(value, list):
1733 raise ConfigError('Expected list, got %r' % value)
1734 if not value:
1735 raise ConfigError('Expected non-empty command')
1736 for subvalue in value:
1737 if not isinstance(subvalue, basestring):
1738 raise ConfigError('Expected string, got %r' % subvalue)
1739
1740 elif key == 'files':
1741 if not isinstance(value, dict):
1742 raise ConfigError('Expected dict, got %r' % value)
1743 for subkey, subvalue in value.iteritems():
1744 if not isinstance(subkey, basestring):
1745 raise ConfigError('Expected string, got %r' % subkey)
1746 if not isinstance(subvalue, dict):
1747 raise ConfigError('Expected dict, got %r' % subvalue)
1748 for subsubkey, subsubvalue in subvalue.iteritems():
1749 if subsubkey == 'l':
1750 if not isinstance(subsubvalue, basestring):
1751 raise ConfigError('Expected string, got %r' % subsubvalue)
1752 elif subsubkey == 'm':
1753 if not isinstance(subsubvalue, int):
1754 raise ConfigError('Expected int, got %r' % subsubvalue)
1755 elif subsubkey == 'h':
1756 if not is_valid_hash(subsubvalue, algo):
1757 raise ConfigError('Expected sha-1, got %r' % subsubvalue)
1758 elif subsubkey == 's':
Marc-Antoine Ruelaab3a622013-11-28 09:47:05 -05001759 if not isinstance(subsubvalue, (int, long)):
1760 raise ConfigError('Expected int or long, got %r' % subsubvalue)
maruel@chromium.org41601642013-09-18 19:40:46 +00001761 else:
1762 raise ConfigError('Unknown subsubkey %s' % subsubkey)
maruel@chromium.org4f2ebe42013-09-19 13:09:08 +00001763 if bool('h' in subvalue) == bool('l' in subvalue):
maruel@chromium.org41601642013-09-18 19:40:46 +00001764 raise ConfigError(
maruel@chromium.org4f2ebe42013-09-19 13:09:08 +00001765 'Need only one of \'h\' (sha-1) or \'l\' (link), got: %r' %
1766 subvalue)
1767 if bool('h' in subvalue) != bool('s' in subvalue):
1768 raise ConfigError(
1769 'Both \'h\' (sha-1) and \'s\' (size) should be set, got: %r' %
1770 subvalue)
1771 if bool('s' in subvalue) == bool('l' in subvalue):
1772 raise ConfigError(
1773 'Need only one of \'s\' (size) or \'l\' (link), got: %r' %
1774 subvalue)
1775 if bool('l' in subvalue) and bool('m' in subvalue):
1776 raise ConfigError(
1777 'Cannot use \'m\' (mode) and \'l\' (link), got: %r' %
maruel@chromium.org41601642013-09-18 19:40:46 +00001778 subvalue)
1779
1780 elif key == 'includes':
1781 if not isinstance(value, list):
1782 raise ConfigError('Expected list, got %r' % value)
1783 if not value:
1784 raise ConfigError('Expected non-empty includes list')
1785 for subvalue in value:
1786 if not is_valid_hash(subvalue, algo):
1787 raise ConfigError('Expected sha-1, got %r' % subvalue)
1788
Marc-Antoine Ruel05199462014-03-13 15:40:48 -04001789 elif key == 'os':
1790 if version >= (1, 4):
1791 raise ConfigError('Key \'os\' is not allowed starting version 1.4')
1792
maruel@chromium.org41601642013-09-18 19:40:46 +00001793 elif key == 'read_only':
Marc-Antoine Ruel7124e392014-01-09 11:49:21 -05001794 if not value in (0, 1, 2):
1795 raise ConfigError('Expected 0, 1 or 2, got %r' % value)
maruel@chromium.org41601642013-09-18 19:40:46 +00001796
1797 elif key == 'relative_cwd':
1798 if not isinstance(value, basestring):
1799 raise ConfigError('Expected string, got %r' % value)
1800
maruel@chromium.org385d73d2013-09-19 18:33:21 +00001801 elif key == 'version':
1802 # Already checked above.
1803 pass
1804
maruel@chromium.org41601642013-09-18 19:40:46 +00001805 else:
maruel@chromium.org385d73d2013-09-19 18:33:21 +00001806 raise ConfigError('Unknown key %r' % key)
maruel@chromium.org41601642013-09-18 19:40:46 +00001807
maruel@chromium.org4f2ebe42013-09-19 13:09:08 +00001808 # Automatically fix os.path.sep if necessary. While .isolated files are always
1809 # in the the native path format, someone could want to download an .isolated
1810 # tree from another OS.
1811 wrong_path_sep = '/' if os.path.sep == '\\' else '\\'
1812 if 'files' in data:
1813 data['files'] = dict(
1814 (k.replace(wrong_path_sep, os.path.sep), v)
1815 for k, v in data['files'].iteritems())
1816 for v in data['files'].itervalues():
1817 if 'l' in v:
1818 v['l'] = v['l'].replace(wrong_path_sep, os.path.sep)
1819 if 'relative_cwd' in data:
1820 data['relative_cwd'] = data['relative_cwd'].replace(
1821 wrong_path_sep, os.path.sep)
maruel@chromium.org41601642013-09-18 19:40:46 +00001822 return data
1823
1824
1825class IsolatedFile(object):
1826 """Represents a single parsed .isolated file."""
1827 def __init__(self, obj_hash, algo):
1828 """|obj_hash| is really the sha-1 of the file."""
1829 logging.debug('IsolatedFile(%s)' % obj_hash)
1830 self.obj_hash = obj_hash
1831 self.algo = algo
1832 # Set once all the left-side of the tree is parsed. 'Tree' here means the
1833 # .isolate and all the .isolated files recursively included by it with
1834 # 'includes' key. The order of each sha-1 in 'includes', each representing a
1835 # .isolated file in the hash table, is important, as the later ones are not
1836 # processed until the firsts are retrieved and read.
1837 self.can_fetch = False
1838
1839 # Raw data.
1840 self.data = {}
1841 # A IsolatedFile instance, one per object in self.includes.
1842 self.children = []
1843
1844 # Set once the .isolated file is loaded.
1845 self._is_parsed = False
1846 # Set once the files are fetched.
1847 self.files_fetched = False
1848
Marc-Antoine Ruel05199462014-03-13 15:40:48 -04001849 def load(self, content):
maruel@chromium.org41601642013-09-18 19:40:46 +00001850 """Verifies the .isolated file is valid and loads this object with the json
1851 data.
1852 """
1853 logging.debug('IsolatedFile.load(%s)' % self.obj_hash)
1854 assert not self._is_parsed
Marc-Antoine Ruel05199462014-03-13 15:40:48 -04001855 self.data = load_isolated(content, self.algo)
maruel@chromium.org41601642013-09-18 19:40:46 +00001856 self.children = [
1857 IsolatedFile(i, self.algo) for i in self.data.get('includes', [])
1858 ]
1859 self._is_parsed = True
1860
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00001861 def fetch_files(self, fetch_queue, files):
maruel@chromium.org41601642013-09-18 19:40:46 +00001862 """Adds files in this .isolated file not present in |files| dictionary.
1863
1864 Preemptively request files.
1865
1866 Note that |files| is modified by this function.
1867 """
1868 assert self.can_fetch
1869 if not self._is_parsed or self.files_fetched:
1870 return
1871 logging.debug('fetch_files(%s)' % self.obj_hash)
1872 for filepath, properties in self.data.get('files', {}).iteritems():
1873 # Root isolated has priority on the files being mapped. In particular,
1874 # overriden files must not be fetched.
1875 if filepath not in files:
1876 files[filepath] = properties
1877 if 'h' in properties:
1878 # Preemptively request files.
1879 logging.debug('fetching %s' % filepath)
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001880 fetch_queue.add(properties['h'], properties['s'], WorkerPool.MED)
maruel@chromium.org41601642013-09-18 19:40:46 +00001881 self.files_fetched = True
1882
1883
1884class Settings(object):
1885 """Results of a completely parsed .isolated file."""
1886 def __init__(self):
1887 self.command = []
1888 self.files = {}
1889 self.read_only = None
1890 self.relative_cwd = None
1891 # The main .isolated file, a IsolatedFile instance.
1892 self.root = None
1893
Marc-Antoine Ruel05199462014-03-13 15:40:48 -04001894 def load(self, fetch_queue, root_isolated_hash, algo):
maruel@chromium.org41601642013-09-18 19:40:46 +00001895 """Loads the .isolated and all the included .isolated asynchronously.
1896
1897 It enables support for "included" .isolated files. They are processed in
1898 strict order but fetched asynchronously from the cache. This is important so
1899 that a file in an included .isolated file that is overridden by an embedding
1900 .isolated file is not fetched needlessly. The includes are fetched in one
1901 pass and the files are fetched as soon as all the ones on the left-side
1902 of the tree were fetched.
1903
1904 The prioritization is very important here for nested .isolated files.
1905 'includes' have the highest priority and the algorithm is optimized for both
1906 deep and wide trees. A deep one is a long link of .isolated files referenced
1907 one at a time by one item in 'includes'. A wide one has a large number of
1908 'includes' in a single .isolated file. 'left' is defined as an included
1909 .isolated file earlier in the 'includes' list. So the order of the elements
1910 in 'includes' is important.
1911 """
1912 self.root = IsolatedFile(root_isolated_hash, algo)
1913
1914 # Isolated files being retrieved now: hash -> IsolatedFile instance.
1915 pending = {}
1916 # Set of hashes of already retrieved items to refuse recursive includes.
1917 seen = set()
1918
1919 def retrieve(isolated_file):
1920 h = isolated_file.obj_hash
1921 if h in seen:
1922 raise ConfigError('IsolatedFile %s is retrieved recursively' % h)
1923 assert h not in pending
1924 seen.add(h)
1925 pending[h] = isolated_file
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08001926 fetch_queue.add(h, priority=WorkerPool.HIGH)
maruel@chromium.org41601642013-09-18 19:40:46 +00001927
1928 retrieve(self.root)
1929
1930 while pending:
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00001931 item_hash = fetch_queue.wait(pending)
maruel@chromium.org41601642013-09-18 19:40:46 +00001932 item = pending.pop(item_hash)
Marc-Antoine Ruel05199462014-03-13 15:40:48 -04001933 item.load(fetch_queue.cache.read(item_hash))
maruel@chromium.org41601642013-09-18 19:40:46 +00001934 if item_hash == root_isolated_hash:
1935 # It's the root item.
1936 item.can_fetch = True
1937
1938 for new_child in item.children:
1939 retrieve(new_child)
1940
1941 # Traverse the whole tree to see if files can now be fetched.
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00001942 self._traverse_tree(fetch_queue, self.root)
maruel@chromium.org41601642013-09-18 19:40:46 +00001943
1944 def check(n):
1945 return all(check(x) for x in n.children) and n.files_fetched
1946 assert check(self.root)
1947
1948 self.relative_cwd = self.relative_cwd or ''
maruel@chromium.org41601642013-09-18 19:40:46 +00001949
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00001950 def _traverse_tree(self, fetch_queue, node):
maruel@chromium.org41601642013-09-18 19:40:46 +00001951 if node.can_fetch:
1952 if not node.files_fetched:
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00001953 self._update_self(fetch_queue, node)
maruel@chromium.org41601642013-09-18 19:40:46 +00001954 will_break = False
1955 for i in node.children:
1956 if not i.can_fetch:
1957 if will_break:
1958 break
1959 # Automatically mark the first one as fetcheable.
1960 i.can_fetch = True
1961 will_break = True
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00001962 self._traverse_tree(fetch_queue, i)
maruel@chromium.org41601642013-09-18 19:40:46 +00001963
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00001964 def _update_self(self, fetch_queue, node):
1965 node.fetch_files(fetch_queue, self.files)
maruel@chromium.org41601642013-09-18 19:40:46 +00001966 # Grabs properties.
1967 if not self.command and node.data.get('command'):
maruel@chromium.org4f2ebe42013-09-19 13:09:08 +00001968 # Ensure paths are correctly separated on windows.
maruel@chromium.org41601642013-09-18 19:40:46 +00001969 self.command = node.data['command']
maruel@chromium.org4f2ebe42013-09-19 13:09:08 +00001970 if self.command:
1971 self.command[0] = self.command[0].replace('/', os.path.sep)
1972 self.command = tools.fix_python_path(self.command)
maruel@chromium.org41601642013-09-18 19:40:46 +00001973 if self.read_only is None and node.data.get('read_only') is not None:
1974 self.read_only = node.data['read_only']
1975 if (self.relative_cwd is None and
1976 node.data.get('relative_cwd') is not None):
1977 self.relative_cwd = node.data['relative_cwd']
1978
1979
Vadim Shtayurae0ab1902014-04-29 10:55:27 -07001980def fetch_isolated(isolated_hash, storage, cache, outdir, require_command):
maruel@chromium.org4f2ebe42013-09-19 13:09:08 +00001981 """Aggressively downloads the .isolated file(s), then download all the files.
maruel@chromium.org4f2ebe42013-09-19 13:09:08 +00001982
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00001983 Arguments:
1984 isolated_hash: hash of the root *.isolated file.
1985 storage: Storage class that communicates with isolate storage.
1986 cache: LocalCache class that knows how to store and map files locally.
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00001987 outdir: Output directory to map file tree to.
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00001988 require_command: Ensure *.isolated specifies a command to run.
1989
1990 Returns:
1991 Settings object that holds details about loaded *.isolated file.
1992 """
Vadim Shtayurae0ab1902014-04-29 10:55:27 -07001993 # Hash algorithm to use, defined by namespace |storage| is using.
1994 algo = storage.hash_algo
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00001995 with cache:
1996 fetch_queue = FetchQueue(storage, cache)
1997 settings = Settings()
1998
1999 with tools.Profiler('GetIsolateds'):
2000 # Optionally support local files by manually adding them to cache.
2001 if not is_valid_hash(isolated_hash, algo):
2002 isolated_hash = fetch_queue.inject_local_file(isolated_hash, algo)
2003
2004 # Load all *.isolated and start loading rest of the files.
Marc-Antoine Ruel05199462014-03-13 15:40:48 -04002005 settings.load(fetch_queue, isolated_hash, algo)
maruel@chromium.org4f2ebe42013-09-19 13:09:08 +00002006 if require_command and not settings.command:
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00002007 # TODO(vadimsh): All fetch operations are already enqueue and there's no
2008 # easy way to cancel them.
maruel@chromium.org4f2ebe42013-09-19 13:09:08 +00002009 raise ConfigError('No command to run')
2010
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00002011 with tools.Profiler('GetRest'):
2012 # Create file system hierarchy.
2013 if not os.path.isdir(outdir):
2014 os.makedirs(outdir)
2015 create_directories(outdir, settings.files)
Marc-Antoine Ruelccafe0e2013-11-08 16:15:36 -05002016 create_symlinks(outdir, settings.files.iteritems())
maruel@chromium.org4f2ebe42013-09-19 13:09:08 +00002017
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00002018 # Ensure working directory exists.
2019 cwd = os.path.normpath(os.path.join(outdir, settings.relative_cwd))
2020 if not os.path.isdir(cwd):
2021 os.makedirs(cwd)
maruel@chromium.org4f2ebe42013-09-19 13:09:08 +00002022
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00002023 # Multimap: digest -> list of pairs (path, props).
2024 remaining = {}
2025 for filepath, props in settings.files.iteritems():
2026 if 'h' in props:
2027 remaining.setdefault(props['h'], []).append((filepath, props))
maruel@chromium.org4f2ebe42013-09-19 13:09:08 +00002028
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00002029 # Now block on the remaining files to be downloaded and mapped.
2030 logging.info('Retrieving remaining files (%d of them)...',
2031 fetch_queue.pending_count)
2032 last_update = time.time()
2033 with threading_utils.DeadlockDetector(DEADLOCK_TIMEOUT) as detector:
2034 while remaining:
2035 detector.ping()
2036
2037 # Wait for any item to finish fetching to cache.
2038 digest = fetch_queue.wait(remaining)
2039
2040 # Link corresponding files to a fetched item in cache.
2041 for filepath, props in remaining.pop(digest):
Marc-Antoine Ruelfb199cf2013-11-12 15:38:12 -05002042 cache.hardlink(
2043 digest, os.path.join(outdir, filepath), props.get('m'))
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00002044
2045 # Report progress.
2046 duration = time.time() - last_update
2047 if duration > DELAY_BETWEEN_UPDATES_IN_SECS:
2048 msg = '%d files remaining...' % len(remaining)
2049 print msg
2050 logging.info(msg)
2051 last_update = time.time()
2052
2053 # Cache could evict some items we just tried to fetch, it's a fatal error.
2054 if not fetch_queue.verify_all_cached():
2055 raise MappingError('Cache is too small to hold all requested files')
maruel@chromium.org4f2ebe42013-09-19 13:09:08 +00002056 return settings
2057
2058
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05002059def directory_to_metadata(root, algo, blacklist):
2060 """Returns the FileItem list and .isolated metadata for a directory."""
2061 root = file_path.get_native_path_case(root)
2062 metadata = dict(
Marc-Antoine Ruel05199462014-03-13 15:40:48 -04002063 (relpath, process_input(os.path.join(root, relpath), {}, False, algo))
2064 for relpath in expand_directory_and_symlink(root, './', blacklist, True)
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05002065 )
2066 for v in metadata.itervalues():
2067 v.pop('t')
2068 items = [
2069 FileItem(
2070 path=os.path.join(root, relpath),
2071 digest=meta['h'],
2072 size=meta['s'],
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08002073 high_priority=relpath.endswith('.isolated'))
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05002074 for relpath, meta in metadata.iteritems() if 'h' in meta
2075 ]
2076 return items, metadata
2077
2078
Vadim Shtayurae0ab1902014-04-29 10:55:27 -07002079def archive_files_to_storage(storage, files, blacklist):
Marc-Antoine Ruel2283ad12014-02-09 11:14:57 -05002080 """Stores every entries and returns the relevant data.
2081
2082 Arguments:
2083 storage: a Storage object that communicates with the remote object store.
Marc-Antoine Ruel2283ad12014-02-09 11:14:57 -05002084 files: list of file paths to upload. If a directory is specified, a
2085 .isolated file is created and its hash is returned.
2086 blacklist: function that returns True if a file should be omitted.
2087 """
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05002088 assert all(isinstance(i, unicode) for i in files), files
2089 if len(files) != len(set(map(os.path.abspath, files))):
2090 raise Error('Duplicate entries found.')
2091
2092 results = []
2093 # The temporary directory is only created as needed.
2094 tempdir = None
2095 try:
2096 # TODO(maruel): Yield the files to a worker thread.
2097 items_to_upload = []
2098 for f in files:
2099 try:
2100 filepath = os.path.abspath(f)
2101 if os.path.isdir(filepath):
2102 # Uploading a whole directory.
Vadim Shtayurae0ab1902014-04-29 10:55:27 -07002103 items, metadata = directory_to_metadata(
2104 filepath, storage.hash_algo, blacklist)
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05002105
2106 # Create the .isolated file.
2107 if not tempdir:
2108 tempdir = tempfile.mkdtemp(prefix='isolateserver')
2109 handle, isolated = tempfile.mkstemp(dir=tempdir, suffix='.isolated')
2110 os.close(handle)
2111 data = {
Vadim Shtayurae0ab1902014-04-29 10:55:27 -07002112 'algo': SUPPORTED_ALGOS_REVERSE[storage.hash_algo],
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05002113 'files': metadata,
Marc-Antoine Ruel1c1edd62013-12-06 09:13:13 -05002114 'version': ISOLATED_FILE_VERSION,
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05002115 }
2116 save_isolated(isolated, data)
Vadim Shtayurae0ab1902014-04-29 10:55:27 -07002117 h = hash_file(isolated, storage.hash_algo)
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05002118 items_to_upload.extend(items)
2119 items_to_upload.append(
2120 FileItem(
2121 path=isolated,
2122 digest=h,
2123 size=os.stat(isolated).st_size,
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08002124 high_priority=True))
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05002125 results.append((h, f))
2126
2127 elif os.path.isfile(filepath):
Vadim Shtayurae0ab1902014-04-29 10:55:27 -07002128 h = hash_file(filepath, storage.hash_algo)
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05002129 items_to_upload.append(
2130 FileItem(
2131 path=filepath,
2132 digest=h,
2133 size=os.stat(filepath).st_size,
Vadim Shtayurabcff74f2014-02-27 16:19:34 -08002134 high_priority=f.endswith('.isolated')))
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05002135 results.append((h, f))
2136 else:
2137 raise Error('%s is neither a file or directory.' % f)
2138 except OSError:
2139 raise Error('Failed to process %s.' % f)
Marc-Antoine Ruel2283ad12014-02-09 11:14:57 -05002140 # Technically we would care about which files were uploaded but we don't
2141 # much in practice.
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05002142 _uploaded_files = storage.upload_items(items_to_upload)
2143 return results
2144 finally:
2145 if tempdir:
2146 shutil.rmtree(tempdir)
2147
2148
Marc-Antoine Ruel488ce8f2014-02-09 11:25:04 -05002149def archive(out, namespace, files, blacklist):
2150 if files == ['-']:
2151 files = sys.stdin.readlines()
2152
2153 if not files:
2154 raise Error('Nothing to upload')
2155
2156 files = [f.decode('utf-8') for f in files]
Marc-Antoine Ruel488ce8f2014-02-09 11:25:04 -05002157 blacklist = tools.gen_blacklist(blacklist)
2158 with get_storage(out, namespace) as storage:
Vadim Shtayurae0ab1902014-04-29 10:55:27 -07002159 results = archive_files_to_storage(storage, files, blacklist)
Marc-Antoine Ruel488ce8f2014-02-09 11:25:04 -05002160 print('\n'.join('%s %s' % (r[0], r[1]) for r in results))
2161
2162
maruel@chromium.orgfb78d432013-08-28 21:22:40 +00002163@subcommand.usage('<file1..fileN> or - to read from stdin')
2164def CMDarchive(parser, args):
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05002165 """Archives data to the server.
2166
2167 If a directory is specified, a .isolated file is created the whole directory
2168 is uploaded. Then this .isolated file can be included in another one to run
2169 commands.
2170
2171 The commands output each file that was processed with its content hash. For
2172 directories, the .isolated generated for the directory is listed as the
2173 directory entry itself.
2174 """
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -05002175 add_isolate_server_options(parser, False)
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05002176 parser.add_option(
2177 '--blacklist',
2178 action='append', default=list(DEFAULT_BLACKLIST),
2179 help='List of regexp to use as blacklist filter when uploading '
2180 'directories')
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +00002181 options, files = parser.parse_args(args)
Marc-Antoine Ruel488ce8f2014-02-09 11:25:04 -05002182 process_isolate_server_options(parser, options)
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05002183 try:
Marc-Antoine Ruel488ce8f2014-02-09 11:25:04 -05002184 archive(options.isolate_server, options.namespace, files, options.blacklist)
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05002185 except Error as e:
2186 parser.error(e.args[0])
Marc-Antoine Ruelfcc3cd82013-11-19 16:31:38 -05002187 return 0
maruel@chromium.orgfb78d432013-08-28 21:22:40 +00002188
2189
2190def CMDdownload(parser, args):
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +00002191 """Download data from the server.
2192
maruel@chromium.org4f2ebe42013-09-19 13:09:08 +00002193 It can either download individual files or a complete tree from a .isolated
2194 file.
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +00002195 """
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -05002196 add_isolate_server_options(parser, True)
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +00002197 parser.add_option(
maruel@chromium.org4f2ebe42013-09-19 13:09:08 +00002198 '-i', '--isolated', metavar='HASH',
2199 help='hash of an isolated file, .isolated file content is discarded, use '
2200 '--file if you need it')
2201 parser.add_option(
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +00002202 '-f', '--file', metavar='HASH DEST', default=[], action='append', nargs=2,
2203 help='hash and destination of a file, can be used multiple times')
2204 parser.add_option(
2205 '-t', '--target', metavar='DIR', default=os.getcwd(),
2206 help='destination directory')
2207 options, args = parser.parse_args(args)
Marc-Antoine Ruel488ce8f2014-02-09 11:25:04 -05002208 process_isolate_server_options(parser, options)
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +00002209 if args:
2210 parser.error('Unsupported arguments: %s' % args)
maruel@chromium.org4f2ebe42013-09-19 13:09:08 +00002211 if bool(options.isolated) == bool(options.file):
2212 parser.error('Use one of --isolated or --file, and only one.')
maruel@chromium.orgb7e79a22013-09-13 01:24:56 +00002213
2214 options.target = os.path.abspath(options.target)
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00002215
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -05002216 remote = options.isolate_server or options.indir
2217 with get_storage(remote, options.namespace) as storage:
Vadim Shtayura3172be52013-12-03 12:49:05 -08002218 # Fetching individual files.
2219 if options.file:
2220 channel = threading_utils.TaskChannel()
2221 pending = {}
2222 for digest, dest in options.file:
2223 pending[digest] = dest
2224 storage.async_fetch(
2225 channel,
2226 WorkerPool.MED,
2227 digest,
2228 UNKNOWN_FILE_SIZE,
2229 functools.partial(file_write, os.path.join(options.target, dest)))
2230 while pending:
2231 fetched = channel.pull()
2232 dest = pending.pop(fetched)
2233 logging.info('%s: %s', fetched, dest)
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00002234
Vadim Shtayura3172be52013-12-03 12:49:05 -08002235 # Fetching whole isolated tree.
2236 if options.isolated:
2237 settings = fetch_isolated(
2238 isolated_hash=options.isolated,
2239 storage=storage,
2240 cache=MemoryCache(),
Vadim Shtayura3172be52013-12-03 12:49:05 -08002241 outdir=options.target,
Vadim Shtayura3172be52013-12-03 12:49:05 -08002242 require_command=False)
2243 rel = os.path.join(options.target, settings.relative_cwd)
2244 print('To run this test please run from the directory %s:' %
2245 os.path.join(options.target, rel))
2246 print(' ' + ' '.join(settings.command))
vadimsh@chromium.org7b5dae32013-10-03 16:59:59 +00002247
maruel@chromium.orgfb78d432013-08-28 21:22:40 +00002248 return 0
2249
2250
Marc-Antoine Ruel488ce8f2014-02-09 11:25:04 -05002251@subcommand.usage('<file1..fileN> or - to read from stdin')
2252def CMDhashtable(parser, args):
2253 """Archives data to a hashtable on the file system.
2254
2255 If a directory is specified, a .isolated file is created the whole directory
2256 is uploaded. Then this .isolated file can be included in another one to run
2257 commands.
2258
2259 The commands output each file that was processed with its content hash. For
2260 directories, the .isolated generated for the directory is listed as the
2261 directory entry itself.
2262 """
2263 add_outdir_options(parser)
2264 parser.add_option(
2265 '--blacklist',
2266 action='append', default=list(DEFAULT_BLACKLIST),
2267 help='List of regexp to use as blacklist filter when uploading '
2268 'directories')
2269 options, files = parser.parse_args(args)
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -05002270 process_outdir_options(parser, options, os.getcwd())
Marc-Antoine Ruel488ce8f2014-02-09 11:25:04 -05002271 try:
2272 # Do not compress files when archiving to the file system.
2273 archive(options.outdir, 'default', files, options.blacklist)
2274 except Error as e:
2275 parser.error(e.args[0])
2276 return 0
2277
2278
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -05002279def add_isolate_server_options(parser, add_indir):
2280 """Adds --isolate-server and --namespace options to parser.
2281
2282 Includes --indir if desired.
2283 """
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -05002284 parser.add_option(
2285 '-I', '--isolate-server',
2286 metavar='URL', default=os.environ.get('ISOLATE_SERVER', ''),
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -05002287 help='URL of the Isolate Server to use. Defaults to the environment '
2288 'variable ISOLATE_SERVER if set. No need to specify https://, this '
2289 'is assumed.')
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -05002290 parser.add_option(
2291 '--namespace', default='default-gzip',
2292 help='The namespace to use on the Isolate Server, default: %default')
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -05002293 if add_indir:
2294 parser.add_option(
2295 '--indir', metavar='DIR',
2296 help='Directory used to store the hashtable instead of using an '
2297 'isolate server.')
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -05002298
2299
2300def process_isolate_server_options(parser, options):
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -05002301 """Processes the --isolate-server and --indir options and aborts if neither is
2302 specified.
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -05002303 """
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -05002304 has_indir = hasattr(options, 'indir')
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -05002305 if not options.isolate_server:
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -05002306 if not has_indir:
2307 parser.error('--isolate-server is required.')
2308 elif not options.indir:
2309 parser.error('Use one of --indir or --isolate-server.')
2310 else:
2311 if has_indir and options.indir:
2312 parser.error('Use only one of --indir or --isolate-server.')
2313
2314 if options.isolate_server:
2315 parts = urlparse.urlparse(options.isolate_server, 'https')
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -05002316 if parts.query:
2317 parser.error('--isolate-server doesn\'t support query parameter.')
2318 if parts.fragment:
2319 parser.error('--isolate-server doesn\'t support fragment in the url.')
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -05002320 # urlparse('foo.com') will result in netloc='', path='foo.com', which is not
2321 # what is desired here.
2322 new = list(parts)
2323 if not new[1] and new[2]:
2324 new[1] = new[2].rstrip('/')
2325 new[2] = ''
2326 new[2] = new[2].rstrip('/')
2327 options.isolate_server = urlparse.urlunparse(new)
2328 return
2329
2330 if file_path.is_url(options.indir):
2331 parser.error('Can\'t use an URL for --indir.')
2332 options.indir = unicode(options.indir).replace('/', os.path.sep)
2333 options.indir = os.path.abspath(
2334 os.path.normpath(os.path.join(os.getcwd(), options.indir)))
2335 if not os.path.isdir(options.indir):
2336 parser.error('Path given to --indir must exist.')
2337
Marc-Antoine Ruel1687b5e2014-02-06 17:47:53 -05002338
2339
Marc-Antoine Ruel488ce8f2014-02-09 11:25:04 -05002340def add_outdir_options(parser):
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -05002341 """Adds --outdir, which is orthogonal to --isolate-server.
2342
2343 Note: On upload, separate commands are used between 'archive' and 'hashtable'.
2344 On 'download', the same command can download from either an isolate server or
2345 a file system.
2346 """
Marc-Antoine Ruel488ce8f2014-02-09 11:25:04 -05002347 parser.add_option(
2348 '-o', '--outdir', metavar='DIR',
2349 help='Directory used to recreate the tree.')
2350
2351
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -05002352def process_outdir_options(parser, options, cwd):
Marc-Antoine Ruel488ce8f2014-02-09 11:25:04 -05002353 if not options.outdir:
2354 parser.error('--outdir is required.')
2355 if file_path.is_url(options.outdir):
Marc-Antoine Ruel8806e622014-02-12 14:15:53 -05002356 parser.error('Can\'t use an URL for --outdir.')
Marc-Antoine Ruel488ce8f2014-02-09 11:25:04 -05002357 options.outdir = unicode(options.outdir).replace('/', os.path.sep)
2358 # outdir doesn't need native path case since tracing is never done from there.
2359 options.outdir = os.path.abspath(
2360 os.path.normpath(os.path.join(cwd, options.outdir)))
2361 # In theory, we'd create the directory outdir right away. Defer doing it in
2362 # case there's errors in the command line.
2363
2364
maruel@chromium.orgfb78d432013-08-28 21:22:40 +00002365class OptionParserIsolateServer(tools.OptionParserWithLogging):
2366 def __init__(self, **kwargs):
Marc-Antoine Ruelac54cb42013-11-18 14:05:35 -05002367 tools.OptionParserWithLogging.__init__(
2368 self,
2369 version=__version__,
2370 prog=os.path.basename(sys.modules[__name__].__file__),
2371 **kwargs)
Vadim Shtayurae34e13a2014-02-02 11:23:26 -08002372 auth.add_auth_options(self)
maruel@chromium.orgfb78d432013-08-28 21:22:40 +00002373
2374 def parse_args(self, *args, **kwargs):
2375 options, args = tools.OptionParserWithLogging.parse_args(
2376 self, *args, **kwargs)
Vadim Shtayura5d1efce2014-02-04 10:55:43 -08002377 auth.process_auth_options(self, options)
maruel@chromium.orgfb78d432013-08-28 21:22:40 +00002378 return options, args
2379
2380
2381def main(args):
2382 dispatcher = subcommand.CommandDispatcher(__name__)
2383 try:
Marc-Antoine Ruelac54cb42013-11-18 14:05:35 -05002384 return dispatcher.execute(OptionParserIsolateServer(), args)
vadimsh@chromium.orgd908a542013-10-30 01:36:17 +00002385 except Exception as e:
2386 tools.report_error(e)
maruel@chromium.orgfb78d432013-08-28 21:22:40 +00002387 return 1
maruel@chromium.orgc6f90062012-11-07 18:32:22 +00002388
2389
2390if __name__ == '__main__':
maruel@chromium.orgfb78d432013-08-28 21:22:40 +00002391 fix_encoding.fix_encoding()
2392 tools.disable_buffering()
2393 colorama.init()
maruel@chromium.orgcb3c3d52013-03-14 18:55:30 +00002394 sys.exit(main(sys.argv[1:]))