Marc-Antoine Ruel | 34f5f28 | 2018-05-16 16:04:31 -0400 | [diff] [blame] | 1 | # Copyright 2018 The LUCI Authors. All rights reserved. |
| 2 | # Use of this source code is governed under the Apache License, Version 2.0 |
| 3 | # that can be found in the LICENSE file. |
| 4 | |
| 5 | """Define local cache policies.""" |
| 6 | |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 7 | import contextlib |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 8 | import errno |
| 9 | import io |
| 10 | import logging |
| 11 | import os |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 12 | import random |
Takuto Ikuta | 6ba1d0c | 2019-08-01 05:37:00 +0000 | [diff] [blame] | 13 | import stat |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 14 | import string |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 15 | import sys |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 16 | import time |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 17 | |
| 18 | from utils import file_path |
| 19 | from utils import fs |
| 20 | from utils import lru |
| 21 | from utils import threading_utils |
| 22 | from utils import tools |
Lei Lei | fe202df | 2019-06-11 17:33:34 +0000 | [diff] [blame] | 23 | tools.force_local_third_party() |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 24 | |
Lei Lei | fe202df | 2019-06-11 17:33:34 +0000 | [diff] [blame] | 25 | # third_party/ |
Takuto Ikuta | bf06ebf | 2019-08-02 07:28:23 +0000 | [diff] [blame] | 26 | from scandir import scandir |
Lei Lei | fe202df | 2019-06-11 17:33:34 +0000 | [diff] [blame] | 27 | import six |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 28 | |
Junji Watanabe | 5e73aab | 2020-04-09 04:20:27 +0000 | [diff] [blame] | 29 | import isolated_format |
| 30 | |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 31 | # The file size to be used when we don't know the correct file size, |
| 32 | # generally used for .isolated files. |
| 33 | UNKNOWN_FILE_SIZE = None |
| 34 | |
| 35 | |
| 36 | def file_write(path, content_generator): |
| 37 | """Writes file content as generated by content_generator. |
| 38 | |
| 39 | Creates the intermediary directory as needed. |
| 40 | |
| 41 | Returns the number of bytes written. |
| 42 | |
| 43 | Meant to be mocked out in unit tests. |
| 44 | """ |
| 45 | file_path.ensure_tree(os.path.dirname(path)) |
| 46 | total = 0 |
| 47 | with fs.open(path, 'wb') as f: |
| 48 | for d in content_generator: |
| 49 | total += len(d) |
| 50 | f.write(d) |
| 51 | return total |
| 52 | |
| 53 | |
| 54 | def is_valid_file(path, size): |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 55 | """Returns if the given files appears valid. |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 56 | |
| 57 | Currently it just checks the file exists and its size matches the expectation. |
| 58 | """ |
| 59 | if size == UNKNOWN_FILE_SIZE: |
| 60 | return fs.isfile(path) |
| 61 | try: |
| 62 | actual_size = fs.stat(path).st_size |
| 63 | except OSError as e: |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 64 | logging.warning('Can\'t read item %s, assuming it\'s invalid: %s', |
| 65 | os.path.basename(path), e) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 66 | return False |
| 67 | if size != actual_size: |
| 68 | logging.warning( |
| 69 | 'Found invalid item %s; %d != %d', |
| 70 | os.path.basename(path), actual_size, size) |
| 71 | return False |
| 72 | return True |
| 73 | |
| 74 | |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 75 | def trim_caches(caches, path, min_free_space, max_age_secs): |
| 76 | """Trims multiple caches. |
| 77 | |
| 78 | The goal here is to coherently trim all caches in a coherent LRU fashion, |
| 79 | deleting older items independent of which container they belong to. |
| 80 | |
| 81 | Two policies are enforced first: |
| 82 | - max_age_secs |
| 83 | - min_free_space |
| 84 | |
| 85 | Once that's done, then we enforce each cache's own policies. |
| 86 | |
| 87 | Returns: |
| 88 | Slice containing the size of all items evicted. |
| 89 | """ |
| 90 | min_ts = time.time() - max_age_secs if max_age_secs else 0 |
| 91 | free_disk = file_path.get_free_space(path) if min_free_space else 0 |
| 92 | total = [] |
| 93 | if min_ts or free_disk: |
| 94 | while True: |
| 95 | oldest = [(c, c.get_oldest()) for c in caches if len(c) > 0] |
| 96 | if not oldest: |
| 97 | break |
Lei Lei | fe202df | 2019-06-11 17:33:34 +0000 | [diff] [blame] | 98 | oldest.sort(key=lambda k: k[1]) |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 99 | c, ts = oldest[0] |
| 100 | if ts >= min_ts and free_disk >= min_free_space: |
| 101 | break |
| 102 | total.append(c.remove_oldest()) |
| 103 | if min_free_space: |
| 104 | free_disk = file_path.get_free_space(path) |
| 105 | # Evaluate each cache's own policies. |
| 106 | for c in caches: |
| 107 | total.extend(c.trim()) |
| 108 | return total |
| 109 | |
Takuto Ikuta | 0671dac | 2019-08-06 22:38:48 +0000 | [diff] [blame] | 110 | def _use_scandir(): |
| 111 | # Use scandir in windows for faster execution. |
| 112 | # Do not use in other OS due to crbug.com/989409 |
| 113 | return sys.platform == 'win32' |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 114 | |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 115 | |
Marc-Antoine Ruel | 33e9f10 | 2018-06-14 19:08:01 +0000 | [diff] [blame] | 116 | def _get_recursive_size(path): |
| 117 | """Returns the total data size for the specified path. |
| 118 | |
| 119 | This function can be surprisingly slow on OSX, so its output should be cached. |
| 120 | """ |
| 121 | try: |
| 122 | total = 0 |
Takuto Ikuta | 0671dac | 2019-08-06 22:38:48 +0000 | [diff] [blame] | 123 | if _use_scandir(): |
| 124 | |
| 125 | if sys.platform == 'win32': |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 126 | |
Takuto Ikuta | 0671dac | 2019-08-06 22:38:48 +0000 | [diff] [blame] | 127 | def direntIsJunction(entry): |
| 128 | # both st_file_attributes and FILE_ATTRIBUTE_REPARSE_POINT are |
| 129 | # windows-only symbols. |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 130 | return bool(entry.stat().st_file_attributes & scandir |
| 131 | .FILE_ATTRIBUTE_REPARSE_POINT) |
Takuto Ikuta | 0671dac | 2019-08-06 22:38:48 +0000 | [diff] [blame] | 132 | else: |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 133 | |
Takuto Ikuta | 0671dac | 2019-08-06 22:38:48 +0000 | [diff] [blame] | 134 | def direntIsJunction(_entry): |
| 135 | return False |
| 136 | |
Takuto Ikuta | bf06ebf | 2019-08-02 07:28:23 +0000 | [diff] [blame] | 137 | stack = [path] |
| 138 | while stack: |
| 139 | for entry in scandir.scandir(stack.pop()): |
Takuto Ikuta | 0671dac | 2019-08-06 22:38:48 +0000 | [diff] [blame] | 140 | if entry.is_symlink() or direntIsJunction(entry): |
Takuto Ikuta | bf06ebf | 2019-08-02 07:28:23 +0000 | [diff] [blame] | 141 | continue |
| 142 | if entry.is_file(): |
| 143 | total += entry.stat().st_size |
| 144 | elif entry.is_dir(): |
| 145 | stack.append(entry.path) |
| 146 | else: |
| 147 | logging.warning('non directory/file entry: %s', entry) |
| 148 | return total |
| 149 | |
Takuto Ikuta | 54c8b06 | 2019-07-31 08:38:41 +0000 | [diff] [blame] | 150 | for root, _, files in fs.walk(path): |
| 151 | for f in files: |
Takuto Ikuta | 6ba1d0c | 2019-08-01 05:37:00 +0000 | [diff] [blame] | 152 | st = fs.lstat(os.path.join(root, f)) |
| 153 | if stat.S_ISLNK(st.st_mode): |
| 154 | continue |
| 155 | total += st.st_size |
Marc-Antoine Ruel | 33e9f10 | 2018-06-14 19:08:01 +0000 | [diff] [blame] | 156 | return total |
| 157 | except (IOError, OSError, UnicodeEncodeError) as exc: |
| 158 | logging.warning('Exception while getting the size of %s:\n%s', path, exc) |
| 159 | return None |
| 160 | |
| 161 | |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 162 | class NamedCacheError(Exception): |
| 163 | """Named cache specific error.""" |
| 164 | |
| 165 | |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 166 | class NoMoreSpace(Exception): |
| 167 | """Not enough space to map the whole directory.""" |
| 168 | pass |
| 169 | |
Marc-Antoine Ruel | 34f5f28 | 2018-05-16 16:04:31 -0400 | [diff] [blame] | 170 | |
| 171 | class CachePolicies(object): |
| 172 | def __init__(self, max_cache_size, min_free_space, max_items, max_age_secs): |
| 173 | """Common caching policies for the multiple caches (isolated, named, cipd). |
| 174 | |
| 175 | Arguments: |
| 176 | - max_cache_size: Trim if the cache gets larger than this value. If 0, the |
| 177 | cache is effectively a leak. |
| 178 | - min_free_space: Trim if disk free space becomes lower than this value. If |
| 179 | 0, it will unconditionally fill the disk. |
| 180 | - max_items: Maximum number of items to keep in the cache. If 0, do not |
| 181 | enforce a limit. |
| 182 | - max_age_secs: Maximum age an item is kept in the cache until it is |
| 183 | automatically evicted. Having a lot of dead luggage slows |
| 184 | everything down. |
| 185 | """ |
| 186 | self.max_cache_size = max_cache_size |
| 187 | self.min_free_space = min_free_space |
| 188 | self.max_items = max_items |
| 189 | self.max_age_secs = max_age_secs |
| 190 | |
| 191 | def __str__(self): |
Takuto Ikuta | a953f27 | 2020-01-20 02:59:17 +0000 | [diff] [blame] | 192 | return ('CachePolicies(max_cache_size=%s (%.3f GiB); max_items=%s; ' |
| 193 | 'min_free_space=%s (%.3f GiB); max_age_secs=%s)') % ( |
| 194 | self.max_cache_size, float(self.max_cache_size) / 1024**3, |
| 195 | self.max_items, self.min_free_space, |
| 196 | float(self.min_free_space) / 1024**3, self.max_age_secs) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 197 | |
| 198 | |
| 199 | class CacheMiss(Exception): |
| 200 | """Raised when an item is not in cache.""" |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 201 | def __init__(self, digest): |
| 202 | self.digest = digest |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 203 | super(CacheMiss, |
| 204 | self).__init__('Item with digest %r is not found in cache' % digest) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 205 | |
| 206 | |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 207 | class Cache(object): |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 208 | |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 209 | def __init__(self, cache_dir): |
| 210 | if cache_dir is not None: |
Takuto Ikuta | 95459dd | 2019-10-29 12:39:47 +0000 | [diff] [blame] | 211 | assert isinstance(cache_dir, six.text_type), cache_dir |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 212 | assert file_path.isabs(cache_dir), cache_dir |
| 213 | self.cache_dir = cache_dir |
| 214 | self._lock = threading_utils.LockWithAssert() |
| 215 | # Profiling values. |
| 216 | self._added = [] |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 217 | self._used = [] |
| 218 | |
Marc-Antoine Ruel | 6c3be5a | 2018-09-04 17:19:59 +0000 | [diff] [blame] | 219 | def __nonzero__(self): |
| 220 | """A cache is always True. |
| 221 | |
| 222 | Otherwise it falls back to __len__, which is surprising. |
| 223 | """ |
| 224 | return True |
| 225 | |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 226 | def __len__(self): |
| 227 | """Returns the number of entries in the cache.""" |
| 228 | raise NotImplementedError() |
| 229 | |
| 230 | def __iter__(self): |
| 231 | """Iterates over all the entries names.""" |
| 232 | raise NotImplementedError() |
| 233 | |
| 234 | def __contains__(self, name): |
| 235 | """Returns if an entry is in the cache.""" |
| 236 | raise NotImplementedError() |
| 237 | |
| 238 | @property |
| 239 | def total_size(self): |
| 240 | """Returns the total size of the cache in bytes.""" |
| 241 | raise NotImplementedError() |
| 242 | |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 243 | @property |
| 244 | def added(self): |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 245 | """Returns a list of the size for each entry added.""" |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 246 | with self._lock: |
| 247 | return self._added[:] |
| 248 | |
| 249 | @property |
| 250 | def used(self): |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 251 | """Returns a list of the size for each entry used.""" |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 252 | with self._lock: |
| 253 | return self._used[:] |
| 254 | |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 255 | def get_oldest(self): |
| 256 | """Returns timestamp of oldest cache entry or None. |
| 257 | |
| 258 | Returns: |
| 259 | Timestamp of the oldest item. |
| 260 | |
| 261 | Used for manual trimming. |
| 262 | """ |
| 263 | raise NotImplementedError() |
| 264 | |
| 265 | def remove_oldest(self): |
| 266 | """Removes the oldest item from the cache. |
| 267 | |
| 268 | Returns: |
| 269 | Size of the oldest item. |
| 270 | |
| 271 | Used for manual trimming. |
| 272 | """ |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 273 | raise NotImplementedError() |
| 274 | |
Marc-Antoine Ruel | 29db845 | 2018-08-01 17:46:33 +0000 | [diff] [blame] | 275 | def save(self): |
| 276 | """Saves the current cache to disk.""" |
| 277 | raise NotImplementedError() |
| 278 | |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 279 | def trim(self): |
Marc-Antoine Ruel | 29db845 | 2018-08-01 17:46:33 +0000 | [diff] [blame] | 280 | """Enforces cache policies, then calls save(). |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 281 | |
| 282 | Returns: |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 283 | Slice with the size of evicted items. |
| 284 | """ |
| 285 | raise NotImplementedError() |
| 286 | |
| 287 | def cleanup(self): |
Marc-Antoine Ruel | 29db845 | 2018-08-01 17:46:33 +0000 | [diff] [blame] | 288 | """Deletes any corrupted item from the cache, then calls trim(), then |
| 289 | save(). |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 290 | |
| 291 | It is assumed to take significantly more time than trim(). |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 292 | """ |
| 293 | raise NotImplementedError() |
| 294 | |
| 295 | |
| 296 | class ContentAddressedCache(Cache): |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 297 | """Content addressed cache that stores objects temporarily. |
| 298 | |
| 299 | It can be accessed concurrently from multiple threads, so it should protect |
| 300 | its internal state with some lock. |
| 301 | """ |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 302 | |
| 303 | def __enter__(self): |
| 304 | """Context manager interface.""" |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 305 | # TODO(maruel): Remove. |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 306 | return self |
| 307 | |
| 308 | def __exit__(self, _exc_type, _exec_value, _traceback): |
| 309 | """Context manager interface.""" |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 310 | # TODO(maruel): Remove. |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 311 | return False |
| 312 | |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 313 | def touch(self, digest, size): |
| 314 | """Ensures item is not corrupted and updates its LRU position. |
| 315 | |
| 316 | Arguments: |
| 317 | digest: hash digest of item to check. |
| 318 | size: expected size of this item. |
| 319 | |
| 320 | Returns: |
| 321 | True if item is in cache and not corrupted. |
| 322 | """ |
| 323 | raise NotImplementedError() |
| 324 | |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 325 | def getfileobj(self, digest): |
| 326 | """Returns a readable file like object. |
| 327 | |
| 328 | If file exists on the file system it will have a .name attribute with an |
| 329 | absolute path to the file. |
| 330 | """ |
| 331 | raise NotImplementedError() |
| 332 | |
| 333 | def write(self, digest, content): |
| 334 | """Reads data from |content| generator and stores it in cache. |
| 335 | |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 336 | It is possible to write to an object that already exists. It may be |
| 337 | ignored (sent to /dev/null) but the timestamp is still updated. |
| 338 | |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 339 | Returns digest to simplify chaining. |
| 340 | """ |
| 341 | raise NotImplementedError() |
| 342 | |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 343 | |
| 344 | class MemoryContentAddressedCache(ContentAddressedCache): |
| 345 | """ContentAddressedCache implementation that stores everything in memory.""" |
| 346 | |
Lei Lei | fe202df | 2019-06-11 17:33:34 +0000 | [diff] [blame] | 347 | def __init__(self, file_mode_mask=0o500): |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 348 | """Args: |
| 349 | file_mode_mask: bit mask to AND file mode with. Default value will make |
| 350 | all mapped files to be read only. |
| 351 | """ |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 352 | super(MemoryContentAddressedCache, self).__init__(None) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 353 | self._file_mode_mask = file_mode_mask |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 354 | # Items in a LRU lookup dict(digest: size). |
| 355 | self._lru = lru.LRUDict() |
| 356 | |
| 357 | # Cache interface implementation. |
| 358 | |
| 359 | def __len__(self): |
| 360 | with self._lock: |
| 361 | return len(self._lru) |
| 362 | |
| 363 | def __iter__(self): |
| 364 | # This is not thread-safe. |
| 365 | return self._lru.__iter__() |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 366 | |
| 367 | def __contains__(self, digest): |
| 368 | with self._lock: |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 369 | return digest in self._lru |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 370 | |
| 371 | @property |
| 372 | def total_size(self): |
| 373 | with self._lock: |
Marc-Antoine Ruel | 04903a3 | 2019-10-09 21:09:25 +0000 | [diff] [blame] | 374 | return sum(len(i) for i in self._lru.values()) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 375 | |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 376 | def get_oldest(self): |
| 377 | with self._lock: |
| 378 | try: |
| 379 | # (key, (value, ts)) |
| 380 | return self._lru.get_oldest()[1][1] |
| 381 | except KeyError: |
| 382 | return None |
| 383 | |
| 384 | def remove_oldest(self): |
| 385 | with self._lock: |
| 386 | # TODO(maruel): Update self._added. |
| 387 | # (key, (value, ts)) |
| 388 | return len(self._lru.pop_oldest()[1][0]) |
| 389 | |
Marc-Antoine Ruel | 29db845 | 2018-08-01 17:46:33 +0000 | [diff] [blame] | 390 | def save(self): |
| 391 | pass |
| 392 | |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 393 | def trim(self): |
| 394 | """Trimming is not implemented for MemoryContentAddressedCache.""" |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 395 | return [] |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 396 | |
| 397 | def cleanup(self): |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 398 | """Cleaning is irrelevant, as there's no stateful serialization.""" |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 399 | pass |
| 400 | |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 401 | # ContentAddressedCache interface implementation. |
| 402 | |
| 403 | def __contains__(self, digest): |
| 404 | with self._lock: |
| 405 | return digest in self._lru |
| 406 | |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 407 | def touch(self, digest, size): |
| 408 | with self._lock: |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 409 | try: |
| 410 | self._lru.touch(digest) |
| 411 | except KeyError: |
| 412 | return False |
| 413 | return True |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 414 | |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 415 | def getfileobj(self, digest): |
| 416 | with self._lock: |
| 417 | try: |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 418 | d = self._lru[digest] |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 419 | except KeyError: |
| 420 | raise CacheMiss(digest) |
| 421 | self._used.append(len(d)) |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 422 | self._lru.touch(digest) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 423 | return io.BytesIO(d) |
| 424 | |
| 425 | def write(self, digest, content): |
| 426 | # Assemble whole stream before taking the lock. |
Lei Lei | 73a5f73 | 2020-03-23 20:36:14 +0000 | [diff] [blame] | 427 | data = six.b('').join(content) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 428 | with self._lock: |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 429 | self._lru.add(digest, data) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 430 | self._added.append(len(data)) |
| 431 | return digest |
| 432 | |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 433 | |
| 434 | class DiskContentAddressedCache(ContentAddressedCache): |
| 435 | """Stateful LRU cache in a flat hash table in a directory. |
| 436 | |
| 437 | Saves its state as json file. |
| 438 | """ |
| 439 | STATE_FILE = u'state.json' |
| 440 | |
Marc-Antoine Ruel | 79d4219 | 2019-02-06 19:24:16 +0000 | [diff] [blame] | 441 | def __init__(self, cache_dir, policies, trim, time_fn=None): |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 442 | """ |
| 443 | Arguments: |
| 444 | cache_dir: directory where to place the cache. |
| 445 | policies: CachePolicies instance, cache retention policies. |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 446 | trim: if True to enforce |policies| right away. |
Marc-Antoine Ruel | 79d4219 | 2019-02-06 19:24:16 +0000 | [diff] [blame] | 447 | It can be done later by calling trim() explicitly. |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 448 | """ |
| 449 | # All protected methods (starting with '_') except _path should be called |
| 450 | # with self._lock held. |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 451 | super(DiskContentAddressedCache, self).__init__(cache_dir) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 452 | self.policies = policies |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 453 | self.state_file = os.path.join(cache_dir, self.STATE_FILE) |
| 454 | # Items in a LRU lookup dict(digest: size). |
| 455 | self._lru = lru.LRUDict() |
| 456 | # Current cached free disk space. It is updated by self._trim(). |
| 457 | file_path.ensure_tree(self.cache_dir) |
| 458 | self._free_disk = file_path.get_free_space(self.cache_dir) |
| 459 | # The first item in the LRU cache that must not be evicted during this run |
| 460 | # since it was referenced. All items more recent that _protected in the LRU |
| 461 | # cache are also inherently protected. It could be a set() of all items |
| 462 | # referenced but this increases memory usage without a use case. |
| 463 | self._protected = None |
| 464 | # Cleanup operations done by self._load(), if any. |
| 465 | self._operations = [] |
| 466 | with tools.Profiler('Setup'): |
| 467 | with self._lock: |
| 468 | self._load(trim, time_fn) |
| 469 | |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 470 | # Cache interface implementation. |
| 471 | |
| 472 | def __len__(self): |
| 473 | with self._lock: |
| 474 | return len(self._lru) |
| 475 | |
| 476 | def __iter__(self): |
| 477 | # This is not thread-safe. |
| 478 | return self._lru.__iter__() |
| 479 | |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 480 | def __contains__(self, digest): |
| 481 | with self._lock: |
| 482 | return digest in self._lru |
| 483 | |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 484 | @property |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 485 | def total_size(self): |
| 486 | with self._lock: |
Marc-Antoine Ruel | 04903a3 | 2019-10-09 21:09:25 +0000 | [diff] [blame] | 487 | return sum(self._lru.values()) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 488 | |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 489 | def get_oldest(self): |
| 490 | with self._lock: |
| 491 | try: |
| 492 | # (key, (value, ts)) |
| 493 | return self._lru.get_oldest()[1][1] |
| 494 | except KeyError: |
| 495 | return None |
| 496 | |
| 497 | def remove_oldest(self): |
| 498 | with self._lock: |
| 499 | # TODO(maruel): Update self._added. |
| 500 | return self._remove_lru_file(True) |
| 501 | |
Marc-Antoine Ruel | 29db845 | 2018-08-01 17:46:33 +0000 | [diff] [blame] | 502 | def save(self): |
| 503 | with self._lock: |
| 504 | return self._save() |
| 505 | |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 506 | def trim(self): |
| 507 | """Forces retention policies.""" |
| 508 | with self._lock: |
| 509 | return self._trim() |
| 510 | |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 511 | def cleanup(self): |
| 512 | """Cleans up the cache directory. |
| 513 | |
| 514 | Ensures there is no unknown files in cache_dir. |
| 515 | Ensures the read-only bits are set correctly. |
| 516 | |
| 517 | At that point, the cache was already loaded, trimmed to respect cache |
| 518 | policies. |
| 519 | """ |
| 520 | with self._lock: |
Lei Lei | fe202df | 2019-06-11 17:33:34 +0000 | [diff] [blame] | 521 | fs.chmod(self.cache_dir, 0o700) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 522 | # Ensure that all files listed in the state still exist and add new ones. |
Marc-Antoine Ruel | 09a76e4 | 2018-06-14 19:02:00 +0000 | [diff] [blame] | 523 | previous = set(self._lru) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 524 | # It'd be faster if there were a readdir() function. |
| 525 | for filename in fs.listdir(self.cache_dir): |
| 526 | if filename == self.STATE_FILE: |
Lei Lei | fe202df | 2019-06-11 17:33:34 +0000 | [diff] [blame] | 527 | fs.chmod(os.path.join(self.cache_dir, filename), 0o600) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 528 | continue |
| 529 | if filename in previous: |
Lei Lei | fe202df | 2019-06-11 17:33:34 +0000 | [diff] [blame] | 530 | fs.chmod(os.path.join(self.cache_dir, filename), 0o400) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 531 | previous.remove(filename) |
| 532 | continue |
| 533 | |
| 534 | # An untracked file. Delete it. |
| 535 | logging.warning('Removing unknown file %s from cache', filename) |
| 536 | p = self._path(filename) |
| 537 | if fs.isdir(p): |
| 538 | try: |
| 539 | file_path.rmtree(p) |
| 540 | except OSError: |
| 541 | pass |
| 542 | else: |
| 543 | file_path.try_remove(p) |
| 544 | continue |
| 545 | |
| 546 | if previous: |
| 547 | # Filter out entries that were not found. |
| 548 | logging.warning('Removed %d lost files', len(previous)) |
| 549 | for filename in previous: |
| 550 | self._lru.pop(filename) |
| 551 | self._save() |
| 552 | |
Junji Watanabe | 5e73aab | 2020-04-09 04:20:27 +0000 | [diff] [blame] | 553 | # Verify hash of every single item to detect corruption. the corrupted |
| 554 | # files will be evicted. |
| 555 | with self._lock: |
| 556 | for digest, (_, timestamp) in self._lru._items.items(): |
| 557 | # verify only if the mtime is grather than the timestamp in state.json |
| 558 | # to avoid take too long time. |
| 559 | if self._get_mtime(digest) <= timestamp: |
Quinten Yearsley | 0bc84ce | 2020-04-09 22:38:08 +0000 | [diff] [blame] | 560 | continue |
Junji Watanabe | 5e73aab | 2020-04-09 04:20:27 +0000 | [diff] [blame] | 561 | logging.warning('Item has been modified. item: %s', digest) |
| 562 | if self._is_valid_hash(digest): |
Quinten Yearsley | 0bc84ce | 2020-04-09 22:38:08 +0000 | [diff] [blame] | 563 | # Update timestamp in state.json |
| 564 | self._lru.touch(digest) |
| 565 | continue |
Junji Watanabe | 5e73aab | 2020-04-09 04:20:27 +0000 | [diff] [blame] | 566 | # remove corrupted file from LRU and file system |
| 567 | self._lru.pop(digest) |
| 568 | self._delete_file(digest, UNKNOWN_FILE_SIZE) |
| 569 | logging.error('Deleted corrupted item: %s', digest) |
| 570 | self._save() |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 571 | |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 572 | # ContentAddressedCache interface implementation. |
| 573 | |
| 574 | def __contains__(self, digest): |
| 575 | with self._lock: |
| 576 | return digest in self._lru |
| 577 | |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 578 | def touch(self, digest, size): |
| 579 | """Verifies an actual file is valid and bumps its LRU position. |
| 580 | |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 581 | Returns False if the file is missing or invalid. |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 582 | |
| 583 | Note that is doesn't compute the hash so it could still be corrupted if the |
| 584 | file size didn't change. |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 585 | """ |
| 586 | # Do the check outside the lock. |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 587 | looks_valid = is_valid_file(self._path(digest), size) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 588 | |
| 589 | # Update its LRU position. |
| 590 | with self._lock: |
| 591 | if digest not in self._lru: |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 592 | if looks_valid: |
| 593 | # Exists but not in the LRU anymore. |
| 594 | self._delete_file(digest, size) |
| 595 | return False |
| 596 | if not looks_valid: |
| 597 | self._lru.pop(digest) |
| 598 | # Exists but not in the LRU anymore. |
| 599 | self._delete_file(digest, size) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 600 | return False |
| 601 | self._lru.touch(digest) |
| 602 | self._protected = self._protected or digest |
| 603 | return True |
| 604 | |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 605 | def getfileobj(self, digest): |
| 606 | try: |
| 607 | f = fs.open(self._path(digest), 'rb') |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 608 | except IOError: |
| 609 | raise CacheMiss(digest) |
Vadim Shtayura | 33054fa | 2018-11-01 12:47:59 +0000 | [diff] [blame] | 610 | with self._lock: |
| 611 | try: |
| 612 | self._used.append(self._lru[digest]) |
| 613 | except KeyError: |
| 614 | # If the digest is not actually in _lru, assume it is a cache miss. |
| 615 | # Existing file will be overwritten by whoever uses the cache and added |
| 616 | # to _lru. |
| 617 | f.close() |
| 618 | raise CacheMiss(digest) |
| 619 | return f |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 620 | |
| 621 | def write(self, digest, content): |
| 622 | assert content is not None |
| 623 | with self._lock: |
| 624 | self._protected = self._protected or digest |
| 625 | path = self._path(digest) |
| 626 | # A stale broken file may remain. It is possible for the file to have write |
| 627 | # access bit removed which would cause the file_write() call to fail to open |
| 628 | # in write mode. Take no chance here. |
| 629 | file_path.try_remove(path) |
| 630 | try: |
| 631 | size = file_write(path, content) |
| 632 | except: |
| 633 | # There are two possible places were an exception can occur: |
| 634 | # 1) Inside |content| generator in case of network or unzipping errors. |
| 635 | # 2) Inside file_write itself in case of disk IO errors. |
| 636 | # In any case delete an incomplete file and propagate the exception to |
| 637 | # caller, it will be logged there. |
| 638 | file_path.try_remove(path) |
| 639 | raise |
| 640 | # Make the file read-only in the cache. This has a few side-effects since |
| 641 | # the file node is modified, so every directory entries to this file becomes |
| 642 | # read-only. It's fine here because it is a new file. |
| 643 | file_path.set_read_only(path, True) |
| 644 | with self._lock: |
| 645 | self._add(digest, size) |
| 646 | return digest |
| 647 | |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 648 | # Internal functions. |
| 649 | |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 650 | def _load(self, trim, time_fn): |
| 651 | """Loads state of the cache from json file. |
| 652 | |
| 653 | If cache_dir does not exist on disk, it is created. |
| 654 | """ |
| 655 | self._lock.assert_locked() |
| 656 | |
| 657 | if not fs.isfile(self.state_file): |
| 658 | if not fs.isdir(self.cache_dir): |
| 659 | fs.makedirs(self.cache_dir) |
| 660 | else: |
| 661 | # Load state of the cache. |
| 662 | try: |
| 663 | self._lru = lru.LRUDict.load(self.state_file) |
| 664 | except ValueError as err: |
| 665 | logging.error('Failed to load cache state: %s' % (err,)) |
Takuto Ikuta | eccc88c | 2019-12-13 14:46:32 +0000 | [diff] [blame] | 666 | # Don't want to keep broken cache dir. |
| 667 | file_path.rmtree(self.cache_dir) |
| 668 | fs.makedirs(self.cache_dir) |
Matt Kotsenas | efe3009 | 2020-03-19 01:12:55 +0000 | [diff] [blame] | 669 | self._free_disk = file_path.get_free_space(self.cache_dir) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 670 | if time_fn: |
| 671 | self._lru.time_fn = time_fn |
| 672 | if trim: |
| 673 | self._trim() |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 674 | |
| 675 | def _save(self): |
| 676 | """Saves the LRU ordering.""" |
| 677 | self._lock.assert_locked() |
| 678 | if sys.platform != 'win32': |
| 679 | d = os.path.dirname(self.state_file) |
| 680 | if fs.isdir(d): |
| 681 | # Necessary otherwise the file can't be created. |
| 682 | file_path.set_read_only(d, False) |
| 683 | if fs.isfile(self.state_file): |
| 684 | file_path.set_read_only(self.state_file, False) |
| 685 | self._lru.save(self.state_file) |
| 686 | |
| 687 | def _trim(self): |
| 688 | """Trims anything we don't know, make sure enough free space exists.""" |
| 689 | self._lock.assert_locked() |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 690 | evicted = [] |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 691 | |
| 692 | # Trim old items. |
| 693 | if self.policies.max_age_secs: |
| 694 | cutoff = self._lru.time_fn() - self.policies.max_age_secs |
| 695 | while self._lru: |
| 696 | oldest = self._lru.get_oldest() |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 697 | # (key, (data, ts) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 698 | if oldest[1][1] >= cutoff: |
| 699 | break |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 700 | evicted.append(self._remove_lru_file(True)) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 701 | |
| 702 | # Ensure maximum cache size. |
| 703 | if self.policies.max_cache_size: |
Marc-Antoine Ruel | 04903a3 | 2019-10-09 21:09:25 +0000 | [diff] [blame] | 704 | total_size = sum(self._lru.values()) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 705 | while total_size > self.policies.max_cache_size: |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 706 | e = self._remove_lru_file(True) |
| 707 | evicted.append(e) |
| 708 | total_size -= e |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 709 | |
| 710 | # Ensure maximum number of items in the cache. |
| 711 | if self.policies.max_items and len(self._lru) > self.policies.max_items: |
Marc-Antoine Ruel | 0fdee22 | 2019-10-10 14:42:40 +0000 | [diff] [blame] | 712 | for _ in range(len(self._lru) - self.policies.max_items): |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 713 | evicted.append(self._remove_lru_file(True)) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 714 | |
| 715 | # Ensure enough free space. |
| 716 | self._free_disk = file_path.get_free_space(self.cache_dir) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 717 | while ( |
| 718 | self.policies.min_free_space and |
| 719 | self._lru and |
| 720 | self._free_disk < self.policies.min_free_space): |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 721 | # self._free_disk is updated by this call. |
| 722 | evicted.append(self._remove_lru_file(True)) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 723 | |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 724 | if evicted: |
Marc-Antoine Ruel | 04903a3 | 2019-10-09 21:09:25 +0000 | [diff] [blame] | 725 | total_usage = sum(self._lru.values()) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 726 | usage_percent = 0. |
| 727 | if total_usage: |
| 728 | usage_percent = 100. * float(total_usage) / self.policies.max_cache_size |
| 729 | |
| 730 | logging.warning( |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 731 | 'Trimmed %d file(s) (%.1fkb) due to not enough free disk space:' |
| 732 | ' %.1fkb free, %.1fkb cache (%.1f%% of its maximum capacity of ' |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 733 | '%.1fkb)', len(evicted), |
| 734 | sum(evicted) / 1024., self._free_disk / 1024., total_usage / 1024., |
| 735 | usage_percent, self.policies.max_cache_size / 1024.) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 736 | self._save() |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 737 | return evicted |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 738 | |
| 739 | def _path(self, digest): |
| 740 | """Returns the path to one item.""" |
| 741 | return os.path.join(self.cache_dir, digest) |
| 742 | |
| 743 | def _remove_lru_file(self, allow_protected): |
Quinten Yearsley | 0bc84ce | 2020-04-09 22:38:08 +0000 | [diff] [blame] | 744 | """Removes the latest recently used file and returns its size. |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 745 | |
| 746 | Updates self._free_disk. |
| 747 | """ |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 748 | self._lock.assert_locked() |
| 749 | try: |
Takuto Ikuta | e40f76a | 2020-01-20 01:22:17 +0000 | [diff] [blame] | 750 | digest, _ = self._lru.get_oldest() |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 751 | if not allow_protected and digest == self._protected: |
Takuto Ikuta | e40f76a | 2020-01-20 01:22:17 +0000 | [diff] [blame] | 752 | total_size = sum(self._lru.values()) |
| 753 | msg = ('Not enough space to fetch the whole isolated tree.\n' |
Takuto Ikuta | a953f27 | 2020-01-20 02:59:17 +0000 | [diff] [blame] | 754 | ' %s\n cache=%d bytes (%.3f GiB), %d items; ' |
| 755 | '%s bytes (%.3f GiB) free_space') % ( |
| 756 | self.policies, total_size, float(total_size) / 1024**3, |
| 757 | len(self._lru), self._free_disk, |
| 758 | float(self._free_disk) / 1024**3) |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 759 | raise NoMoreSpace(msg) |
| 760 | except KeyError: |
| 761 | # That means an internal error. |
| 762 | raise NoMoreSpace('Nothing to remove, can\'t happend') |
| 763 | digest, (size, _) = self._lru.pop_oldest() |
| 764 | logging.debug('Removing LRU file %s', digest) |
| 765 | self._delete_file(digest, size) |
| 766 | return size |
| 767 | |
| 768 | def _add(self, digest, size=UNKNOWN_FILE_SIZE): |
| 769 | """Adds an item into LRU cache marking it as a newest one.""" |
| 770 | self._lock.assert_locked() |
| 771 | if size == UNKNOWN_FILE_SIZE: |
| 772 | size = fs.stat(self._path(digest)).st_size |
| 773 | self._added.append(size) |
| 774 | self._lru.add(digest, size) |
| 775 | self._free_disk -= size |
| 776 | # Do a quicker version of self._trim(). It only enforces free disk space, |
| 777 | # not cache size limits. It doesn't actually look at real free disk space, |
| 778 | # only uses its cache values. self._trim() will be called later to enforce |
| 779 | # real trimming but doing this quick version here makes it possible to map |
| 780 | # an isolated that is larger than the current amount of free disk space when |
| 781 | # the cache size is already large. |
Junji Watanabe | 38b28b0 | 2020-04-23 10:23:30 +0000 | [diff] [blame] | 782 | while (self.policies.min_free_space and self._lru and |
| 783 | self._free_disk < self.policies.min_free_space): |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 784 | # self._free_disk is updated by this call. |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 785 | if self._remove_lru_file(False) == -1: |
| 786 | break |
| 787 | |
| 788 | def _delete_file(self, digest, size=UNKNOWN_FILE_SIZE): |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 789 | """Deletes cache file from the file system. |
| 790 | |
| 791 | Updates self._free_disk. |
| 792 | """ |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 793 | self._lock.assert_locked() |
| 794 | try: |
| 795 | if size == UNKNOWN_FILE_SIZE: |
| 796 | try: |
| 797 | size = fs.stat(self._path(digest)).st_size |
| 798 | except OSError: |
| 799 | size = 0 |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 800 | if file_path.try_remove(self._path(digest)): |
| 801 | self._free_disk += size |
Marc-Antoine Ruel | 2666d9c | 2018-05-18 13:52:02 -0400 | [diff] [blame] | 802 | except OSError as e: |
| 803 | if e.errno != errno.ENOENT: |
| 804 | logging.error('Error attempting to delete a file %s:\n%s' % (digest, e)) |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 805 | |
Junji Watanabe | 5e73aab | 2020-04-09 04:20:27 +0000 | [diff] [blame] | 806 | def _get_mtime(self, digest): |
| 807 | """Get mtime of cache file.""" |
| 808 | return os.path.getmtime(self._path(digest)) |
| 809 | |
| 810 | def _is_valid_hash(self, digest): |
| 811 | """Verify digest with supported hash algos.""" |
| 812 | for _, algo in isolated_format.SUPPORTED_ALGOS.items(): |
Quinten Yearsley | 0bc84ce | 2020-04-09 22:38:08 +0000 | [diff] [blame] | 813 | if digest == isolated_format.hash_file(self._path(digest), algo): |
| 814 | return True |
Junji Watanabe | 5e73aab | 2020-04-09 04:20:27 +0000 | [diff] [blame] | 815 | return False |
| 816 | |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 817 | |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 818 | class NamedCache(Cache): |
| 819 | """Manages cache directories. |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 820 | |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 821 | A cache entry is a tuple (name, path), where |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 822 | name is a short identifier that describes the contents of the cache, e.g. |
| 823 | "git_v8" could be all git repositories required by v8 builds, or |
| 824 | "build_chromium" could be build artefacts of the Chromium. |
| 825 | path is a directory path relative to the task run dir. Cache installation |
| 826 | puts the requested cache directory at the path. |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 827 | """ |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 828 | _DIR_ALPHABET = string.ascii_letters + string.digits |
| 829 | STATE_FILE = u'state.json' |
Marc-Antoine Ruel | 9a518d0 | 2018-06-16 14:41:12 +0000 | [diff] [blame] | 830 | NAMED_DIR = u'named' |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 831 | |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 832 | def __init__(self, cache_dir, policies, time_fn=None): |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 833 | """Initializes NamedCaches. |
| 834 | |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 835 | Arguments: |
| 836 | - cache_dir is a directory for persistent cache storage. |
| 837 | - policies is a CachePolicies instance. |
| 838 | - time_fn is a function that returns timestamp (float) and used to take |
| 839 | timestamps when new caches are requested. Used in unit tests. |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 840 | """ |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 841 | super(NamedCache, self).__init__(cache_dir) |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 842 | self._policies = policies |
Marc-Antoine Ruel | 33e9f10 | 2018-06-14 19:08:01 +0000 | [diff] [blame] | 843 | # LRU {cache_name -> tuple(cache_location, size)} |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 844 | self.state_file = os.path.join(cache_dir, self.STATE_FILE) |
| 845 | self._lru = lru.LRUDict() |
| 846 | if not fs.isdir(self.cache_dir): |
| 847 | fs.makedirs(self.cache_dir) |
Marc-Antoine Ruel | 957c7c2 | 2019-01-25 22:21:05 +0000 | [diff] [blame] | 848 | elif fs.isfile(self.state_file): |
Marc-Antoine Ruel | 3543e21 | 2018-05-23 01:04:34 +0000 | [diff] [blame] | 849 | try: |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 850 | self._lru = lru.LRUDict.load(self.state_file) |
| 851 | except ValueError: |
Marc-Antoine Ruel | 44699b3 | 2018-09-24 23:31:50 +0000 | [diff] [blame] | 852 | logging.exception( |
| 853 | 'NamedCache: failed to load named cache state file; obliterating') |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 854 | file_path.rmtree(self.cache_dir) |
Takuto Ikuta | 568ddb2 | 2020-01-20 23:24:16 +0000 | [diff] [blame] | 855 | fs.makedirs(self.cache_dir) |
Marc-Antoine Ruel | 33e9f10 | 2018-06-14 19:08:01 +0000 | [diff] [blame] | 856 | with self._lock: |
| 857 | self._try_upgrade() |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 858 | if time_fn: |
| 859 | self._lru.time_fn = time_fn |
| 860 | |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 861 | @property |
| 862 | def available(self): |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 863 | """Returns a set of names of available caches.""" |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 864 | with self._lock: |
Marc-Antoine Ruel | 09a76e4 | 2018-06-14 19:02:00 +0000 | [diff] [blame] | 865 | return set(self._lru) |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 866 | |
Marc-Antoine Ruel | 97430be | 2019-01-25 18:26:34 +0000 | [diff] [blame] | 867 | def install(self, dst, name): |
| 868 | """Creates the directory |dst| and moves a previous named cache |name| if it |
| 869 | was in the local named caches cache. |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 870 | |
Marc-Antoine Ruel | 97430be | 2019-01-25 18:26:34 +0000 | [diff] [blame] | 871 | dst must be absolute, unicode and must not exist. |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 872 | |
Marc-Antoine Ruel | 957c7c2 | 2019-01-25 22:21:05 +0000 | [diff] [blame] | 873 | Returns the reused named cache size in bytes, or 0 if none was present. |
| 874 | |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 875 | Raises NamedCacheError if cannot install the cache. |
| 876 | """ |
Marc-Antoine Ruel | 97430be | 2019-01-25 18:26:34 +0000 | [diff] [blame] | 877 | logging.info('NamedCache.install(%r, %r)', dst, name) |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 878 | with self._lock: |
| 879 | try: |
Marc-Antoine Ruel | 957c7c2 | 2019-01-25 22:21:05 +0000 | [diff] [blame] | 880 | if fs.isdir(dst): |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 881 | raise NamedCacheError( |
Marc-Antoine Ruel | 97430be | 2019-01-25 18:26:34 +0000 | [diff] [blame] | 882 | 'installation directory %r already exists' % dst) |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 883 | |
Marc-Antoine Ruel | 957c7c2 | 2019-01-25 22:21:05 +0000 | [diff] [blame] | 884 | # Remove the named symlink if it exists. |
| 885 | link_name = self._get_named_path(name) |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 886 | if fs.exists(link_name): |
Marc-Antoine Ruel | 97430be | 2019-01-25 18:26:34 +0000 | [diff] [blame] | 887 | # Remove the symlink itself, not its destination. |
| 888 | fs.remove(link_name) |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 889 | |
Marc-Antoine Ruel | 33e9f10 | 2018-06-14 19:08:01 +0000 | [diff] [blame] | 890 | if name in self._lru: |
Marc-Antoine Ruel | 44699b3 | 2018-09-24 23:31:50 +0000 | [diff] [blame] | 891 | rel_cache, size = self._lru.get(name) |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 892 | abs_cache = os.path.join(self.cache_dir, rel_cache) |
Marc-Antoine Ruel | 957c7c2 | 2019-01-25 22:21:05 +0000 | [diff] [blame] | 893 | if fs.isdir(abs_cache): |
Marc-Antoine Ruel | 44699b3 | 2018-09-24 23:31:50 +0000 | [diff] [blame] | 894 | logging.info('- reusing %r; size was %d', rel_cache, size) |
Marc-Antoine Ruel | 97430be | 2019-01-25 18:26:34 +0000 | [diff] [blame] | 895 | file_path.ensure_tree(os.path.dirname(dst)) |
| 896 | fs.rename(abs_cache, dst) |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 897 | self._remove(name) |
Marc-Antoine Ruel | 957c7c2 | 2019-01-25 22:21:05 +0000 | [diff] [blame] | 898 | return size |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 899 | |
Marc-Antoine Ruel | 44699b3 | 2018-09-24 23:31:50 +0000 | [diff] [blame] | 900 | logging.warning('- expected directory %r, does not exist', rel_cache) |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 901 | self._remove(name) |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 902 | |
Marc-Antoine Ruel | 44699b3 | 2018-09-24 23:31:50 +0000 | [diff] [blame] | 903 | # The named cache does not exist, create an empty directory. When |
| 904 | # uninstalling, we will move it back to the cache and create an an |
| 905 | # entry. |
| 906 | logging.info('- creating new directory') |
Marc-Antoine Ruel | 97430be | 2019-01-25 18:26:34 +0000 | [diff] [blame] | 907 | file_path.ensure_tree(dst) |
Marc-Antoine Ruel | 957c7c2 | 2019-01-25 22:21:05 +0000 | [diff] [blame] | 908 | return 0 |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 909 | except (IOError, OSError) as ex: |
Marc-Antoine Ruel | 799bc4f | 2019-01-30 22:54:47 +0000 | [diff] [blame] | 910 | # Raise using the original traceback. |
| 911 | exc = NamedCacheError( |
Marc-Antoine Ruel | 957c7c2 | 2019-01-25 22:21:05 +0000 | [diff] [blame] | 912 | 'cannot install cache named %r at %r: %s' % (name, dst, ex)) |
Lei Lei | fe202df | 2019-06-11 17:33:34 +0000 | [diff] [blame] | 913 | six.reraise(exc, None, sys.exc_info()[2]) |
Marc-Antoine Ruel | 33e9f10 | 2018-06-14 19:08:01 +0000 | [diff] [blame] | 914 | finally: |
| 915 | self._save() |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 916 | |
Marc-Antoine Ruel | 97430be | 2019-01-25 18:26:34 +0000 | [diff] [blame] | 917 | def uninstall(self, src, name): |
| 918 | """Moves the cache directory back into the named cache hive for an eventual |
| 919 | reuse. |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 920 | |
Marc-Antoine Ruel | 97430be | 2019-01-25 18:26:34 +0000 | [diff] [blame] | 921 | The opposite of install(). |
| 922 | |
| 923 | src must be absolute and unicode. Its content is moved back into the local |
| 924 | named caches cache. |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 925 | |
Marc-Antoine Ruel | 957c7c2 | 2019-01-25 22:21:05 +0000 | [diff] [blame] | 926 | Returns the named cache size in bytes. |
| 927 | |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 928 | Raises NamedCacheError if cannot uninstall the cache. |
| 929 | """ |
Marc-Antoine Ruel | 97430be | 2019-01-25 18:26:34 +0000 | [diff] [blame] | 930 | logging.info('NamedCache.uninstall(%r, %r)', src, name) |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 931 | with self._lock: |
| 932 | try: |
Marc-Antoine Ruel | 957c7c2 | 2019-01-25 22:21:05 +0000 | [diff] [blame] | 933 | if not fs.isdir(src): |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 934 | logging.warning( |
Marc-Antoine Ruel | 44699b3 | 2018-09-24 23:31:50 +0000 | [diff] [blame] | 935 | 'NamedCache: Directory %r does not exist anymore. Cache lost.', |
Marc-Antoine Ruel | 97430be | 2019-01-25 18:26:34 +0000 | [diff] [blame] | 936 | src) |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 937 | return |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 938 | |
Marc-Antoine Ruel | 33e9f10 | 2018-06-14 19:08:01 +0000 | [diff] [blame] | 939 | if name in self._lru: |
| 940 | # This shouldn't happen but just remove the preexisting one and move |
| 941 | # on. |
Marc-Antoine Ruel | 44699b3 | 2018-09-24 23:31:50 +0000 | [diff] [blame] | 942 | logging.error('- overwriting existing cache!') |
Marc-Antoine Ruel | 33e9f10 | 2018-06-14 19:08:01 +0000 | [diff] [blame] | 943 | self._remove(name) |
Marc-Antoine Ruel | 957c7c2 | 2019-01-25 22:21:05 +0000 | [diff] [blame] | 944 | |
Takuto Ikuta | 9348327 | 2020-06-05 09:06:34 +0000 | [diff] [blame^] | 945 | # Calculate the size of the named cache to keep. |
Marc-Antoine Ruel | 957c7c2 | 2019-01-25 22:21:05 +0000 | [diff] [blame] | 946 | size = _get_recursive_size(src) |
| 947 | logging.info('- Size is %d', size) |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 948 | |
| 949 | # Move the dir and create an entry for the named cache. |
Marc-Antoine Ruel | 957c7c2 | 2019-01-25 22:21:05 +0000 | [diff] [blame] | 950 | rel_cache = self._allocate_dir() |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 951 | abs_cache = os.path.join(self.cache_dir, rel_cache) |
Marc-Antoine Ruel | 44699b3 | 2018-09-24 23:31:50 +0000 | [diff] [blame] | 952 | logging.info('- Moving to %r', rel_cache) |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 953 | file_path.ensure_tree(os.path.dirname(abs_cache)) |
Marc-Antoine Ruel | 97430be | 2019-01-25 18:26:34 +0000 | [diff] [blame] | 954 | fs.rename(src, abs_cache) |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 955 | |
Marc-Antoine Ruel | 33e9f10 | 2018-06-14 19:08:01 +0000 | [diff] [blame] | 956 | self._lru.add(name, (rel_cache, size)) |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 957 | self._added.append(size) |
Marc-Antoine Ruel | 33e9f10 | 2018-06-14 19:08:01 +0000 | [diff] [blame] | 958 | |
| 959 | # Create symlink <cache_dir>/<named>/<name> -> <cache_dir>/<short name> |
| 960 | # for user convenience. |
| 961 | named_path = self._get_named_path(name) |
Marc-Antoine Ruel | 957c7c2 | 2019-01-25 22:21:05 +0000 | [diff] [blame] | 962 | if fs.exists(named_path): |
Marc-Antoine Ruel | 33e9f10 | 2018-06-14 19:08:01 +0000 | [diff] [blame] | 963 | file_path.remove(named_path) |
| 964 | else: |
| 965 | file_path.ensure_tree(os.path.dirname(named_path)) |
| 966 | |
| 967 | try: |
Marc-Antoine Ruel | 957c7c2 | 2019-01-25 22:21:05 +0000 | [diff] [blame] | 968 | fs.symlink(os.path.join(u'..', rel_cache), named_path) |
Marc-Antoine Ruel | 44699b3 | 2018-09-24 23:31:50 +0000 | [diff] [blame] | 969 | logging.info( |
| 970 | 'NamedCache: Created symlink %r to %r', named_path, abs_cache) |
Marc-Antoine Ruel | 33e9f10 | 2018-06-14 19:08:01 +0000 | [diff] [blame] | 971 | except OSError: |
| 972 | # Ignore on Windows. It happens when running as a normal user or when |
| 973 | # UAC is enabled and the user is a filtered administrator account. |
| 974 | if sys.platform != 'win32': |
| 975 | raise |
Marc-Antoine Ruel | 957c7c2 | 2019-01-25 22:21:05 +0000 | [diff] [blame] | 976 | return size |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 977 | except (IOError, OSError) as ex: |
Marc-Antoine Ruel | 799bc4f | 2019-01-30 22:54:47 +0000 | [diff] [blame] | 978 | # Raise using the original traceback. |
| 979 | exc = NamedCacheError( |
Marc-Antoine Ruel | 97430be | 2019-01-25 18:26:34 +0000 | [diff] [blame] | 980 | 'cannot uninstall cache named %r at %r: %s' % (name, src, ex)) |
Lei Lei | fe202df | 2019-06-11 17:33:34 +0000 | [diff] [blame] | 981 | six.reraise(exc, None, sys.exc_info()[2]) |
Marc-Antoine Ruel | 33e9f10 | 2018-06-14 19:08:01 +0000 | [diff] [blame] | 982 | finally: |
Marc-Antoine Ruel | 29db845 | 2018-08-01 17:46:33 +0000 | [diff] [blame] | 983 | # Call save() at every uninstall. The assumptions are: |
| 984 | # - The total the number of named caches is low, so the state.json file |
| 985 | # is small, so the time it takes to write it to disk is short. |
| 986 | # - The number of mapped named caches per task is low, so the number of |
| 987 | # times save() is called on tear-down isn't high enough to be |
| 988 | # significant. |
| 989 | # - uninstall() sometimes throws due to file locking on Windows or |
| 990 | # access rights on Linux. We want to keep as many as possible. |
Marc-Antoine Ruel | 33e9f10 | 2018-06-14 19:08:01 +0000 | [diff] [blame] | 991 | self._save() |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 992 | |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 993 | # Cache interface implementation. |
| 994 | |
| 995 | def __len__(self): |
| 996 | with self._lock: |
| 997 | return len(self._lru) |
| 998 | |
| 999 | def __iter__(self): |
| 1000 | # This is not thread-safe. |
| 1001 | return self._lru.__iter__() |
| 1002 | |
John Budorick | c618697 | 2020-02-26 00:58:14 +0000 | [diff] [blame] | 1003 | def __contains__(self, name): |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 1004 | with self._lock: |
John Budorick | c618697 | 2020-02-26 00:58:14 +0000 | [diff] [blame] | 1005 | return name in self._lru |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 1006 | |
| 1007 | @property |
| 1008 | def total_size(self): |
| 1009 | with self._lock: |
Marc-Antoine Ruel | 04903a3 | 2019-10-09 21:09:25 +0000 | [diff] [blame] | 1010 | return sum(size for _rel_path, size in self._lru.values()) |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 1011 | |
| 1012 | def get_oldest(self): |
| 1013 | with self._lock: |
| 1014 | try: |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 1015 | # (key, (value, ts)) |
| 1016 | return self._lru.get_oldest()[1][1] |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 1017 | except KeyError: |
| 1018 | return None |
| 1019 | |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 1020 | def remove_oldest(self): |
| 1021 | with self._lock: |
| 1022 | # TODO(maruel): Update self._added. |
Marc-Antoine Ruel | 44699b3 | 2018-09-24 23:31:50 +0000 | [diff] [blame] | 1023 | _name, size = self._remove_lru_item() |
| 1024 | return size |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 1025 | |
Marc-Antoine Ruel | 29db845 | 2018-08-01 17:46:33 +0000 | [diff] [blame] | 1026 | def save(self): |
| 1027 | with self._lock: |
| 1028 | return self._save() |
| 1029 | |
John Budorick | c618697 | 2020-02-26 00:58:14 +0000 | [diff] [blame] | 1030 | def touch(self, *names): |
| 1031 | with self._lock: |
| 1032 | for name in names: |
| 1033 | if name in self._lru: |
| 1034 | self._lru.touch(name) |
| 1035 | self._save() |
| 1036 | |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1037 | def trim(self): |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 1038 | evicted = [] |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 1039 | with self._lock: |
Marc-Antoine Ruel | 957c7c2 | 2019-01-25 22:21:05 +0000 | [diff] [blame] | 1040 | if not fs.isdir(self.cache_dir): |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 1041 | return evicted |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1042 | |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 1043 | # Trim according to maximum number of items. |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 1044 | if self._policies.max_items: |
| 1045 | while len(self._lru) > self._policies.max_items: |
Marc-Antoine Ruel | 44699b3 | 2018-09-24 23:31:50 +0000 | [diff] [blame] | 1046 | name, size = self._remove_lru_item() |
| 1047 | evicted.append(size) |
| 1048 | logging.info( |
| 1049 | 'NamedCache.trim(): Removed %r(%d) due to max_items(%d)', |
| 1050 | name, size, self._policies.max_items) |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1051 | |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 1052 | # Trim according to maximum age. |
| 1053 | if self._policies.max_age_secs: |
| 1054 | cutoff = self._lru.time_fn() - self._policies.max_age_secs |
| 1055 | while self._lru: |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 1056 | _name, (_data, ts) = self._lru.get_oldest() |
| 1057 | if ts >= cutoff: |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 1058 | break |
Marc-Antoine Ruel | 44699b3 | 2018-09-24 23:31:50 +0000 | [diff] [blame] | 1059 | name, size = self._remove_lru_item() |
| 1060 | evicted.append(size) |
| 1061 | logging.info( |
| 1062 | 'NamedCache.trim(): Removed %r(%d) due to max_age_secs(%d)', |
| 1063 | name, size, self._policies.max_age_secs) |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1064 | |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 1065 | # Trim according to minimum free space. |
| 1066 | if self._policies.min_free_space: |
Marc-Antoine Ruel | 33e9f10 | 2018-06-14 19:08:01 +0000 | [diff] [blame] | 1067 | while self._lru: |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 1068 | free_space = file_path.get_free_space(self.cache_dir) |
Marc-Antoine Ruel | 33e9f10 | 2018-06-14 19:08:01 +0000 | [diff] [blame] | 1069 | if free_space >= self._policies.min_free_space: |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 1070 | break |
Marc-Antoine Ruel | 44699b3 | 2018-09-24 23:31:50 +0000 | [diff] [blame] | 1071 | name, size = self._remove_lru_item() |
| 1072 | evicted.append(size) |
| 1073 | logging.info( |
| 1074 | 'NamedCache.trim(): Removed %r(%d) due to min_free_space(%d)', |
| 1075 | name, size, self._policies.min_free_space) |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1076 | |
Marc-Antoine Ruel | 33e9f10 | 2018-06-14 19:08:01 +0000 | [diff] [blame] | 1077 | # Trim according to maximum total size. |
| 1078 | if self._policies.max_cache_size: |
| 1079 | while self._lru: |
Marc-Antoine Ruel | 04903a3 | 2019-10-09 21:09:25 +0000 | [diff] [blame] | 1080 | total = sum(size for _rel_cache, size in self._lru.values()) |
Marc-Antoine Ruel | 33e9f10 | 2018-06-14 19:08:01 +0000 | [diff] [blame] | 1081 | if total <= self._policies.max_cache_size: |
| 1082 | break |
Marc-Antoine Ruel | 44699b3 | 2018-09-24 23:31:50 +0000 | [diff] [blame] | 1083 | name, size = self._remove_lru_item() |
| 1084 | evicted.append(size) |
| 1085 | logging.info( |
| 1086 | 'NamedCache.trim(): Removed %r(%d) due to max_cache_size(%d)', |
| 1087 | name, size, self._policies.max_cache_size) |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1088 | |
Marc-Antoine Ruel | e79ddbf | 2018-06-13 18:33:07 +0000 | [diff] [blame] | 1089 | self._save() |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 1090 | return evicted |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 1091 | |
| 1092 | def cleanup(self): |
Marc-Antoine Ruel | 9a518d0 | 2018-06-16 14:41:12 +0000 | [diff] [blame] | 1093 | """Removes unknown directories. |
| 1094 | |
| 1095 | Does not recalculate the cache size since it's surprisingly slow on some |
| 1096 | OSes. |
| 1097 | """ |
| 1098 | success = True |
| 1099 | with self._lock: |
| 1100 | try: |
| 1101 | actual = set(fs.listdir(self.cache_dir)) |
| 1102 | actual.discard(self.NAMED_DIR) |
| 1103 | actual.discard(self.STATE_FILE) |
Marc-Antoine Ruel | 04903a3 | 2019-10-09 21:09:25 +0000 | [diff] [blame] | 1104 | expected = {v[0]: k for k, v in self._lru.items()} |
Marc-Antoine Ruel | 9a518d0 | 2018-06-16 14:41:12 +0000 | [diff] [blame] | 1105 | # First, handle the actual cache content. |
| 1106 | # Remove missing entries. |
| 1107 | for missing in (set(expected) - actual): |
Marc-Antoine Ruel | 44699b3 | 2018-09-24 23:31:50 +0000 | [diff] [blame] | 1108 | name, size = self._lru.pop(expected[missing]) |
| 1109 | logging.warning( |
| 1110 | 'NamedCache.cleanup(): Missing on disk %r(%d)', name, size) |
Marc-Antoine Ruel | 9a518d0 | 2018-06-16 14:41:12 +0000 | [diff] [blame] | 1111 | # Remove unexpected items. |
| 1112 | for unexpected in (actual - set(expected)): |
| 1113 | try: |
| 1114 | p = os.path.join(self.cache_dir, unexpected) |
Marc-Antoine Ruel | 44699b3 | 2018-09-24 23:31:50 +0000 | [diff] [blame] | 1115 | logging.warning( |
| 1116 | 'NamedCache.cleanup(): Unexpected %r', unexpected) |
Marc-Antoine Ruel | 4136222 | 2018-06-28 14:52:34 +0000 | [diff] [blame] | 1117 | if fs.isdir(p) and not fs.islink(p): |
Marc-Antoine Ruel | 9a518d0 | 2018-06-16 14:41:12 +0000 | [diff] [blame] | 1118 | file_path.rmtree(p) |
| 1119 | else: |
| 1120 | fs.remove(p) |
| 1121 | except (IOError, OSError) as e: |
| 1122 | logging.error('Failed to remove %s: %s', unexpected, e) |
| 1123 | success = False |
| 1124 | |
| 1125 | # Second, fix named cache links. |
| 1126 | named = os.path.join(self.cache_dir, self.NAMED_DIR) |
Marc-Antoine Ruel | 957c7c2 | 2019-01-25 22:21:05 +0000 | [diff] [blame] | 1127 | if fs.isdir(named): |
Marc-Antoine Ruel | 9a518d0 | 2018-06-16 14:41:12 +0000 | [diff] [blame] | 1128 | actual = set(fs.listdir(named)) |
| 1129 | expected = set(self._lru) |
| 1130 | # Confirm entries. Do not add missing ones for now. |
| 1131 | for name in expected.intersection(actual): |
| 1132 | p = os.path.join(self.cache_dir, self.NAMED_DIR, name) |
Marc-Antoine Ruel | 957c7c2 | 2019-01-25 22:21:05 +0000 | [diff] [blame] | 1133 | expected_link = os.path.join(u'..', self._lru[name][0]) |
Marc-Antoine Ruel | 9a518d0 | 2018-06-16 14:41:12 +0000 | [diff] [blame] | 1134 | if fs.islink(p): |
| 1135 | link = fs.readlink(p) |
| 1136 | if expected_link == link: |
| 1137 | continue |
| 1138 | logging.warning( |
| 1139 | 'Unexpected symlink for cache %s: %s, expected %s', |
| 1140 | name, link, expected_link) |
| 1141 | else: |
| 1142 | logging.warning('Unexpected non symlink for cache %s', name) |
Marc-Antoine Ruel | 4136222 | 2018-06-28 14:52:34 +0000 | [diff] [blame] | 1143 | if fs.isdir(p) and not fs.islink(p): |
Marc-Antoine Ruel | 9a518d0 | 2018-06-16 14:41:12 +0000 | [diff] [blame] | 1144 | file_path.rmtree(p) |
| 1145 | else: |
| 1146 | fs.remove(p) |
| 1147 | # Remove unexpected items. |
| 1148 | for unexpected in (actual - expected): |
| 1149 | try: |
| 1150 | p = os.path.join(self.cache_dir, self.NAMED_DIR, unexpected) |
| 1151 | if fs.isdir(p): |
| 1152 | file_path.rmtree(p) |
| 1153 | else: |
| 1154 | fs.remove(p) |
| 1155 | except (IOError, OSError) as e: |
| 1156 | logging.error('Failed to remove %s: %s', unexpected, e) |
| 1157 | success = False |
| 1158 | finally: |
| 1159 | self._save() |
| 1160 | return success |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1161 | |
Marc-Antoine Ruel | 5d7606b | 2018-06-15 19:06:12 +0000 | [diff] [blame] | 1162 | # Internal functions. |
| 1163 | |
| 1164 | def _try_upgrade(self): |
| 1165 | """Upgrades from the old format to the new one if necessary. |
| 1166 | |
| 1167 | This code can be removed so all bots are known to have the right new format. |
| 1168 | """ |
| 1169 | if not self._lru: |
| 1170 | return |
| 1171 | _name, (data, _ts) = self._lru.get_oldest() |
| 1172 | if isinstance(data, (list, tuple)): |
| 1173 | return |
| 1174 | # Update to v2. |
| 1175 | def upgrade(_name, rel_cache): |
| 1176 | abs_cache = os.path.join(self.cache_dir, rel_cache) |
| 1177 | return rel_cache, _get_recursive_size(abs_cache) |
| 1178 | self._lru.transform(upgrade) |
| 1179 | self._save() |
| 1180 | |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 1181 | def _remove_lru_item(self): |
| 1182 | """Removes the oldest LRU entry. LRU must not be empty.""" |
| 1183 | name, ((_rel_path, size), _ts) = self._lru.get_oldest() |
| 1184 | logging.info('Removing named cache %r', name) |
| 1185 | self._remove(name) |
Marc-Antoine Ruel | 44699b3 | 2018-09-24 23:31:50 +0000 | [diff] [blame] | 1186 | return name, size |
Marc-Antoine Ruel | 7139d91 | 2018-06-15 20:04:42 +0000 | [diff] [blame] | 1187 | |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1188 | def _allocate_dir(self): |
Marc-Antoine Ruel | 957c7c2 | 2019-01-25 22:21:05 +0000 | [diff] [blame] | 1189 | """Creates and returns relative path of a new cache directory. |
| 1190 | |
| 1191 | In practice, it is a 2-letter string. |
| 1192 | """ |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1193 | # We randomly generate directory names that have two lower/upper case |
| 1194 | # letters or digits. Total number of possibilities is (26*2 + 10)^2 = 3844. |
| 1195 | abc_len = len(self._DIR_ALPHABET) |
| 1196 | tried = set() |
| 1197 | while len(tried) < 1000: |
| 1198 | i = random.randint(0, abc_len * abc_len - 1) |
| 1199 | rel_path = ( |
| 1200 | self._DIR_ALPHABET[i / abc_len] + |
| 1201 | self._DIR_ALPHABET[i % abc_len]) |
| 1202 | if rel_path in tried: |
| 1203 | continue |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 1204 | abs_path = os.path.join(self.cache_dir, rel_path) |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1205 | if not fs.exists(abs_path): |
| 1206 | return rel_path |
| 1207 | tried.add(rel_path) |
| 1208 | raise NamedCacheError( |
| 1209 | 'could not allocate a new cache dir, too many cache dirs') |
| 1210 | |
| 1211 | def _remove(self, name): |
| 1212 | """Removes a cache directory and entry. |
| 1213 | |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1214 | Returns: |
| 1215 | Number of caches deleted. |
| 1216 | """ |
| 1217 | self._lock.assert_locked() |
Marc-Antoine Ruel | 33e9f10 | 2018-06-14 19:08:01 +0000 | [diff] [blame] | 1218 | # First try to remove the alias if it exists. |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1219 | named_dir = self._get_named_path(name) |
| 1220 | if fs.islink(named_dir): |
| 1221 | fs.unlink(named_dir) |
| 1222 | |
Marc-Antoine Ruel | 33e9f10 | 2018-06-14 19:08:01 +0000 | [diff] [blame] | 1223 | # Then remove the actual data. |
| 1224 | if name not in self._lru: |
| 1225 | return |
| 1226 | rel_path, _size = self._lru.get(name) |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 1227 | abs_path = os.path.join(self.cache_dir, rel_path) |
Marc-Antoine Ruel | 957c7c2 | 2019-01-25 22:21:05 +0000 | [diff] [blame] | 1228 | if fs.isdir(abs_path): |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1229 | file_path.rmtree(abs_path) |
| 1230 | self._lru.pop(name) |
| 1231 | |
Marc-Antoine Ruel | 49f9f8d | 2018-05-24 15:57:06 -0400 | [diff] [blame] | 1232 | def _save(self): |
| 1233 | self._lock.assert_locked() |
| 1234 | file_path.ensure_tree(self.cache_dir) |
| 1235 | self._lru.save(self.state_file) |
| 1236 | |
Marc-Antoine Ruel | 8b11dbd | 2018-05-18 14:31:22 -0400 | [diff] [blame] | 1237 | def _get_named_path(self, name): |
Marc-Antoine Ruel | 9a518d0 | 2018-06-16 14:41:12 +0000 | [diff] [blame] | 1238 | return os.path.join(self.cache_dir, self.NAMED_DIR, name) |