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