maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | # Copyright (c) 2012 The Chromium Authors. All rights reserved. |
| 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 6 | """Reads a .isolated, creates a tree of hardlinks and runs the test. |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 7 | |
| 8 | Keeps a local cache. |
| 9 | """ |
| 10 | |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 11 | import ctypes |
| 12 | import hashlib |
csharp@chromium.org | a110d79 | 2013-01-07 16:16:16 +0000 | [diff] [blame] | 13 | import httplib |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 14 | import json |
| 15 | import logging |
csharp@chromium.org | ff2a466 | 2012-11-21 20:49:32 +0000 | [diff] [blame] | 16 | import logging.handlers |
csharp@chromium.org | f13eec0 | 2013-03-11 18:22:56 +0000 | [diff] [blame] | 17 | import math |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 18 | import optparse |
| 19 | import os |
| 20 | import Queue |
csharp@chromium.org | f13eec0 | 2013-03-11 18:22:56 +0000 | [diff] [blame] | 21 | import random |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 22 | import re |
| 23 | import shutil |
| 24 | import stat |
| 25 | import subprocess |
| 26 | import sys |
| 27 | import tempfile |
| 28 | import threading |
| 29 | import time |
maruel@chromium.org | 97cd0be | 2013-03-13 14:01:36 +0000 | [diff] [blame] | 30 | import traceback |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 31 | import urllib |
csharp@chromium.org | a92403f | 2012-11-20 15:13:59 +0000 | [diff] [blame] | 32 | import urllib2 |
csharp@chromium.org | f13eec0 | 2013-03-11 18:22:56 +0000 | [diff] [blame] | 33 | import urlparse |
csharp@chromium.org | a92403f | 2012-11-20 15:13:59 +0000 | [diff] [blame] | 34 | import zlib |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 35 | |
| 36 | |
maruel@chromium.org | 6b365dc | 2012-10-18 19:17:56 +0000 | [diff] [blame] | 37 | # Types of action accepted by link_file(). |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 38 | HARDLINK, SYMLINK, COPY = range(1, 4) |
| 39 | |
| 40 | RE_IS_SHA1 = re.compile(r'^[a-fA-F0-9]{40}$') |
| 41 | |
csharp@chromium.org | 8dc5254 | 2012-11-08 20:29:55 +0000 | [diff] [blame] | 42 | # The file size to be used when we don't know the correct file size, |
| 43 | # generally used for .isolated files. |
| 44 | UNKNOWN_FILE_SIZE = None |
| 45 | |
csharp@chromium.org | a92403f | 2012-11-20 15:13:59 +0000 | [diff] [blame] | 46 | # The size of each chunk to read when downloading and unzipping files. |
| 47 | ZIPPED_FILE_CHUNK = 16 * 1024 |
| 48 | |
csharp@chromium.org | ff2a466 | 2012-11-21 20:49:32 +0000 | [diff] [blame] | 49 | # The name of the log file to use. |
| 50 | RUN_ISOLATED_LOG_FILE = 'run_isolated.log' |
| 51 | |
csharp@chromium.org | e217f30 | 2012-11-22 16:51:53 +0000 | [diff] [blame] | 52 | # The base directory containing this file. |
| 53 | BASE_DIR = os.path.dirname(os.path.abspath(__file__)) |
| 54 | |
| 55 | # The name of the log to use for the run_test_cases.py command |
| 56 | RUN_TEST_CASES_LOG = os.path.join(BASE_DIR, 'run_test_cases.log') |
| 57 | |
csharp@chromium.org | 9c59ff1 | 2012-12-12 02:32:29 +0000 | [diff] [blame] | 58 | # The delay (in seconds) to wait between logging statements when retrieving |
| 59 | # the required files. This is intended to let the user (or buildbot) know that |
| 60 | # the program is still running. |
| 61 | DELAY_BETWEEN_UPDATES_IN_SECS = 30 |
| 62 | |
csharp@chromium.org | f13eec0 | 2013-03-11 18:22:56 +0000 | [diff] [blame] | 63 | # The name of the key to store the count of url attempts. |
| 64 | COUNT_KEY = 'UrlOpenAttempt' |
| 65 | |
| 66 | # The maximum number of attempts to trying opening a url before aborting. |
| 67 | MAX_URL_OPEN_ATTEMPTS = 20 |
| 68 | |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 69 | |
| 70 | class ConfigError(ValueError): |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 71 | """Generic failure to load a .isolated file.""" |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 72 | pass |
| 73 | |
| 74 | |
| 75 | class MappingError(OSError): |
| 76 | """Failed to recreate the tree.""" |
| 77 | pass |
| 78 | |
| 79 | |
| 80 | def get_flavor(): |
| 81 | """Returns the system default flavor. Copied from gyp/pylib/gyp/common.py.""" |
| 82 | flavors = { |
| 83 | 'cygwin': 'win', |
| 84 | 'win32': 'win', |
| 85 | 'darwin': 'mac', |
| 86 | 'sunos5': 'solaris', |
| 87 | 'freebsd7': 'freebsd', |
| 88 | 'freebsd8': 'freebsd', |
| 89 | } |
| 90 | return flavors.get(sys.platform, 'linux') |
| 91 | |
| 92 | |
| 93 | def os_link(source, link_name): |
| 94 | """Add support for os.link() on Windows.""" |
| 95 | if sys.platform == 'win32': |
| 96 | if not ctypes.windll.kernel32.CreateHardLinkW( |
| 97 | unicode(link_name), unicode(source), 0): |
| 98 | raise OSError() |
| 99 | else: |
| 100 | os.link(source, link_name) |
| 101 | |
| 102 | |
| 103 | def readable_copy(outfile, infile): |
| 104 | """Makes a copy of the file that is readable by everyone.""" |
| 105 | shutil.copy(infile, outfile) |
| 106 | read_enabled_mode = (os.stat(outfile).st_mode | stat.S_IRUSR | |
| 107 | stat.S_IRGRP | stat.S_IROTH) |
| 108 | os.chmod(outfile, read_enabled_mode) |
| 109 | |
| 110 | |
| 111 | def link_file(outfile, infile, action): |
| 112 | """Links a file. The type of link depends on |action|.""" |
| 113 | logging.debug('Mapping %s to %s' % (infile, outfile)) |
| 114 | if action not in (HARDLINK, SYMLINK, COPY): |
| 115 | raise ValueError('Unknown mapping action %s' % action) |
| 116 | if not os.path.isfile(infile): |
| 117 | raise MappingError('%s is missing' % infile) |
| 118 | if os.path.isfile(outfile): |
| 119 | raise MappingError( |
| 120 | '%s already exist; insize:%d; outsize:%d' % |
| 121 | (outfile, os.stat(infile).st_size, os.stat(outfile).st_size)) |
| 122 | |
| 123 | if action == COPY: |
| 124 | readable_copy(outfile, infile) |
| 125 | elif action == SYMLINK and sys.platform != 'win32': |
| 126 | # On windows, symlink are converted to hardlink and fails over to copy. |
maruel@chromium.org | f43e68b | 2012-10-15 20:23:10 +0000 | [diff] [blame] | 127 | os.symlink(infile, outfile) # pylint: disable=E1101 |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 128 | else: |
| 129 | try: |
| 130 | os_link(infile, outfile) |
| 131 | except OSError: |
| 132 | # Probably a different file system. |
| 133 | logging.warn( |
| 134 | 'Failed to hardlink, failing back to copy %s to %s' % ( |
| 135 | infile, outfile)) |
| 136 | readable_copy(outfile, infile) |
| 137 | |
| 138 | |
| 139 | def _set_write_bit(path, read_only): |
| 140 | """Sets or resets the executable bit on a file or directory.""" |
| 141 | mode = os.lstat(path).st_mode |
| 142 | if read_only: |
| 143 | mode = mode & 0500 |
| 144 | else: |
| 145 | mode = mode | 0200 |
| 146 | if hasattr(os, 'lchmod'): |
| 147 | os.lchmod(path, mode) # pylint: disable=E1101 |
| 148 | else: |
| 149 | if stat.S_ISLNK(mode): |
| 150 | # Skip symlink without lchmod() support. |
| 151 | logging.debug('Can\'t change +w bit on symlink %s' % path) |
| 152 | return |
| 153 | |
| 154 | # TODO(maruel): Implement proper DACL modification on Windows. |
| 155 | os.chmod(path, mode) |
| 156 | |
| 157 | |
| 158 | def make_writable(root, read_only): |
| 159 | """Toggle the writable bit on a directory tree.""" |
csharp@chromium.org | 837352f | 2013-01-17 21:17:03 +0000 | [diff] [blame] | 160 | assert os.path.isabs(root), root |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 161 | for dirpath, dirnames, filenames in os.walk(root, topdown=True): |
| 162 | for filename in filenames: |
| 163 | _set_write_bit(os.path.join(dirpath, filename), read_only) |
| 164 | |
| 165 | for dirname in dirnames: |
| 166 | _set_write_bit(os.path.join(dirpath, dirname), read_only) |
| 167 | |
| 168 | |
| 169 | def rmtree(root): |
| 170 | """Wrapper around shutil.rmtree() to retry automatically on Windows.""" |
| 171 | make_writable(root, False) |
| 172 | if sys.platform == 'win32': |
| 173 | for i in range(3): |
| 174 | try: |
| 175 | shutil.rmtree(root) |
| 176 | break |
| 177 | except WindowsError: # pylint: disable=E0602 |
| 178 | delay = (i+1)*2 |
| 179 | print >> sys.stderr, ( |
| 180 | 'The test has subprocess outliving it. Sleep %d seconds.' % delay) |
| 181 | time.sleep(delay) |
| 182 | else: |
| 183 | shutil.rmtree(root) |
| 184 | |
| 185 | |
| 186 | def is_same_filesystem(path1, path2): |
| 187 | """Returns True if both paths are on the same filesystem. |
| 188 | |
| 189 | This is required to enable the use of hardlinks. |
| 190 | """ |
| 191 | assert os.path.isabs(path1), path1 |
| 192 | assert os.path.isabs(path2), path2 |
| 193 | if sys.platform == 'win32': |
| 194 | # If the drive letter mismatches, assume it's a separate partition. |
| 195 | # TODO(maruel): It should look at the underlying drive, a drive letter could |
| 196 | # be a mount point to a directory on another drive. |
| 197 | assert re.match(r'^[a-zA-Z]\:\\.*', path1), path1 |
| 198 | assert re.match(r'^[a-zA-Z]\:\\.*', path2), path2 |
| 199 | if path1[0].lower() != path2[0].lower(): |
| 200 | return False |
| 201 | return os.stat(path1).st_dev == os.stat(path2).st_dev |
| 202 | |
| 203 | |
| 204 | def get_free_space(path): |
| 205 | """Returns the number of free bytes.""" |
| 206 | if sys.platform == 'win32': |
| 207 | free_bytes = ctypes.c_ulonglong(0) |
| 208 | ctypes.windll.kernel32.GetDiskFreeSpaceExW( |
| 209 | ctypes.c_wchar_p(path), None, None, ctypes.pointer(free_bytes)) |
| 210 | return free_bytes.value |
maruel@chromium.org | f43e68b | 2012-10-15 20:23:10 +0000 | [diff] [blame] | 211 | # For OSes other than Windows. |
| 212 | f = os.statvfs(path) # pylint: disable=E1101 |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 213 | return f.f_bfree * f.f_frsize |
| 214 | |
| 215 | |
| 216 | def make_temp_dir(prefix, root_dir): |
| 217 | """Returns a temporary directory on the same file system as root_dir.""" |
| 218 | base_temp_dir = None |
| 219 | if not is_same_filesystem(root_dir, tempfile.gettempdir()): |
| 220 | base_temp_dir = os.path.dirname(root_dir) |
| 221 | return tempfile.mkdtemp(prefix=prefix, dir=base_temp_dir) |
| 222 | |
| 223 | |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 224 | def load_isolated(content): |
| 225 | """Verifies the .isolated file is valid and loads this object with the json |
| 226 | data. |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 227 | """ |
| 228 | try: |
| 229 | data = json.loads(content) |
| 230 | except ValueError: |
| 231 | raise ConfigError('Failed to parse: %s...' % content[:100]) |
| 232 | |
| 233 | if not isinstance(data, dict): |
| 234 | raise ConfigError('Expected dict, got %r' % data) |
| 235 | |
| 236 | for key, value in data.iteritems(): |
| 237 | if key == 'command': |
| 238 | if not isinstance(value, list): |
| 239 | raise ConfigError('Expected list, got %r' % value) |
maruel@chromium.org | 89ad2db | 2012-12-12 14:29:22 +0000 | [diff] [blame] | 240 | if not value: |
| 241 | raise ConfigError('Expected non-empty command') |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 242 | for subvalue in value: |
| 243 | if not isinstance(subvalue, basestring): |
| 244 | raise ConfigError('Expected string, got %r' % subvalue) |
| 245 | |
| 246 | elif key == 'files': |
| 247 | if not isinstance(value, dict): |
| 248 | raise ConfigError('Expected dict, got %r' % value) |
| 249 | for subkey, subvalue in value.iteritems(): |
| 250 | if not isinstance(subkey, basestring): |
| 251 | raise ConfigError('Expected string, got %r' % subkey) |
| 252 | if not isinstance(subvalue, dict): |
| 253 | raise ConfigError('Expected dict, got %r' % subvalue) |
| 254 | for subsubkey, subsubvalue in subvalue.iteritems(): |
maruel@chromium.org | e5c1713 | 2012-11-21 18:18:46 +0000 | [diff] [blame] | 255 | if subsubkey == 'l': |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 256 | if not isinstance(subsubvalue, basestring): |
| 257 | raise ConfigError('Expected string, got %r' % subsubvalue) |
maruel@chromium.org | e5c1713 | 2012-11-21 18:18:46 +0000 | [diff] [blame] | 258 | elif subsubkey == 'm': |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 259 | if not isinstance(subsubvalue, int): |
| 260 | raise ConfigError('Expected int, got %r' % subsubvalue) |
maruel@chromium.org | e5c1713 | 2012-11-21 18:18:46 +0000 | [diff] [blame] | 261 | elif subsubkey == 'h': |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 262 | if not RE_IS_SHA1.match(subsubvalue): |
| 263 | raise ConfigError('Expected sha-1, got %r' % subsubvalue) |
maruel@chromium.org | e5c1713 | 2012-11-21 18:18:46 +0000 | [diff] [blame] | 264 | elif subsubkey == 's': |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 265 | if not isinstance(subsubvalue, int): |
| 266 | raise ConfigError('Expected int, got %r' % subsubvalue) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 267 | else: |
| 268 | raise ConfigError('Unknown subsubkey %s' % subsubkey) |
maruel@chromium.org | e5c1713 | 2012-11-21 18:18:46 +0000 | [diff] [blame] | 269 | if bool('h' in subvalue) and bool('l' in subvalue): |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 270 | raise ConfigError( |
maruel@chromium.org | e5c1713 | 2012-11-21 18:18:46 +0000 | [diff] [blame] | 271 | 'Did not expect both \'h\' (sha-1) and \'l\' (link), got: %r' % |
| 272 | subvalue) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 273 | |
| 274 | elif key == 'includes': |
| 275 | if not isinstance(value, list): |
| 276 | raise ConfigError('Expected list, got %r' % value) |
maruel@chromium.org | 89ad2db | 2012-12-12 14:29:22 +0000 | [diff] [blame] | 277 | if not value: |
| 278 | raise ConfigError('Expected non-empty includes list') |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 279 | for subvalue in value: |
| 280 | if not RE_IS_SHA1.match(subvalue): |
| 281 | raise ConfigError('Expected sha-1, got %r' % subvalue) |
| 282 | |
| 283 | elif key == 'read_only': |
| 284 | if not isinstance(value, bool): |
| 285 | raise ConfigError('Expected bool, got %r' % value) |
| 286 | |
| 287 | elif key == 'relative_cwd': |
| 288 | if not isinstance(value, basestring): |
| 289 | raise ConfigError('Expected string, got %r' % value) |
| 290 | |
| 291 | elif key == 'os': |
| 292 | if value != get_flavor(): |
| 293 | raise ConfigError( |
| 294 | 'Expected \'os\' to be \'%s\' but got \'%s\'' % |
| 295 | (get_flavor(), value)) |
| 296 | |
| 297 | else: |
| 298 | raise ConfigError('Unknown key %s' % key) |
| 299 | |
| 300 | return data |
| 301 | |
| 302 | |
| 303 | def fix_python_path(cmd): |
| 304 | """Returns the fixed command line to call the right python executable.""" |
| 305 | out = cmd[:] |
| 306 | if out[0] == 'python': |
| 307 | out[0] = sys.executable |
| 308 | elif out[0].endswith('.py'): |
| 309 | out.insert(0, sys.executable) |
| 310 | return out |
| 311 | |
| 312 | |
maruel@chromium.org | ef33312 | 2013-03-12 20:36:40 +0000 | [diff] [blame] | 313 | def url_open(url, data=None, retry_404=False, content_type=None): |
csharp@chromium.org | f13eec0 | 2013-03-11 18:22:56 +0000 | [diff] [blame] | 314 | """Attempts to open the given url multiple times. |
| 315 | |
| 316 | |data| can be either: |
| 317 | -None for a GET request |
| 318 | -str for pre-encoded data |
| 319 | -list for data to be encoded |
| 320 | -dict for data to be encoded (COUNT_KEY will be added in this case) |
| 321 | |
| 322 | If no wait_duration is given, the default wait time will exponentially |
| 323 | increase between each retry. |
| 324 | |
| 325 | Returns a file-like object, where the response may be read from, or None |
| 326 | if it was unable to connect. |
| 327 | """ |
| 328 | method = 'GET' if data is None else 'POST' |
| 329 | |
csharp@chromium.org | f13eec0 | 2013-03-11 18:22:56 +0000 | [diff] [blame] | 330 | if isinstance(data, dict) and COUNT_KEY in data: |
| 331 | logging.error('%s already existed in the data passed into UlrOpen. It ' |
| 332 | 'would be overwritten. Aborting UrlOpen', COUNT_KEY) |
| 333 | return None |
| 334 | |
maruel@chromium.org | ef33312 | 2013-03-12 20:36:40 +0000 | [diff] [blame] | 335 | assert not ((method != 'POST') and content_type), ( |
| 336 | 'Can\'t use content_type on GET') |
| 337 | |
| 338 | def make_request(extra): |
| 339 | """Returns a urllib2.Request instance for this specific retry.""" |
| 340 | if isinstance(data, str) or data is None: |
| 341 | payload = data |
| 342 | else: |
| 343 | if isinstance(data, dict): |
| 344 | payload = data.items() |
| 345 | else: |
| 346 | payload = data[:] |
| 347 | payload.extend(extra.iteritems()) |
| 348 | payload = urllib.urlencode(payload) |
| 349 | |
| 350 | new_url = url |
| 351 | if isinstance(data, str) or data is None: |
| 352 | # In these cases, add the extra parameter to the query part of the url. |
| 353 | url_parts = list(urlparse.urlparse(new_url)) |
| 354 | # Append the query parameter. |
| 355 | if url_parts[4] and extra: |
| 356 | url_parts[4] += '&' |
| 357 | url_parts[4] += urllib.urlencode(extra) |
| 358 | new_url = urlparse.urlunparse(url_parts) |
| 359 | |
| 360 | request = urllib2.Request(new_url, data=payload) |
| 361 | if payload is not None: |
| 362 | if content_type: |
| 363 | request.add_header('Content-Type', content_type) |
| 364 | request.add_header('Content-Length', len(payload)) |
| 365 | return request |
| 366 | |
| 367 | return url_open_request(make_request, retry_404) |
| 368 | |
| 369 | |
| 370 | def url_open_request(make_request, retry_404=False): |
| 371 | """Internal version of url_open() for users that need special handling. |
| 372 | """ |
maruel@chromium.org | 8ac504b | 2013-03-13 16:25:45 +0000 | [diff] [blame] | 373 | last_error = None |
csharp@chromium.org | f13eec0 | 2013-03-11 18:22:56 +0000 | [diff] [blame] | 374 | for attempt in range(MAX_URL_OPEN_ATTEMPTS): |
maruel@chromium.org | ef33312 | 2013-03-12 20:36:40 +0000 | [diff] [blame] | 375 | extra = {COUNT_KEY: attempt} if attempt else {} |
| 376 | request = make_request(extra) |
csharp@chromium.org | f13eec0 | 2013-03-11 18:22:56 +0000 | [diff] [blame] | 377 | try: |
maruel@chromium.org | ef33312 | 2013-03-12 20:36:40 +0000 | [diff] [blame] | 378 | url_response = urllib2.urlopen(request) |
maruel@chromium.org | f04becf | 2013-03-14 19:09:11 +0000 | [diff] [blame] | 379 | logging.debug('url_open(%s) succeeded', request.get_full_url()) |
csharp@chromium.org | f13eec0 | 2013-03-11 18:22:56 +0000 | [diff] [blame] | 380 | return url_response |
| 381 | except urllib2.HTTPError as e: |
csharp@chromium.org | e9c8d94 | 2013-03-11 20:48:36 +0000 | [diff] [blame] | 382 | if e.code < 500 and not (retry_404 and e.code == 404): |
csharp@chromium.org | f13eec0 | 2013-03-11 18:22:56 +0000 | [diff] [blame] | 383 | # This HTTPError means we reached the server and there was a problem |
| 384 | # with the request, so don't retry. |
maruel@chromium.org | 8ac504b | 2013-03-13 16:25:45 +0000 | [diff] [blame] | 385 | logging.error( |
| 386 | 'Able to connect to %s but an exception was thrown.\n%s\n%s', |
| 387 | request.get_full_url(), e, e.read()) |
csharp@chromium.org | f13eec0 | 2013-03-11 18:22:56 +0000 | [diff] [blame] | 388 | return None |
| 389 | |
| 390 | # The HTTPError was due to a server error, so retry the attempt. |
| 391 | logging.warning('Able to connect to %s on attempt %d.\nException: %s ', |
maruel@chromium.org | ef33312 | 2013-03-12 20:36:40 +0000 | [diff] [blame] | 392 | request.get_full_url(), attempt, e) |
maruel@chromium.org | 8ac504b | 2013-03-13 16:25:45 +0000 | [diff] [blame] | 393 | last_error = e |
csharp@chromium.org | f13eec0 | 2013-03-11 18:22:56 +0000 | [diff] [blame] | 394 | |
| 395 | except (urllib2.URLError, httplib.HTTPException) as e: |
| 396 | logging.warning('Unable to open url %s on attempt %d.\nException: %s', |
maruel@chromium.org | ef33312 | 2013-03-12 20:36:40 +0000 | [diff] [blame] | 397 | request.get_full_url(), attempt, e) |
maruel@chromium.org | 8ac504b | 2013-03-13 16:25:45 +0000 | [diff] [blame] | 398 | last_error = e |
csharp@chromium.org | f13eec0 | 2013-03-11 18:22:56 +0000 | [diff] [blame] | 399 | |
| 400 | # Only sleep if we are going to try again. |
| 401 | if attempt != MAX_URL_OPEN_ATTEMPTS - 1: |
| 402 | duration = random.random() * 3 + math.pow(1.5, (attempt + 1)) |
| 403 | duration = min(10, max(0.1, duration)) |
| 404 | time.sleep(duration) |
| 405 | |
maruel@chromium.org | 8ac504b | 2013-03-13 16:25:45 +0000 | [diff] [blame] | 406 | logging.error('Unable to open given url, %s, after %d attempts.\n%s', |
| 407 | request.get_full_url(), MAX_URL_OPEN_ATTEMPTS, last_error) |
csharp@chromium.org | f13eec0 | 2013-03-11 18:22:56 +0000 | [diff] [blame] | 408 | return None |
| 409 | |
| 410 | |
maruel@chromium.org | 8df128b | 2012-11-08 19:05:04 +0000 | [diff] [blame] | 411 | class ThreadPool(object): |
| 412 | """Implements a multithreaded worker pool oriented for mapping jobs with |
| 413 | thread-local result storage. |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 414 | |
| 415 | Arguments: |
| 416 | - initial_threads: Number of threads to start immediately. Can be 0 if it is |
| 417 | uncertain that threads will be needed. |
| 418 | - max_threads: Maximum number of threads that will be started when all the |
| 419 | threads are busy working. Often the number of CPU cores. |
| 420 | - queue_size: Maximum number of tasks to buffer in the queue. 0 for unlimited |
| 421 | queue. A non-zero value may make add_task() blocking. |
maruel@chromium.org | 8df128b | 2012-11-08 19:05:04 +0000 | [diff] [blame] | 422 | """ |
maruel@chromium.org | 5a1446a | 2013-01-17 15:13:27 +0000 | [diff] [blame] | 423 | QUEUE_CLASS = Queue.PriorityQueue |
maruel@chromium.org | 8df128b | 2012-11-08 19:05:04 +0000 | [diff] [blame] | 424 | |
maruel@chromium.org | 6b0c9ec | 2013-01-18 00:34:31 +0000 | [diff] [blame] | 425 | def __init__(self, initial_threads, max_threads, queue_size): |
| 426 | logging.debug( |
| 427 | 'ThreadPool(%d, %d, %d)', initial_threads, max_threads, queue_size) |
| 428 | assert initial_threads <= max_threads |
| 429 | # Update this check once 256 cores CPU are common. |
| 430 | assert max_threads <= 256 |
| 431 | |
maruel@chromium.org | eb28165 | 2012-11-08 21:10:23 +0000 | [diff] [blame] | 432 | self.tasks = self.QUEUE_CLASS(queue_size) |
maruel@chromium.org | 6b0c9ec | 2013-01-18 00:34:31 +0000 | [diff] [blame] | 433 | self._max_threads = max_threads |
maruel@chromium.org | 8df128b | 2012-11-08 19:05:04 +0000 | [diff] [blame] | 434 | |
maruel@chromium.org | 6b0c9ec | 2013-01-18 00:34:31 +0000 | [diff] [blame] | 435 | # Mutables. |
| 436 | self._num_of_added_tasks_lock = threading.Lock() |
maruel@chromium.org | 5a1446a | 2013-01-17 15:13:27 +0000 | [diff] [blame] | 437 | self._num_of_added_tasks = 0 |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 438 | self._outputs_exceptions_cond = threading.Condition() |
maruel@chromium.org | 5a1446a | 2013-01-17 15:13:27 +0000 | [diff] [blame] | 439 | self._outputs = [] |
| 440 | self._exceptions = [] |
maruel@chromium.org | 6b0c9ec | 2013-01-18 00:34:31 +0000 | [diff] [blame] | 441 | # Number of threads in wait state. |
| 442 | self._ready_lock = threading.Lock() |
| 443 | self._ready = 0 |
| 444 | self._workers_lock = threading.Lock() |
| 445 | self._workers = [] |
| 446 | for _ in range(initial_threads): |
| 447 | self._add_worker() |
maruel@chromium.org | 5a1446a | 2013-01-17 15:13:27 +0000 | [diff] [blame] | 448 | |
maruel@chromium.org | 6b0c9ec | 2013-01-18 00:34:31 +0000 | [diff] [blame] | 449 | def _add_worker(self): |
| 450 | """Adds one worker thread if there isn't too many. Thread-safe.""" |
| 451 | # Better to take the lock two times than hold it for too long. |
| 452 | with self._workers_lock: |
| 453 | if len(self._workers) >= self._max_threads: |
| 454 | return False |
| 455 | worker = threading.Thread(target=self._run) |
| 456 | with self._workers_lock: |
| 457 | if len(self._workers) >= self._max_threads: |
| 458 | return False |
| 459 | self._workers.append(worker) |
| 460 | worker.daemon = True |
| 461 | worker.start() |
maruel@chromium.org | 5a1446a | 2013-01-17 15:13:27 +0000 | [diff] [blame] | 462 | |
maruel@chromium.org | 831958f | 2013-01-22 15:01:46 +0000 | [diff] [blame] | 463 | def add_task(self, priority, func, *args, **kwargs): |
maruel@chromium.org | 8df128b | 2012-11-08 19:05:04 +0000 | [diff] [blame] | 464 | """Adds a task, a function to be executed by a worker. |
| 465 | |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 466 | |priority| can adjust the priority of the task versus others. Lower priority |
maruel@chromium.org | 831958f | 2013-01-22 15:01:46 +0000 | [diff] [blame] | 467 | takes precedence. |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 468 | |
| 469 | Returns the index of the item added, e.g. the total number of enqueued items |
| 470 | up to now. |
maruel@chromium.org | 8df128b | 2012-11-08 19:05:04 +0000 | [diff] [blame] | 471 | """ |
maruel@chromium.org | 831958f | 2013-01-22 15:01:46 +0000 | [diff] [blame] | 472 | assert isinstance(priority, int) |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 473 | assert callable(func) |
maruel@chromium.org | 6b0c9ec | 2013-01-18 00:34:31 +0000 | [diff] [blame] | 474 | with self._ready_lock: |
| 475 | start_new_worker = not self._ready |
| 476 | with self._num_of_added_tasks_lock: |
maruel@chromium.org | 5a1446a | 2013-01-17 15:13:27 +0000 | [diff] [blame] | 477 | self._num_of_added_tasks += 1 |
| 478 | index = self._num_of_added_tasks |
maruel@chromium.org | 6b0c9ec | 2013-01-18 00:34:31 +0000 | [diff] [blame] | 479 | self.tasks.put((priority, index, func, args, kwargs)) |
| 480 | if start_new_worker: |
| 481 | self._add_worker() |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 482 | return index |
maruel@chromium.org | 5a1446a | 2013-01-17 15:13:27 +0000 | [diff] [blame] | 483 | |
| 484 | def _run(self): |
maruel@chromium.org | 6b0c9ec | 2013-01-18 00:34:31 +0000 | [diff] [blame] | 485 | """Worker thread loop. Runs until a None task is queued.""" |
maruel@chromium.org | 5a1446a | 2013-01-17 15:13:27 +0000 | [diff] [blame] | 486 | while True: |
maruel@chromium.org | 5a1446a | 2013-01-17 15:13:27 +0000 | [diff] [blame] | 487 | try: |
maruel@chromium.org | 6b0c9ec | 2013-01-18 00:34:31 +0000 | [diff] [blame] | 488 | with self._ready_lock: |
| 489 | self._ready += 1 |
| 490 | task = self.tasks.get() |
| 491 | finally: |
| 492 | with self._ready_lock: |
| 493 | self._ready -= 1 |
| 494 | try: |
| 495 | if task is None: |
| 496 | # We're done. |
| 497 | return |
| 498 | _priority, _index, func, args, kwargs = task |
maruel@chromium.org | 5a1446a | 2013-01-17 15:13:27 +0000 | [diff] [blame] | 499 | out = func(*args, **kwargs) |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 500 | if out is not None: |
| 501 | self._outputs_exceptions_cond.acquire() |
| 502 | try: |
| 503 | self._outputs.append(out) |
| 504 | self._outputs_exceptions_cond.notifyAll() |
| 505 | finally: |
| 506 | self._outputs_exceptions_cond.release() |
maruel@chromium.org | 5a1446a | 2013-01-17 15:13:27 +0000 | [diff] [blame] | 507 | except Exception as e: |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 508 | logging.warning('Caught exception: %s', e) |
maruel@chromium.org | 5a1446a | 2013-01-17 15:13:27 +0000 | [diff] [blame] | 509 | exc_info = sys.exc_info() |
maruel@chromium.org | 97cd0be | 2013-03-13 14:01:36 +0000 | [diff] [blame] | 510 | logging.info(''.join(traceback.format_tb(exc_info[2]))) |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 511 | self._outputs_exceptions_cond.acquire() |
| 512 | try: |
maruel@chromium.org | 5a1446a | 2013-01-17 15:13:27 +0000 | [diff] [blame] | 513 | self._exceptions.append(exc_info) |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 514 | self._outputs_exceptions_cond.notifyAll() |
| 515 | finally: |
| 516 | self._outputs_exceptions_cond.release() |
maruel@chromium.org | 5a1446a | 2013-01-17 15:13:27 +0000 | [diff] [blame] | 517 | finally: |
csharp@chromium.org | 6099118 | 2013-03-18 13:44:17 +0000 | [diff] [blame^] | 518 | try: |
| 519 | self.tasks.task_done() |
| 520 | except Exception as e: |
| 521 | # We need to catch and log this error here because this is the root |
| 522 | # function for the thread, nothing higher will catch the error. |
| 523 | logging.exception('Caught exception while marking task as done: %s', |
| 524 | e) |
maruel@chromium.org | 8df128b | 2012-11-08 19:05:04 +0000 | [diff] [blame] | 525 | |
maruel@chromium.org | eb28165 | 2012-11-08 21:10:23 +0000 | [diff] [blame] | 526 | def join(self): |
maruel@chromium.org | 5a1446a | 2013-01-17 15:13:27 +0000 | [diff] [blame] | 527 | """Extracts all the results from each threads unordered. |
| 528 | |
| 529 | Call repeatedly to extract all the exceptions if desired. |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 530 | |
| 531 | Note: will wait for all work items to be done before returning an exception. |
| 532 | To get an exception early, use get_one_result(). |
maruel@chromium.org | 5a1446a | 2013-01-17 15:13:27 +0000 | [diff] [blame] | 533 | """ |
| 534 | # TODO(maruel): Stop waiting as soon as an exception is caught. |
maruel@chromium.org | eb28165 | 2012-11-08 21:10:23 +0000 | [diff] [blame] | 535 | self.tasks.join() |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 536 | self._outputs_exceptions_cond.acquire() |
| 537 | try: |
maruel@chromium.org | 6b0c9ec | 2013-01-18 00:34:31 +0000 | [diff] [blame] | 538 | if self._exceptions: |
| 539 | e = self._exceptions.pop(0) |
| 540 | raise e[0], e[1], e[2] |
maruel@chromium.org | 6b0c9ec | 2013-01-18 00:34:31 +0000 | [diff] [blame] | 541 | out = self._outputs |
| 542 | self._outputs = [] |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 543 | finally: |
| 544 | self._outputs_exceptions_cond.release() |
maruel@chromium.org | 8df128b | 2012-11-08 19:05:04 +0000 | [diff] [blame] | 545 | return out |
| 546 | |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 547 | def get_one_result(self): |
| 548 | """Returns the next item that was generated or raises an exception if one |
| 549 | occured. |
| 550 | |
| 551 | Warning: this function will hang if there is no work item left. Use join |
| 552 | instead. |
| 553 | """ |
| 554 | self._outputs_exceptions_cond.acquire() |
| 555 | try: |
| 556 | while True: |
| 557 | if self._exceptions: |
| 558 | e = self._exceptions.pop(0) |
| 559 | raise e[0], e[1], e[2] |
| 560 | if self._outputs: |
| 561 | return self._outputs.pop(0) |
| 562 | self._outputs_exceptions_cond.wait() |
| 563 | finally: |
| 564 | self._outputs_exceptions_cond.release() |
| 565 | |
maruel@chromium.org | 8df128b | 2012-11-08 19:05:04 +0000 | [diff] [blame] | 566 | def close(self): |
| 567 | """Closes all the threads.""" |
| 568 | for _ in range(len(self._workers)): |
| 569 | # Enqueueing None causes the worker to stop. |
maruel@chromium.org | eb28165 | 2012-11-08 21:10:23 +0000 | [diff] [blame] | 570 | self.tasks.put(None) |
maruel@chromium.org | 8df128b | 2012-11-08 19:05:04 +0000 | [diff] [blame] | 571 | for t in self._workers: |
| 572 | t.join() |
| 573 | |
| 574 | def __enter__(self): |
| 575 | """Enables 'with' statement.""" |
| 576 | return self |
| 577 | |
maruel@chromium.org | 97cd0be | 2013-03-13 14:01:36 +0000 | [diff] [blame] | 578 | def __exit__(self, _exc_type, _exc_value, _traceback): |
maruel@chromium.org | 8df128b | 2012-11-08 19:05:04 +0000 | [diff] [blame] | 579 | """Enables 'with' statement.""" |
| 580 | self.close() |
| 581 | |
| 582 | |
csharp@chromium.org | 8dc5254 | 2012-11-08 20:29:55 +0000 | [diff] [blame] | 583 | def valid_file(filepath, size): |
| 584 | """Determines if the given files appears valid (currently it just checks |
| 585 | the file's size).""" |
maruel@chromium.org | 770993b | 2012-12-11 17:16:48 +0000 | [diff] [blame] | 586 | if size == UNKNOWN_FILE_SIZE: |
| 587 | return True |
| 588 | actual_size = os.stat(filepath).st_size |
| 589 | if size != actual_size: |
| 590 | logging.warning( |
| 591 | 'Found invalid item %s; %d != %d', |
| 592 | os.path.basename(filepath), actual_size, size) |
| 593 | return False |
| 594 | return True |
csharp@chromium.org | 8dc5254 | 2012-11-08 20:29:55 +0000 | [diff] [blame] | 595 | |
| 596 | |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 597 | class Profiler(object): |
| 598 | def __init__(self, name): |
| 599 | self.name = name |
| 600 | self.start_time = None |
| 601 | |
| 602 | def __enter__(self): |
| 603 | self.start_time = time.time() |
| 604 | return self |
| 605 | |
| 606 | def __exit__(self, _exc_type, _exec_value, _traceback): |
| 607 | time_taken = time.time() - self.start_time |
| 608 | logging.info('Profiling: Section %s took %3.3f seconds', |
| 609 | self.name, time_taken) |
| 610 | |
| 611 | |
| 612 | class Remote(object): |
maruel@chromium.org | fb155e9 | 2012-09-28 20:36:54 +0000 | [diff] [blame] | 613 | """Priority based worker queue to fetch or upload files from a |
| 614 | content-address server. Any function may be given as the fetcher/upload, |
| 615 | as long as it takes two inputs (the item contents, and their relative |
| 616 | destination). |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 617 | |
| 618 | Supports local file system, CIFS or http remotes. |
| 619 | |
| 620 | When the priority of items is equals, works in strict FIFO mode. |
| 621 | """ |
| 622 | # Initial and maximum number of worker threads. |
| 623 | INITIAL_WORKERS = 2 |
| 624 | MAX_WORKERS = 16 |
| 625 | # Priorities. |
| 626 | LOW, MED, HIGH = (1<<8, 2<<8, 3<<8) |
| 627 | INTERNAL_PRIORITY_BITS = (1<<8) - 1 |
| 628 | RETRIES = 5 |
| 629 | |
maruel@chromium.org | fb155e9 | 2012-09-28 20:36:54 +0000 | [diff] [blame] | 630 | def __init__(self, destination_root): |
| 631 | # Function to fetch a remote object or upload to a remote location.. |
| 632 | self._do_item = self.get_file_handler(destination_root) |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 633 | # Contains tuple(priority, obj). |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 634 | self._done = Queue.PriorityQueue() |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 635 | self._pool = ThreadPool(self.INITIAL_WORKERS, self.MAX_WORKERS, 0) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 636 | |
maruel@chromium.org | fb155e9 | 2012-09-28 20:36:54 +0000 | [diff] [blame] | 637 | def join(self): |
| 638 | """Blocks until the queue is empty.""" |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 639 | return self._pool.join() |
maruel@chromium.org | fb155e9 | 2012-09-28 20:36:54 +0000 | [diff] [blame] | 640 | |
csharp@chromium.org | df2968f | 2012-11-16 20:25:37 +0000 | [diff] [blame] | 641 | def add_item(self, priority, obj, dest, size): |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 642 | """Retrieves an object from the remote data store. |
| 643 | |
| 644 | The smaller |priority| gets fetched first. |
| 645 | |
| 646 | Thread-safe. |
| 647 | """ |
| 648 | assert (priority & self.INTERNAL_PRIORITY_BITS) == 0 |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 649 | return self._add_item(priority, obj, dest, size) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 650 | |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 651 | def _add_item(self, priority, obj, dest, size): |
| 652 | assert isinstance(obj, basestring), obj |
| 653 | assert isinstance(dest, basestring), dest |
| 654 | assert size is None or isinstance(size, int), size |
| 655 | return self._pool.add_task( |
| 656 | priority, self._task_executer, priority, obj, dest, size) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 657 | |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 658 | def get_one_result(self): |
| 659 | return self._pool.get_one_result() |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 660 | |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 661 | def _task_executer(self, priority, obj, dest, size): |
| 662 | """Wraps self._do_item to trap and retry on IOError exceptions.""" |
| 663 | try: |
| 664 | self._do_item(obj, dest) |
| 665 | if size and not valid_file(dest, size): |
| 666 | download_size = os.stat(dest).st_size |
| 667 | os.remove(dest) |
| 668 | raise IOError('File incorrect size after download of %s. Got %s and ' |
| 669 | 'expected %s' % (obj, download_size, size)) |
| 670 | # TODO(maruel): Technically, we'd want to have an output queue to be a |
| 671 | # PriorityQueue. |
| 672 | return obj |
| 673 | except IOError as e: |
| 674 | logging.debug('Caught IOError: %s', e) |
| 675 | # Retry a few times, lowering the priority. |
| 676 | if (priority & self.INTERNAL_PRIORITY_BITS) < self.RETRIES: |
| 677 | self._add_item(priority + 1, obj, dest, size) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 678 | return |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 679 | raise |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 680 | |
csharp@chromium.org | 59c7bcf | 2012-11-21 21:13:18 +0000 | [diff] [blame] | 681 | def get_file_handler(self, file_or_url): # pylint: disable=R0201 |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 682 | """Returns a object to retrieve objects from a remote.""" |
| 683 | if re.match(r'^https?://.+$', file_or_url): |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 684 | def download_file(item, dest): |
| 685 | # TODO(maruel): Reuse HTTP connections. The stdlib doesn't make this |
| 686 | # easy. |
csharp@chromium.org | a92403f | 2012-11-20 15:13:59 +0000 | [diff] [blame] | 687 | try: |
csharp@chromium.org | aa2d151 | 2012-12-05 21:17:39 +0000 | [diff] [blame] | 688 | zipped_source = file_or_url + item |
csharp@chromium.org | a92403f | 2012-11-20 15:13:59 +0000 | [diff] [blame] | 689 | logging.debug('download_file(%s)', zipped_source) |
csharp@chromium.org | e9c8d94 | 2013-03-11 20:48:36 +0000 | [diff] [blame] | 690 | |
| 691 | # Because the app engine DB is only eventually consistent, retry |
| 692 | # 404 errors because the file might just not be visible yet (even |
| 693 | # though it has been uploaded). |
| 694 | connection = url_open(zipped_source, retry_404=True) |
csharp@chromium.org | f13eec0 | 2013-03-11 18:22:56 +0000 | [diff] [blame] | 695 | if not connection: |
| 696 | raise IOError('Unable to open connection to %s' % zipped_source) |
csharp@chromium.org | a92403f | 2012-11-20 15:13:59 +0000 | [diff] [blame] | 697 | decompressor = zlib.decompressobj() |
maruel@chromium.org | 3f03918 | 2012-11-27 21:32:41 +0000 | [diff] [blame] | 698 | size = 0 |
csharp@chromium.org | a92403f | 2012-11-20 15:13:59 +0000 | [diff] [blame] | 699 | with open(dest, 'wb') as f: |
| 700 | while True: |
| 701 | chunk = connection.read(ZIPPED_FILE_CHUNK) |
| 702 | if not chunk: |
| 703 | break |
maruel@chromium.org | 3f03918 | 2012-11-27 21:32:41 +0000 | [diff] [blame] | 704 | size += len(chunk) |
csharp@chromium.org | a92403f | 2012-11-20 15:13:59 +0000 | [diff] [blame] | 705 | f.write(decompressor.decompress(chunk)) |
| 706 | # Ensure that all the data was properly decompressed. |
| 707 | uncompressed_data = decompressor.flush() |
| 708 | assert not uncompressed_data |
csharp@chromium.org | 549669e | 2013-01-22 19:48:17 +0000 | [diff] [blame] | 709 | except IOError: |
| 710 | logging.error('Encountered an exception with (%s, %s)' % (item, dest)) |
| 711 | raise |
csharp@chromium.org | a110d79 | 2013-01-07 16:16:16 +0000 | [diff] [blame] | 712 | except httplib.HTTPException as e: |
| 713 | raise IOError('Encountered an HTTPException.\n%s' % e) |
csharp@chromium.org | 186d623 | 2012-11-26 14:36:12 +0000 | [diff] [blame] | 714 | except zlib.error as e: |
maruel@chromium.org | 5dd75dd | 2012-12-03 15:11:32 +0000 | [diff] [blame] | 715 | # Log the first bytes to see if it's uncompressed data. |
| 716 | logging.warning('%r', e[:512]) |
maruel@chromium.org | 3f03918 | 2012-11-27 21:32:41 +0000 | [diff] [blame] | 717 | raise IOError( |
| 718 | 'Problem unzipping data for item %s. Got %d bytes.\n%s' % |
| 719 | (item, size, e)) |
csharp@chromium.org | a92403f | 2012-11-20 15:13:59 +0000 | [diff] [blame] | 720 | |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 721 | return download_file |
| 722 | |
| 723 | def copy_file(item, dest): |
| 724 | source = os.path.join(file_or_url, item) |
csharp@chromium.org | ffd8cf0 | 2013-01-09 21:57:38 +0000 | [diff] [blame] | 725 | if source == dest: |
| 726 | logging.info('Source and destination are the same, no action required') |
| 727 | return |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 728 | logging.debug('copy_file(%s, %s)', source, dest) |
| 729 | shutil.copy(source, dest) |
| 730 | return copy_file |
| 731 | |
| 732 | |
| 733 | class CachePolicies(object): |
| 734 | def __init__(self, max_cache_size, min_free_space, max_items): |
| 735 | """ |
| 736 | Arguments: |
| 737 | - max_cache_size: Trim if the cache gets larger than this value. If 0, the |
| 738 | cache is effectively a leak. |
| 739 | - min_free_space: Trim if disk free space becomes lower than this value. If |
| 740 | 0, it unconditionally fill the disk. |
| 741 | - max_items: Maximum number of items to keep in the cache. If 0, do not |
| 742 | enforce a limit. |
| 743 | """ |
| 744 | self.max_cache_size = max_cache_size |
| 745 | self.min_free_space = min_free_space |
| 746 | self.max_items = max_items |
| 747 | |
| 748 | |
csharp@chromium.org | ffd8cf0 | 2013-01-09 21:57:38 +0000 | [diff] [blame] | 749 | class NoCache(object): |
| 750 | """This class is intended to be usable everywhere the Cache class is. |
| 751 | Instead of downloading to a cache, all files are downloaded to the target |
| 752 | directory and then moved to where they are needed. |
| 753 | """ |
| 754 | |
| 755 | def __init__(self, target_directory, remote): |
| 756 | self.target_directory = target_directory |
| 757 | self.remote = remote |
| 758 | |
| 759 | def retrieve(self, priority, item, size): |
| 760 | """Get the request file.""" |
| 761 | self.remote.add_item(priority, item, self.path(item), size) |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 762 | self.remote.get_one_result() |
csharp@chromium.org | ffd8cf0 | 2013-01-09 21:57:38 +0000 | [diff] [blame] | 763 | |
| 764 | def wait_for(self, items): |
| 765 | """Download the first item of the given list if it is missing.""" |
| 766 | item = items.iterkeys().next() |
| 767 | |
| 768 | if not os.path.exists(self.path(item)): |
| 769 | self.remote.add_item(Remote.MED, item, self.path(item), UNKNOWN_FILE_SIZE) |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 770 | downloaded = self.remote.get_one_result() |
csharp@chromium.org | ffd8cf0 | 2013-01-09 21:57:38 +0000 | [diff] [blame] | 771 | assert downloaded == item |
| 772 | |
| 773 | return item |
| 774 | |
| 775 | def path(self, item): |
| 776 | return os.path.join(self.target_directory, item) |
| 777 | |
| 778 | |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 779 | class Cache(object): |
| 780 | """Stateful LRU cache. |
| 781 | |
| 782 | Saves its state as json file. |
| 783 | """ |
| 784 | STATE_FILE = 'state.json' |
| 785 | |
| 786 | def __init__(self, cache_dir, remote, policies): |
| 787 | """ |
| 788 | Arguments: |
| 789 | - cache_dir: Directory where to place the cache. |
| 790 | - remote: Remote where to fetch items from. |
| 791 | - policies: cache retention policies. |
| 792 | """ |
| 793 | self.cache_dir = cache_dir |
| 794 | self.remote = remote |
| 795 | self.policies = policies |
| 796 | self.state_file = os.path.join(cache_dir, self.STATE_FILE) |
| 797 | # The tuple(file, size) are kept as an array in a LRU style. E.g. |
| 798 | # self.state[0] is the oldest item. |
| 799 | self.state = [] |
maruel@chromium.org | 770993b | 2012-12-11 17:16:48 +0000 | [diff] [blame] | 800 | self._state_need_to_be_saved = False |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 801 | # A lookup map to speed up searching. |
| 802 | self._lookup = {} |
maruel@chromium.org | 770993b | 2012-12-11 17:16:48 +0000 | [diff] [blame] | 803 | self._lookup_is_stale = True |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 804 | |
| 805 | # Items currently being fetched. Keep it local to reduce lock contention. |
| 806 | self._pending_queue = set() |
| 807 | |
| 808 | # Profiling values. |
| 809 | self._added = [] |
| 810 | self._removed = [] |
| 811 | self._free_disk = 0 |
| 812 | |
maruel@chromium.org | 770993b | 2012-12-11 17:16:48 +0000 | [diff] [blame] | 813 | with Profiler('Setup'): |
| 814 | if not os.path.isdir(self.cache_dir): |
| 815 | os.makedirs(self.cache_dir) |
| 816 | if os.path.isfile(self.state_file): |
| 817 | try: |
| 818 | self.state = json.load(open(self.state_file, 'r')) |
| 819 | except (IOError, ValueError), e: |
| 820 | # Too bad. The file will be overwritten and the cache cleared. |
| 821 | logging.error( |
| 822 | 'Broken state file %s, ignoring.\n%s' % (self.STATE_FILE, e)) |
| 823 | self._state_need_to_be_saved = True |
| 824 | if (not isinstance(self.state, list) or |
| 825 | not all( |
| 826 | isinstance(i, (list, tuple)) and len(i) == 2 |
| 827 | for i in self.state)): |
| 828 | # Discard. |
| 829 | self._state_need_to_be_saved = True |
| 830 | self.state = [] |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 831 | |
maruel@chromium.org | 770993b | 2012-12-11 17:16:48 +0000 | [diff] [blame] | 832 | # Ensure that all files listed in the state still exist and add new ones. |
| 833 | previous = set(filename for filename, _ in self.state) |
| 834 | if len(previous) != len(self.state): |
| 835 | logging.warn('Cache state is corrupted, found duplicate files') |
| 836 | self._state_need_to_be_saved = True |
| 837 | self.state = [] |
| 838 | |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 839 | added = 0 |
| 840 | for filename in os.listdir(self.cache_dir): |
| 841 | if filename == self.STATE_FILE: |
| 842 | continue |
| 843 | if filename in previous: |
| 844 | previous.remove(filename) |
| 845 | continue |
| 846 | # An untracked file. |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 847 | if not RE_IS_SHA1.match(filename): |
| 848 | logging.warn('Removing unknown file %s from cache', filename) |
| 849 | os.remove(self.path(filename)) |
maruel@chromium.org | 770993b | 2012-12-11 17:16:48 +0000 | [diff] [blame] | 850 | continue |
| 851 | # Insert as the oldest file. It will be deleted eventually if not |
| 852 | # accessed. |
| 853 | self._add(filename, False) |
| 854 | logging.warn('Add unknown file %s to cache', filename) |
| 855 | added += 1 |
| 856 | |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 857 | if added: |
| 858 | logging.warn('Added back %d unknown files', added) |
maruel@chromium.org | 770993b | 2012-12-11 17:16:48 +0000 | [diff] [blame] | 859 | if previous: |
| 860 | logging.warn('Removed %d lost files', len(previous)) |
| 861 | # Set explicitly in case self._add() wasn't called. |
| 862 | self._state_need_to_be_saved = True |
| 863 | # Filter out entries that were not found while keeping the previous |
| 864 | # order. |
| 865 | self.state = [ |
| 866 | (filename, size) for filename, size in self.state |
| 867 | if filename not in previous |
| 868 | ] |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 869 | self.trim() |
| 870 | |
| 871 | def __enter__(self): |
| 872 | return self |
| 873 | |
| 874 | def __exit__(self, _exc_type, _exec_value, _traceback): |
| 875 | with Profiler('CleanupTrimming'): |
| 876 | self.trim() |
| 877 | |
| 878 | logging.info( |
maruel@chromium.org | 5fd6f47 | 2012-12-11 00:26:08 +0000 | [diff] [blame] | 879 | '%5d (%8dkb) added', len(self._added), sum(self._added) / 1024) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 880 | logging.info( |
maruel@chromium.org | 5fd6f47 | 2012-12-11 00:26:08 +0000 | [diff] [blame] | 881 | '%5d (%8dkb) current', |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 882 | len(self.state), |
| 883 | sum(i[1] for i in self.state) / 1024) |
| 884 | logging.info( |
maruel@chromium.org | 5fd6f47 | 2012-12-11 00:26:08 +0000 | [diff] [blame] | 885 | '%5d (%8dkb) removed', len(self._removed), sum(self._removed) / 1024) |
| 886 | logging.info(' %8dkb free', self._free_disk / 1024) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 887 | |
csharp@chromium.org | 8dc5254 | 2012-11-08 20:29:55 +0000 | [diff] [blame] | 888 | def remove_file_at_index(self, index): |
| 889 | """Removes the file at the given index.""" |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 890 | try: |
maruel@chromium.org | 770993b | 2012-12-11 17:16:48 +0000 | [diff] [blame] | 891 | self._state_need_to_be_saved = True |
csharp@chromium.org | 8dc5254 | 2012-11-08 20:29:55 +0000 | [diff] [blame] | 892 | filename, size = self.state.pop(index) |
maruel@chromium.org | 770993b | 2012-12-11 17:16:48 +0000 | [diff] [blame] | 893 | # If the lookup was already stale, its possible the filename was not |
| 894 | # present yet. |
| 895 | self._lookup_is_stale = True |
| 896 | self._lookup.pop(filename, None) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 897 | self._removed.append(size) |
| 898 | os.remove(self.path(filename)) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 899 | except OSError as e: |
| 900 | logging.error('Error attempting to delete a file\n%s' % e) |
| 901 | |
csharp@chromium.org | 8dc5254 | 2012-11-08 20:29:55 +0000 | [diff] [blame] | 902 | def remove_lru_file(self): |
| 903 | """Removes the last recently used file.""" |
| 904 | self.remove_file_at_index(0) |
| 905 | |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 906 | def trim(self): |
| 907 | """Trims anything we don't know, make sure enough free space exists.""" |
| 908 | # Ensure maximum cache size. |
| 909 | if self.policies.max_cache_size and self.state: |
| 910 | while sum(i[1] for i in self.state) > self.policies.max_cache_size: |
| 911 | self.remove_lru_file() |
| 912 | |
| 913 | # Ensure maximum number of items in the cache. |
| 914 | if self.policies.max_items and self.state: |
| 915 | while len(self.state) > self.policies.max_items: |
| 916 | self.remove_lru_file() |
| 917 | |
| 918 | # Ensure enough free space. |
| 919 | self._free_disk = get_free_space(self.cache_dir) |
| 920 | while ( |
| 921 | self.policies.min_free_space and |
| 922 | self.state and |
| 923 | self._free_disk < self.policies.min_free_space): |
| 924 | self.remove_lru_file() |
| 925 | self._free_disk = get_free_space(self.cache_dir) |
| 926 | |
| 927 | self.save() |
| 928 | |
csharp@chromium.org | 8dc5254 | 2012-11-08 20:29:55 +0000 | [diff] [blame] | 929 | def retrieve(self, priority, item, size): |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 930 | """Retrieves a file from the remote, if not already cached, and adds it to |
| 931 | the cache. |
csharp@chromium.org | 8dc5254 | 2012-11-08 20:29:55 +0000 | [diff] [blame] | 932 | |
| 933 | If the file is in the cache, verifiy that the file is valid (i.e. it is |
| 934 | the correct size), retrieving it again if it isn't. |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 935 | """ |
| 936 | assert not '/' in item |
| 937 | path = self.path(item) |
maruel@chromium.org | 770993b | 2012-12-11 17:16:48 +0000 | [diff] [blame] | 938 | self._update_lookup() |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 939 | index = self._lookup.get(item) |
csharp@chromium.org | 8dc5254 | 2012-11-08 20:29:55 +0000 | [diff] [blame] | 940 | |
| 941 | if index is not None: |
| 942 | if not valid_file(self.path(item), size): |
| 943 | self.remove_file_at_index(index) |
csharp@chromium.org | 8dc5254 | 2012-11-08 20:29:55 +0000 | [diff] [blame] | 944 | index = None |
| 945 | else: |
| 946 | assert index < len(self.state) |
| 947 | # Was already in cache. Update it's LRU value by putting it at the end. |
maruel@chromium.org | 770993b | 2012-12-11 17:16:48 +0000 | [diff] [blame] | 948 | self._state_need_to_be_saved = True |
| 949 | self._lookup_is_stale = True |
csharp@chromium.org | 8dc5254 | 2012-11-08 20:29:55 +0000 | [diff] [blame] | 950 | self.state.append(self.state.pop(index)) |
csharp@chromium.org | 8dc5254 | 2012-11-08 20:29:55 +0000 | [diff] [blame] | 951 | |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 952 | if index is None: |
| 953 | if item in self._pending_queue: |
| 954 | # Already pending. The same object could be referenced multiple times. |
| 955 | return |
csharp@chromium.org | df2968f | 2012-11-16 20:25:37 +0000 | [diff] [blame] | 956 | self.remote.add_item(priority, item, path, size) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 957 | self._pending_queue.add(item) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 958 | |
| 959 | def add(self, filepath, obj): |
| 960 | """Forcibly adds a file to the cache.""" |
maruel@chromium.org | 770993b | 2012-12-11 17:16:48 +0000 | [diff] [blame] | 961 | self._update_lookup() |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 962 | if not obj in self._lookup: |
| 963 | link_file(self.path(obj), filepath, HARDLINK) |
| 964 | self._add(obj, True) |
| 965 | |
| 966 | def path(self, item): |
| 967 | """Returns the path to one item.""" |
| 968 | return os.path.join(self.cache_dir, item) |
| 969 | |
| 970 | def save(self): |
| 971 | """Saves the LRU ordering.""" |
maruel@chromium.org | 770993b | 2012-12-11 17:16:48 +0000 | [diff] [blame] | 972 | if self._state_need_to_be_saved: |
| 973 | json.dump(self.state, open(self.state_file, 'wb'), separators=(',',':')) |
| 974 | self._state_need_to_be_saved = False |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 975 | |
| 976 | def wait_for(self, items): |
| 977 | """Starts a loop that waits for at least one of |items| to be retrieved. |
| 978 | |
| 979 | Returns the first item retrieved. |
| 980 | """ |
| 981 | # Flush items already present. |
maruel@chromium.org | 770993b | 2012-12-11 17:16:48 +0000 | [diff] [blame] | 982 | self._update_lookup() |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 983 | for item in items: |
| 984 | if item in self._lookup: |
| 985 | return item |
| 986 | |
| 987 | assert all(i in self._pending_queue for i in items), ( |
| 988 | items, self._pending_queue) |
| 989 | # Note that: |
| 990 | # len(self._pending_queue) == |
| 991 | # ( len(self.remote._workers) - self.remote._ready + |
| 992 | # len(self._remote._queue) + len(self._remote.done)) |
| 993 | # There is no lock-free way to verify that. |
| 994 | while self._pending_queue: |
maruel@chromium.org | 13eca0b | 2013-01-22 16:42:21 +0000 | [diff] [blame] | 995 | item = self.remote.get_one_result() |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 996 | self._pending_queue.remove(item) |
| 997 | self._add(item, True) |
| 998 | if item in items: |
| 999 | return item |
| 1000 | |
| 1001 | def _add(self, item, at_end): |
| 1002 | """Adds an item in the internal state. |
| 1003 | |
| 1004 | If |at_end| is False, self._lookup becomes inconsistent and |
| 1005 | self._update_lookup() must be called. |
| 1006 | """ |
| 1007 | size = os.stat(self.path(item)).st_size |
| 1008 | self._added.append(size) |
maruel@chromium.org | 770993b | 2012-12-11 17:16:48 +0000 | [diff] [blame] | 1009 | self._state_need_to_be_saved = True |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1010 | if at_end: |
| 1011 | self.state.append((item, size)) |
| 1012 | self._lookup[item] = len(self.state) - 1 |
| 1013 | else: |
maruel@chromium.org | 770993b | 2012-12-11 17:16:48 +0000 | [diff] [blame] | 1014 | self._lookup_is_stale = True |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1015 | self.state.insert(0, (item, size)) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1016 | |
| 1017 | def _update_lookup(self): |
maruel@chromium.org | 770993b | 2012-12-11 17:16:48 +0000 | [diff] [blame] | 1018 | if self._lookup_is_stale: |
| 1019 | self._lookup = dict( |
| 1020 | (filename, index) for index, (filename, _) in enumerate(self.state)) |
| 1021 | self._lookup_is_stale = False |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1022 | |
| 1023 | |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1024 | class IsolatedFile(object): |
| 1025 | """Represents a single parsed .isolated file.""" |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1026 | def __init__(self, obj_hash): |
| 1027 | """|obj_hash| is really the sha-1 of the file.""" |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1028 | logging.debug('IsolatedFile(%s)' % obj_hash) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1029 | self.obj_hash = obj_hash |
| 1030 | # Set once all the left-side of the tree is parsed. 'Tree' here means the |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1031 | # .isolate and all the .isolated files recursively included by it with |
| 1032 | # 'includes' key. The order of each sha-1 in 'includes', each representing a |
| 1033 | # .isolated file in the hash table, is important, as the later ones are not |
| 1034 | # processed until the firsts are retrieved and read. |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1035 | self.can_fetch = False |
| 1036 | |
| 1037 | # Raw data. |
| 1038 | self.data = {} |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1039 | # A IsolatedFile instance, one per object in self.includes. |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1040 | self.children = [] |
| 1041 | |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1042 | # Set once the .isolated file is loaded. |
| 1043 | self._is_parsed = False |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1044 | # Set once the files are fetched. |
| 1045 | self.files_fetched = False |
| 1046 | |
| 1047 | def load(self, content): |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1048 | """Verifies the .isolated file is valid and loads this object with the json |
| 1049 | data. |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1050 | """ |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1051 | logging.debug('IsolatedFile.load(%s)' % self.obj_hash) |
| 1052 | assert not self._is_parsed |
| 1053 | self.data = load_isolated(content) |
| 1054 | self.children = [IsolatedFile(i) for i in self.data.get('includes', [])] |
| 1055 | self._is_parsed = True |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1056 | |
| 1057 | def fetch_files(self, cache, files): |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1058 | """Adds files in this .isolated file not present in |files| dictionary. |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1059 | |
| 1060 | Preemptively request files. |
| 1061 | |
| 1062 | Note that |files| is modified by this function. |
| 1063 | """ |
| 1064 | assert self.can_fetch |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1065 | if not self._is_parsed or self.files_fetched: |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1066 | return |
| 1067 | logging.debug('fetch_files(%s)' % self.obj_hash) |
| 1068 | for filepath, properties in self.data.get('files', {}).iteritems(): |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1069 | # Root isolated has priority on the files being mapped. In particular, |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1070 | # overriden files must not be fetched. |
| 1071 | if filepath not in files: |
| 1072 | files[filepath] = properties |
maruel@chromium.org | e5c1713 | 2012-11-21 18:18:46 +0000 | [diff] [blame] | 1073 | if 'h' in properties: |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1074 | # Preemptively request files. |
| 1075 | logging.debug('fetching %s' % filepath) |
maruel@chromium.org | e5c1713 | 2012-11-21 18:18:46 +0000 | [diff] [blame] | 1076 | cache.retrieve(Remote.MED, properties['h'], properties['s']) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1077 | self.files_fetched = True |
| 1078 | |
| 1079 | |
| 1080 | class Settings(object): |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1081 | """Results of a completely parsed .isolated file.""" |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1082 | def __init__(self): |
| 1083 | self.command = [] |
| 1084 | self.files = {} |
| 1085 | self.read_only = None |
| 1086 | self.relative_cwd = None |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1087 | # The main .isolated file, a IsolatedFile instance. |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1088 | self.root = None |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1089 | |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1090 | def load(self, cache, root_isolated_hash): |
| 1091 | """Loads the .isolated and all the included .isolated asynchronously. |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1092 | |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1093 | It enables support for "included" .isolated files. They are processed in |
| 1094 | strict order but fetched asynchronously from the cache. This is important so |
| 1095 | that a file in an included .isolated file that is overridden by an embedding |
| 1096 | .isolated file is not fetched neededlessly. The includes are fetched in one |
| 1097 | pass and the files are fetched as soon as all the ones on the left-side |
| 1098 | of the tree were fetched. |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1099 | |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1100 | The prioritization is very important here for nested .isolated files. |
| 1101 | 'includes' have the highest priority and the algorithm is optimized for both |
| 1102 | deep and wide trees. A deep one is a long link of .isolated files referenced |
| 1103 | one at a time by one item in 'includes'. A wide one has a large number of |
| 1104 | 'includes' in a single .isolated file. 'left' is defined as an included |
| 1105 | .isolated file earlier in the 'includes' list. So the order of the elements |
| 1106 | in 'includes' is important. |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1107 | """ |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1108 | self.root = IsolatedFile(root_isolated_hash) |
csharp@chromium.org | 8dc5254 | 2012-11-08 20:29:55 +0000 | [diff] [blame] | 1109 | cache.retrieve(Remote.HIGH, root_isolated_hash, UNKNOWN_FILE_SIZE) |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1110 | pending = {root_isolated_hash: self.root} |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1111 | # Keeps the list of retrieved items to refuse recursive includes. |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1112 | retrieved = [root_isolated_hash] |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1113 | |
| 1114 | def update_self(node): |
| 1115 | node.fetch_files(cache, self.files) |
| 1116 | # Grabs properties. |
| 1117 | if not self.command and node.data.get('command'): |
| 1118 | self.command = node.data['command'] |
| 1119 | if self.read_only is None and node.data.get('read_only') is not None: |
| 1120 | self.read_only = node.data['read_only'] |
| 1121 | if (self.relative_cwd is None and |
| 1122 | node.data.get('relative_cwd') is not None): |
| 1123 | self.relative_cwd = node.data['relative_cwd'] |
| 1124 | |
| 1125 | def traverse_tree(node): |
| 1126 | if node.can_fetch: |
| 1127 | if not node.files_fetched: |
| 1128 | update_self(node) |
| 1129 | will_break = False |
| 1130 | for i in node.children: |
| 1131 | if not i.can_fetch: |
| 1132 | if will_break: |
| 1133 | break |
| 1134 | # Automatically mark the first one as fetcheable. |
| 1135 | i.can_fetch = True |
| 1136 | will_break = True |
| 1137 | traverse_tree(i) |
| 1138 | |
| 1139 | while pending: |
| 1140 | item_hash = cache.wait_for(pending) |
| 1141 | item = pending.pop(item_hash) |
| 1142 | item.load(open(cache.path(item_hash), 'r').read()) |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1143 | if item_hash == root_isolated_hash: |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1144 | # It's the root item. |
| 1145 | item.can_fetch = True |
| 1146 | |
| 1147 | for new_child in item.children: |
| 1148 | h = new_child.obj_hash |
| 1149 | if h in retrieved: |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1150 | raise ConfigError('IsolatedFile %s is retrieved recursively' % h) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1151 | pending[h] = new_child |
csharp@chromium.org | 8dc5254 | 2012-11-08 20:29:55 +0000 | [diff] [blame] | 1152 | cache.retrieve(Remote.HIGH, h, UNKNOWN_FILE_SIZE) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1153 | |
| 1154 | # Traverse the whole tree to see if files can now be fetched. |
| 1155 | traverse_tree(self.root) |
| 1156 | def check(n): |
| 1157 | return all(check(x) for x in n.children) and n.files_fetched |
| 1158 | assert check(self.root) |
| 1159 | self.relative_cwd = self.relative_cwd or '' |
| 1160 | self.read_only = self.read_only or False |
| 1161 | |
| 1162 | |
csharp@chromium.org | ffd8cf0 | 2013-01-09 21:57:38 +0000 | [diff] [blame] | 1163 | def create_directories(base_directory, files): |
| 1164 | """Creates the directory structure needed by the given list of files.""" |
| 1165 | logging.debug('create_directories(%s, %d)', base_directory, len(files)) |
| 1166 | # Creates the tree of directories to create. |
| 1167 | directories = set(os.path.dirname(f) for f in files) |
| 1168 | for item in list(directories): |
| 1169 | while item: |
| 1170 | directories.add(item) |
| 1171 | item = os.path.dirname(item) |
| 1172 | for d in sorted(directories): |
| 1173 | if d: |
| 1174 | os.mkdir(os.path.join(base_directory, d)) |
| 1175 | |
| 1176 | |
| 1177 | def create_links(base_directory, files): |
| 1178 | """Creates any links needed by the given set of files.""" |
| 1179 | for filepath, properties in files: |
| 1180 | if 'link' not in properties: |
| 1181 | continue |
| 1182 | outfile = os.path.join(base_directory, filepath) |
| 1183 | # symlink doesn't exist on Windows. So the 'link' property should |
| 1184 | # never be specified for windows .isolated file. |
| 1185 | os.symlink(properties['l'], outfile) # pylint: disable=E1101 |
| 1186 | if 'm' in properties: |
| 1187 | lchmod = getattr(os, 'lchmod', None) |
| 1188 | if lchmod: |
| 1189 | lchmod(outfile, properties['m']) |
| 1190 | |
| 1191 | |
| 1192 | def setup_commands(base_directory, cwd, cmd): |
| 1193 | """Correctly adjusts and then returns the required working directory |
| 1194 | and command needed to run the test. |
| 1195 | """ |
| 1196 | assert not os.path.isabs(cwd), 'The cwd must be a relative path, got %s' % cwd |
| 1197 | cwd = os.path.join(base_directory, cwd) |
| 1198 | if not os.path.isdir(cwd): |
| 1199 | os.makedirs(cwd) |
| 1200 | |
| 1201 | # Ensure paths are correctly separated on windows. |
| 1202 | cmd[0] = cmd[0].replace('/', os.path.sep) |
| 1203 | cmd = fix_python_path(cmd) |
| 1204 | |
| 1205 | return cwd, cmd |
| 1206 | |
| 1207 | |
| 1208 | def generate_remaining_files(files): |
| 1209 | """Generates a dictionary of all the remaining files to be downloaded.""" |
| 1210 | remaining = {} |
| 1211 | for filepath, props in files: |
| 1212 | if 'h' in props: |
| 1213 | remaining.setdefault(props['h'], []).append((filepath, props)) |
| 1214 | |
| 1215 | return remaining |
| 1216 | |
| 1217 | |
| 1218 | def download_test_data(isolated_hash, target_directory, remote): |
| 1219 | """Downloads the dependencies to the given directory.""" |
| 1220 | if not os.path.exists(target_directory): |
| 1221 | os.makedirs(target_directory) |
| 1222 | |
| 1223 | settings = Settings() |
| 1224 | no_cache = NoCache(target_directory, Remote(remote)) |
| 1225 | |
| 1226 | # Download all the isolated files. |
| 1227 | with Profiler('GetIsolateds') as _prof: |
| 1228 | settings.load(no_cache, isolated_hash) |
| 1229 | |
| 1230 | if not settings.command: |
| 1231 | print >> sys.stderr, 'No command to run' |
| 1232 | return 1 |
| 1233 | |
| 1234 | with Profiler('GetRest') as _prof: |
| 1235 | create_directories(target_directory, settings.files) |
| 1236 | create_links(target_directory, settings.files.iteritems()) |
| 1237 | |
| 1238 | cwd, cmd = setup_commands(target_directory, settings.relative_cwd, |
| 1239 | settings.command[:]) |
| 1240 | |
| 1241 | remaining = generate_remaining_files(settings.files.iteritems()) |
| 1242 | |
| 1243 | # Now block on the remaining files to be downloaded and mapped. |
| 1244 | logging.info('Retrieving remaining files') |
| 1245 | last_update = time.time() |
| 1246 | while remaining: |
| 1247 | obj = no_cache.wait_for(remaining) |
| 1248 | files = remaining.pop(obj) |
| 1249 | |
| 1250 | for i, (filepath, properties) in enumerate(files): |
| 1251 | outfile = os.path.join(target_directory, filepath) |
| 1252 | logging.info(no_cache.path(obj)) |
| 1253 | |
| 1254 | if i + 1 == len(files): |
| 1255 | os.rename(no_cache.path(obj), outfile) |
| 1256 | else: |
| 1257 | shutil.copyfile(no_cache.path(obj), outfile) |
| 1258 | |
| 1259 | if 'm' in properties: |
| 1260 | # It's not set on Windows. |
| 1261 | os.chmod(outfile, properties['m']) |
| 1262 | |
| 1263 | if time.time() - last_update > DELAY_BETWEEN_UPDATES_IN_SECS: |
| 1264 | logging.info('%d files remaining...' % len(remaining)) |
| 1265 | last_update = time.time() |
| 1266 | |
| 1267 | print('.isolated files successfully downloaded and setup in %s' % |
| 1268 | target_directory) |
| 1269 | print('To run this test please run the command %s from the directory %s' % |
| 1270 | (cmd, cwd)) |
| 1271 | |
| 1272 | return 0 |
| 1273 | |
| 1274 | |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1275 | def run_tha_test(isolated_hash, cache_dir, remote, policies): |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1276 | """Downloads the dependencies in the cache, hardlinks them into a temporary |
| 1277 | directory and runs the executable. |
| 1278 | """ |
| 1279 | settings = Settings() |
| 1280 | with Cache(cache_dir, Remote(remote), policies) as cache: |
| 1281 | outdir = make_temp_dir('run_tha_test', cache_dir) |
| 1282 | try: |
| 1283 | # Initiate all the files download. |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1284 | with Profiler('GetIsolateds') as _prof: |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1285 | # Optionally support local files. |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1286 | if not RE_IS_SHA1.match(isolated_hash): |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1287 | # Adds it in the cache. While not strictly necessary, this simplifies |
| 1288 | # the rest. |
maruel@chromium.org | cb3c3d5 | 2013-03-14 18:55:30 +0000 | [diff] [blame] | 1289 | h = hashlib.sha1(open(isolated_hash, 'rb').read()).hexdigest() |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1290 | cache.add(isolated_hash, h) |
| 1291 | isolated_hash = h |
| 1292 | settings.load(cache, isolated_hash) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1293 | |
| 1294 | if not settings.command: |
| 1295 | print >> sys.stderr, 'No command to run' |
| 1296 | return 1 |
| 1297 | |
| 1298 | with Profiler('GetRest') as _prof: |
csharp@chromium.org | ffd8cf0 | 2013-01-09 21:57:38 +0000 | [diff] [blame] | 1299 | create_directories(outdir, settings.files) |
| 1300 | create_links(outdir, settings.files.iteritems()) |
| 1301 | remaining = generate_remaining_files(settings.files.iteritems()) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1302 | |
| 1303 | # Do bookkeeping while files are being downloaded in the background. |
csharp@chromium.org | ffd8cf0 | 2013-01-09 21:57:38 +0000 | [diff] [blame] | 1304 | cwd, cmd = setup_commands(outdir, settings.relative_cwd, |
| 1305 | settings.command[:]) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1306 | |
| 1307 | # Now block on the remaining files to be downloaded and mapped. |
csharp@chromium.org | 9c59ff1 | 2012-12-12 02:32:29 +0000 | [diff] [blame] | 1308 | logging.info('Retrieving remaining files') |
| 1309 | last_update = time.time() |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1310 | while remaining: |
| 1311 | obj = cache.wait_for(remaining) |
| 1312 | for filepath, properties in remaining.pop(obj): |
| 1313 | outfile = os.path.join(outdir, filepath) |
| 1314 | link_file(outfile, cache.path(obj), HARDLINK) |
maruel@chromium.org | d02e8ed | 2012-11-21 20:30:14 +0000 | [diff] [blame] | 1315 | if 'm' in properties: |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1316 | # It's not set on Windows. |
maruel@chromium.org | d02e8ed | 2012-11-21 20:30:14 +0000 | [diff] [blame] | 1317 | os.chmod(outfile, properties['m']) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1318 | |
csharp@chromium.org | 9c59ff1 | 2012-12-12 02:32:29 +0000 | [diff] [blame] | 1319 | if time.time() - last_update > DELAY_BETWEEN_UPDATES_IN_SECS: |
| 1320 | logging.info('%d files remaining...' % len(remaining)) |
| 1321 | last_update = time.time() |
| 1322 | |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1323 | if settings.read_only: |
| 1324 | make_writable(outdir, True) |
| 1325 | logging.info('Running %s, cwd=%s' % (cmd, cwd)) |
csharp@chromium.org | e217f30 | 2012-11-22 16:51:53 +0000 | [diff] [blame] | 1326 | |
| 1327 | # TODO(csharp): This should be specified somewhere else. |
| 1328 | # Add a rotating log file if one doesn't already exist. |
| 1329 | env = os.environ.copy() |
| 1330 | env.setdefault('RUN_TEST_CASES_LOG_FILE', RUN_TEST_CASES_LOG) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1331 | try: |
| 1332 | with Profiler('RunTest') as _prof: |
csharp@chromium.org | e217f30 | 2012-11-22 16:51:53 +0000 | [diff] [blame] | 1333 | return subprocess.call(cmd, cwd=cwd, env=env) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1334 | except OSError: |
| 1335 | print >> sys.stderr, 'Failed to run %s; cwd=%s' % (cmd, cwd) |
| 1336 | raise |
| 1337 | finally: |
| 1338 | rmtree(outdir) |
| 1339 | |
| 1340 | |
| 1341 | def main(): |
| 1342 | parser = optparse.OptionParser( |
| 1343 | usage='%prog <options>', description=sys.modules[__name__].__doc__) |
| 1344 | parser.add_option( |
| 1345 | '-v', '--verbose', action='count', default=0, help='Use multiple times') |
| 1346 | parser.add_option('--no-run', action='store_true', help='Skip the run part') |
| 1347 | |
csharp@chromium.org | ffd8cf0 | 2013-01-09 21:57:38 +0000 | [diff] [blame] | 1348 | group = optparse.OptionGroup(parser, 'Download') |
| 1349 | group.add_option( |
| 1350 | '--download', metavar='DEST', |
| 1351 | help='Downloads files to DEST and returns without running, instead of ' |
| 1352 | 'downloading and then running from a temporary directory.') |
| 1353 | parser.add_option_group(group) |
| 1354 | |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1355 | group = optparse.OptionGroup(parser, 'Data source') |
| 1356 | group.add_option( |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1357 | '-s', '--isolated', |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1358 | metavar='FILE', |
| 1359 | help='File/url describing what to map or run') |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1360 | # TODO(maruel): Remove once not used anymore. |
| 1361 | group.add_option( |
| 1362 | '-m', '--manifest', dest='isolated', help=optparse.SUPPRESS_HELP) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1363 | group.add_option( |
| 1364 | '-H', '--hash', |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1365 | help='Hash of the .isolated to grab from the hash table') |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1366 | parser.add_option_group(group) |
| 1367 | |
| 1368 | group.add_option( |
csharp@chromium.org | ffd8cf0 | 2013-01-09 21:57:38 +0000 | [diff] [blame] | 1369 | '-r', '--remote', metavar='URL', |
| 1370 | default= |
| 1371 | 'https://isolateserver.appspot.com/content/retrieve/default-gzip/', |
| 1372 | help='Remote where to get the items. Defaults to %default') |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1373 | group = optparse.OptionGroup(parser, 'Cache management') |
| 1374 | group.add_option( |
| 1375 | '--cache', |
| 1376 | default='cache', |
| 1377 | metavar='DIR', |
| 1378 | help='Cache directory, default=%default') |
| 1379 | group.add_option( |
| 1380 | '--max-cache-size', |
| 1381 | type='int', |
| 1382 | metavar='NNN', |
| 1383 | default=20*1024*1024*1024, |
| 1384 | help='Trim if the cache gets larger than this value, default=%default') |
| 1385 | group.add_option( |
| 1386 | '--min-free-space', |
| 1387 | type='int', |
| 1388 | metavar='NNN', |
| 1389 | default=1*1024*1024*1024, |
| 1390 | help='Trim if disk free space becomes lower than this value, ' |
| 1391 | 'default=%default') |
| 1392 | group.add_option( |
| 1393 | '--max-items', |
| 1394 | type='int', |
| 1395 | metavar='NNN', |
| 1396 | default=100000, |
| 1397 | help='Trim if more than this number of items are in the cache ' |
| 1398 | 'default=%default') |
| 1399 | parser.add_option_group(group) |
| 1400 | |
| 1401 | options, args = parser.parse_args() |
| 1402 | level = [logging.ERROR, logging.INFO, logging.DEBUG][min(2, options.verbose)] |
csharp@chromium.org | ff2a466 | 2012-11-21 20:49:32 +0000 | [diff] [blame] | 1403 | |
| 1404 | logging_console = logging.StreamHandler() |
| 1405 | logging_console.setFormatter(logging.Formatter( |
| 1406 | '%(levelname)5s %(module)15s(%(lineno)3d): %(message)s')) |
| 1407 | logging_console.setLevel(level) |
| 1408 | logging.getLogger().addHandler(logging_console) |
| 1409 | |
| 1410 | logging_rotating_file = logging.handlers.RotatingFileHandler( |
| 1411 | RUN_ISOLATED_LOG_FILE, |
| 1412 | maxBytes=10 * 1024 * 1024, backupCount=5) |
| 1413 | logging_rotating_file.setLevel(logging.DEBUG) |
| 1414 | logging_rotating_file.setFormatter(logging.Formatter( |
| 1415 | '%(asctime)s %(levelname)-8s %(module)15s(%(lineno)3d): %(message)s')) |
| 1416 | logging.getLogger().addHandler(logging_rotating_file) |
| 1417 | |
| 1418 | logging.getLogger().setLevel(logging.DEBUG) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1419 | |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1420 | if bool(options.isolated) == bool(options.hash): |
maruel@chromium.org | 5dd75dd | 2012-12-03 15:11:32 +0000 | [diff] [blame] | 1421 | logging.debug('One and only one of --isolated or --hash is required.') |
maruel@chromium.org | 0cd0b18 | 2012-10-22 13:34:15 +0000 | [diff] [blame] | 1422 | parser.error('One and only one of --isolated or --hash is required.') |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1423 | if args: |
maruel@chromium.org | 5dd75dd | 2012-12-03 15:11:32 +0000 | [diff] [blame] | 1424 | logging.debug('Unsupported args %s' % ' '.join(args)) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1425 | parser.error('Unsupported args %s' % ' '.join(args)) |
| 1426 | |
csharp@chromium.org | ffd8cf0 | 2013-01-09 21:57:38 +0000 | [diff] [blame] | 1427 | options.cache = os.path.abspath(options.cache) |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1428 | policies = CachePolicies( |
| 1429 | options.max_cache_size, options.min_free_space, options.max_items) |
csharp@chromium.org | ffd8cf0 | 2013-01-09 21:57:38 +0000 | [diff] [blame] | 1430 | |
| 1431 | if options.download: |
| 1432 | return download_test_data(options.isolated or options.hash, |
| 1433 | options.download, options.remote) |
| 1434 | else: |
| 1435 | try: |
| 1436 | return run_tha_test( |
| 1437 | options.isolated or options.hash, |
| 1438 | options.cache, |
| 1439 | options.remote, |
| 1440 | policies) |
| 1441 | except Exception, e: |
| 1442 | # Make sure any exception is logged. |
| 1443 | logging.exception(e) |
| 1444 | return 1 |
maruel@chromium.org | 9c72d4e | 2012-09-28 19:20:25 +0000 | [diff] [blame] | 1445 | |
| 1446 | |
| 1447 | if __name__ == '__main__': |
| 1448 | sys.exit(main()) |