blob: fad59ec4f2b76c9431cba3ea0bb40d36babf8121 [file] [log] [blame]
Marc-Antoine Ruel34f5f282018-05-16 16:04:31 -04001# 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 Ruel8b11dbd2018-05-18 14:31:22 -04007import contextlib
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -04008import errno
9import io
10import logging
11import os
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -040012import random
13import string
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -040014import sys
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +000015import time
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -040016
17from utils import file_path
18from utils import fs
19from utils import lru
20from utils import threading_utils
21from utils import tools
22
23
24# The file size to be used when we don't know the correct file size,
25# generally used for .isolated files.
26UNKNOWN_FILE_SIZE = None
27
28
29def file_write(path, content_generator):
30 """Writes file content as generated by content_generator.
31
32 Creates the intermediary directory as needed.
33
34 Returns the number of bytes written.
35
36 Meant to be mocked out in unit tests.
37 """
38 file_path.ensure_tree(os.path.dirname(path))
39 total = 0
40 with fs.open(path, 'wb') as f:
41 for d in content_generator:
42 total += len(d)
43 f.write(d)
44 return total
45
46
47def is_valid_file(path, size):
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +000048 """Returns if the given files appears valid.
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -040049
50 Currently it just checks the file exists and its size matches the expectation.
51 """
52 if size == UNKNOWN_FILE_SIZE:
53 return fs.isfile(path)
54 try:
55 actual_size = fs.stat(path).st_size
56 except OSError as e:
57 logging.warning(
58 'Can\'t read item %s, assuming it\'s invalid: %s',
59 os.path.basename(path), e)
60 return False
61 if size != actual_size:
62 logging.warning(
63 'Found invalid item %s; %d != %d',
64 os.path.basename(path), actual_size, size)
65 return False
66 return True
67
68
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +000069def trim_caches(caches, path, min_free_space, max_age_secs):
70 """Trims multiple caches.
71
72 The goal here is to coherently trim all caches in a coherent LRU fashion,
73 deleting older items independent of which container they belong to.
74
75 Two policies are enforced first:
76 - max_age_secs
77 - min_free_space
78
79 Once that's done, then we enforce each cache's own policies.
80
81 Returns:
82 Slice containing the size of all items evicted.
83 """
84 min_ts = time.time() - max_age_secs if max_age_secs else 0
85 free_disk = file_path.get_free_space(path) if min_free_space else 0
86 total = []
87 if min_ts or free_disk:
88 while True:
89 oldest = [(c, c.get_oldest()) for c in caches if len(c) > 0]
90 if not oldest:
91 break
92 oldest.sort(key=lambda (_, ts): ts)
93 c, ts = oldest[0]
94 if ts >= min_ts and free_disk >= min_free_space:
95 break
96 total.append(c.remove_oldest())
97 if min_free_space:
98 free_disk = file_path.get_free_space(path)
99 # Evaluate each cache's own policies.
100 for c in caches:
101 total.extend(c.trim())
102 return total
103
104
Marc-Antoine Ruel33e9f102018-06-14 19:08:01 +0000105def _get_recursive_size(path):
106 """Returns the total data size for the specified path.
107
108 This function can be surprisingly slow on OSX, so its output should be cached.
109 """
110 try:
111 total = 0
112 for root, _, files in fs.walk(path):
113 for f in files:
114 total += fs.lstat(os.path.join(root, f)).st_size
115 return total
116 except (IOError, OSError, UnicodeEncodeError) as exc:
117 logging.warning('Exception while getting the size of %s:\n%s', path, exc)
118 return None
119
120
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400121class NamedCacheError(Exception):
122 """Named cache specific error."""
123
124
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400125class NoMoreSpace(Exception):
126 """Not enough space to map the whole directory."""
127 pass
128
Marc-Antoine Ruel34f5f282018-05-16 16:04:31 -0400129
130class CachePolicies(object):
131 def __init__(self, max_cache_size, min_free_space, max_items, max_age_secs):
132 """Common caching policies for the multiple caches (isolated, named, cipd).
133
134 Arguments:
135 - max_cache_size: Trim if the cache gets larger than this value. If 0, the
136 cache is effectively a leak.
137 - min_free_space: Trim if disk free space becomes lower than this value. If
138 0, it will unconditionally fill the disk.
139 - max_items: Maximum number of items to keep in the cache. If 0, do not
140 enforce a limit.
141 - max_age_secs: Maximum age an item is kept in the cache until it is
142 automatically evicted. Having a lot of dead luggage slows
143 everything down.
144 """
145 self.max_cache_size = max_cache_size
146 self.min_free_space = min_free_space
147 self.max_items = max_items
148 self.max_age_secs = max_age_secs
149
150 def __str__(self):
151 return (
152 'CachePolicies(max_cache_size=%s; max_items=%s; min_free_space=%s; '
153 'max_age_secs=%s)') % (
154 self.max_cache_size, self.max_items, self.min_free_space,
155 self.max_age_secs)
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400156
157
158class CacheMiss(Exception):
159 """Raised when an item is not in cache."""
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400160 def __init__(self, digest):
161 self.digest = digest
162 super(CacheMiss, self).__init__(
163 'Item with digest %r is not found in cache' % digest)
164
165
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400166class Cache(object):
167 def __init__(self, cache_dir):
168 if cache_dir is not None:
169 assert isinstance(cache_dir, unicode), cache_dir
170 assert file_path.isabs(cache_dir), cache_dir
171 self.cache_dir = cache_dir
172 self._lock = threading_utils.LockWithAssert()
173 # Profiling values.
174 self._added = []
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400175 self._used = []
176
Marc-Antoine Ruel6c3be5a2018-09-04 17:19:59 +0000177 def __nonzero__(self):
178 """A cache is always True.
179
180 Otherwise it falls back to __len__, which is surprising.
181 """
182 return True
183
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000184 def __len__(self):
185 """Returns the number of entries in the cache."""
186 raise NotImplementedError()
187
188 def __iter__(self):
189 """Iterates over all the entries names."""
190 raise NotImplementedError()
191
192 def __contains__(self, name):
193 """Returns if an entry is in the cache."""
194 raise NotImplementedError()
195
196 @property
197 def total_size(self):
198 """Returns the total size of the cache in bytes."""
199 raise NotImplementedError()
200
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400201 @property
202 def added(self):
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000203 """Returns a list of the size for each entry added."""
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400204 with self._lock:
205 return self._added[:]
206
207 @property
208 def used(self):
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000209 """Returns a list of the size for each entry used."""
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400210 with self._lock:
211 return self._used[:]
212
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000213 def get_oldest(self):
214 """Returns timestamp of oldest cache entry or None.
215
216 Returns:
217 Timestamp of the oldest item.
218
219 Used for manual trimming.
220 """
221 raise NotImplementedError()
222
223 def remove_oldest(self):
224 """Removes the oldest item from the cache.
225
226 Returns:
227 Size of the oldest item.
228
229 Used for manual trimming.
230 """
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400231 raise NotImplementedError()
232
Marc-Antoine Ruel29db8452018-08-01 17:46:33 +0000233 def save(self):
234 """Saves the current cache to disk."""
235 raise NotImplementedError()
236
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400237 def trim(self):
Marc-Antoine Ruel29db8452018-08-01 17:46:33 +0000238 """Enforces cache policies, then calls save().
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400239
240 Returns:
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000241 Slice with the size of evicted items.
242 """
243 raise NotImplementedError()
244
245 def cleanup(self):
Marc-Antoine Ruel29db8452018-08-01 17:46:33 +0000246 """Deletes any corrupted item from the cache, then calls trim(), then
247 save().
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000248
249 It is assumed to take significantly more time than trim().
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400250 """
251 raise NotImplementedError()
252
253
254class ContentAddressedCache(Cache):
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400255 """Content addressed cache that stores objects temporarily.
256
257 It can be accessed concurrently from multiple threads, so it should protect
258 its internal state with some lock.
259 """
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400260
261 def __enter__(self):
262 """Context manager interface."""
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000263 # TODO(maruel): Remove.
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400264 return self
265
266 def __exit__(self, _exc_type, _exec_value, _traceback):
267 """Context manager interface."""
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000268 # TODO(maruel): Remove.
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400269 return False
270
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400271 def touch(self, digest, size):
272 """Ensures item is not corrupted and updates its LRU position.
273
274 Arguments:
275 digest: hash digest of item to check.
276 size: expected size of this item.
277
278 Returns:
279 True if item is in cache and not corrupted.
280 """
281 raise NotImplementedError()
282
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400283 def getfileobj(self, digest):
284 """Returns a readable file like object.
285
286 If file exists on the file system it will have a .name attribute with an
287 absolute path to the file.
288 """
289 raise NotImplementedError()
290
291 def write(self, digest, content):
292 """Reads data from |content| generator and stores it in cache.
293
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000294 It is possible to write to an object that already exists. It may be
295 ignored (sent to /dev/null) but the timestamp is still updated.
296
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400297 Returns digest to simplify chaining.
298 """
299 raise NotImplementedError()
300
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400301
302class MemoryContentAddressedCache(ContentAddressedCache):
303 """ContentAddressedCache implementation that stores everything in memory."""
304
305 def __init__(self, file_mode_mask=0500):
306 """Args:
307 file_mode_mask: bit mask to AND file mode with. Default value will make
308 all mapped files to be read only.
309 """
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400310 super(MemoryContentAddressedCache, self).__init__(None)
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400311 self._file_mode_mask = file_mode_mask
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000312 # Items in a LRU lookup dict(digest: size).
313 self._lru = lru.LRUDict()
314
315 # Cache interface implementation.
316
317 def __len__(self):
318 with self._lock:
319 return len(self._lru)
320
321 def __iter__(self):
322 # This is not thread-safe.
323 return self._lru.__iter__()
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400324
325 def __contains__(self, digest):
326 with self._lock:
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000327 return digest in self._lru
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400328
329 @property
330 def total_size(self):
331 with self._lock:
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000332 return sum(len(i) for i in self._lru.itervalues())
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400333
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000334 def get_oldest(self):
335 with self._lock:
336 try:
337 # (key, (value, ts))
338 return self._lru.get_oldest()[1][1]
339 except KeyError:
340 return None
341
342 def remove_oldest(self):
343 with self._lock:
344 # TODO(maruel): Update self._added.
345 # (key, (value, ts))
346 return len(self._lru.pop_oldest()[1][0])
347
Marc-Antoine Ruel29db8452018-08-01 17:46:33 +0000348 def save(self):
349 pass
350
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000351 def trim(self):
352 """Trimming is not implemented for MemoryContentAddressedCache."""
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000353 return []
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400354
355 def cleanup(self):
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000356 """Cleaning is irrelevant, as there's no stateful serialization."""
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400357 pass
358
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000359 # ContentAddressedCache interface implementation.
360
361 def __contains__(self, digest):
362 with self._lock:
363 return digest in self._lru
364
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400365 def touch(self, digest, size):
366 with self._lock:
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000367 try:
368 self._lru.touch(digest)
369 except KeyError:
370 return False
371 return True
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400372
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400373 def getfileobj(self, digest):
374 with self._lock:
375 try:
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000376 d = self._lru[digest]
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400377 except KeyError:
378 raise CacheMiss(digest)
379 self._used.append(len(d))
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000380 self._lru.touch(digest)
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400381 return io.BytesIO(d)
382
383 def write(self, digest, content):
384 # Assemble whole stream before taking the lock.
385 data = ''.join(content)
386 with self._lock:
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000387 self._lru.add(digest, data)
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400388 self._added.append(len(data))
389 return digest
390
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400391
392class DiskContentAddressedCache(ContentAddressedCache):
393 """Stateful LRU cache in a flat hash table in a directory.
394
395 Saves its state as json file.
396 """
397 STATE_FILE = u'state.json'
398
399 def __init__(self, cache_dir, policies, hash_algo, trim, time_fn=None):
400 """
401 Arguments:
402 cache_dir: directory where to place the cache.
403 policies: CachePolicies instance, cache retention policies.
404 algo: hashing algorithm used.
405 trim: if True to enforce |policies| right away.
406 It can be done later by calling trim() explicitly.
407 """
408 # All protected methods (starting with '_') except _path should be called
409 # with self._lock held.
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400410 super(DiskContentAddressedCache, self).__init__(cache_dir)
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400411 self.policies = policies
412 self.hash_algo = hash_algo
413 self.state_file = os.path.join(cache_dir, self.STATE_FILE)
414 # Items in a LRU lookup dict(digest: size).
415 self._lru = lru.LRUDict()
416 # Current cached free disk space. It is updated by self._trim().
417 file_path.ensure_tree(self.cache_dir)
418 self._free_disk = file_path.get_free_space(self.cache_dir)
419 # The first item in the LRU cache that must not be evicted during this run
420 # since it was referenced. All items more recent that _protected in the LRU
421 # cache are also inherently protected. It could be a set() of all items
422 # referenced but this increases memory usage without a use case.
423 self._protected = None
424 # Cleanup operations done by self._load(), if any.
425 self._operations = []
426 with tools.Profiler('Setup'):
427 with self._lock:
428 self._load(trim, time_fn)
429
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000430 # Cache interface implementation.
431
432 def __len__(self):
433 with self._lock:
434 return len(self._lru)
435
436 def __iter__(self):
437 # This is not thread-safe.
438 return self._lru.__iter__()
439
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400440 def __contains__(self, digest):
441 with self._lock:
442 return digest in self._lru
443
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400444 @property
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400445 def total_size(self):
446 with self._lock:
447 return sum(self._lru.itervalues())
448
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000449 def get_oldest(self):
450 with self._lock:
451 try:
452 # (key, (value, ts))
453 return self._lru.get_oldest()[1][1]
454 except KeyError:
455 return None
456
457 def remove_oldest(self):
458 with self._lock:
459 # TODO(maruel): Update self._added.
460 return self._remove_lru_file(True)
461
Marc-Antoine Ruel29db8452018-08-01 17:46:33 +0000462 def save(self):
463 with self._lock:
464 return self._save()
465
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000466 def trim(self):
467 """Forces retention policies."""
468 with self._lock:
469 return self._trim()
470
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400471 def cleanup(self):
472 """Cleans up the cache directory.
473
474 Ensures there is no unknown files in cache_dir.
475 Ensures the read-only bits are set correctly.
476
477 At that point, the cache was already loaded, trimmed to respect cache
478 policies.
479 """
480 with self._lock:
481 fs.chmod(self.cache_dir, 0700)
482 # Ensure that all files listed in the state still exist and add new ones.
Marc-Antoine Ruel09a76e42018-06-14 19:02:00 +0000483 previous = set(self._lru)
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400484 # It'd be faster if there were a readdir() function.
485 for filename in fs.listdir(self.cache_dir):
486 if filename == self.STATE_FILE:
487 fs.chmod(os.path.join(self.cache_dir, filename), 0600)
488 continue
489 if filename in previous:
490 fs.chmod(os.path.join(self.cache_dir, filename), 0400)
491 previous.remove(filename)
492 continue
493
494 # An untracked file. Delete it.
495 logging.warning('Removing unknown file %s from cache', filename)
496 p = self._path(filename)
497 if fs.isdir(p):
498 try:
499 file_path.rmtree(p)
500 except OSError:
501 pass
502 else:
503 file_path.try_remove(p)
504 continue
505
506 if previous:
507 # Filter out entries that were not found.
508 logging.warning('Removed %d lost files', len(previous))
509 for filename in previous:
510 self._lru.pop(filename)
511 self._save()
512
513 # What remains to be done is to hash every single item to
514 # detect corruption, then save to ensure state.json is up to date.
515 # Sadly, on a 50GiB cache with 100MiB/s I/O, this is still over 8 minutes.
516 # TODO(maruel): Let's revisit once directory metadata is stored in
517 # state.json so only the files that had been mapped since the last cleanup()
518 # call are manually verified.
519 #
520 #with self._lock:
521 # for digest in self._lru:
522 # if not isolated_format.is_valid_hash(
523 # self._path(digest), self.hash_algo):
524 # self.evict(digest)
525 # logging.info('Deleted corrupted item: %s', digest)
526
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000527 # ContentAddressedCache interface implementation.
528
529 def __contains__(self, digest):
530 with self._lock:
531 return digest in self._lru
532
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400533 def touch(self, digest, size):
534 """Verifies an actual file is valid and bumps its LRU position.
535
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000536 Returns False if the file is missing or invalid.
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400537
538 Note that is doesn't compute the hash so it could still be corrupted if the
539 file size didn't change.
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400540 """
541 # Do the check outside the lock.
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000542 looks_valid = is_valid_file(self._path(digest), size)
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400543
544 # Update its LRU position.
545 with self._lock:
546 if digest not in self._lru:
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000547 if looks_valid:
548 # Exists but not in the LRU anymore.
549 self._delete_file(digest, size)
550 return False
551 if not looks_valid:
552 self._lru.pop(digest)
553 # Exists but not in the LRU anymore.
554 self._delete_file(digest, size)
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400555 return False
556 self._lru.touch(digest)
557 self._protected = self._protected or digest
558 return True
559
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400560 def getfileobj(self, digest):
561 try:
562 f = fs.open(self._path(digest), 'rb')
563 with self._lock:
564 self._used.append(self._lru[digest])
565 return f
566 except IOError:
567 raise CacheMiss(digest)
568
569 def write(self, digest, content):
570 assert content is not None
571 with self._lock:
572 self._protected = self._protected or digest
573 path = self._path(digest)
574 # A stale broken file may remain. It is possible for the file to have write
575 # access bit removed which would cause the file_write() call to fail to open
576 # in write mode. Take no chance here.
577 file_path.try_remove(path)
578 try:
579 size = file_write(path, content)
580 except:
581 # There are two possible places were an exception can occur:
582 # 1) Inside |content| generator in case of network or unzipping errors.
583 # 2) Inside file_write itself in case of disk IO errors.
584 # In any case delete an incomplete file and propagate the exception to
585 # caller, it will be logged there.
586 file_path.try_remove(path)
587 raise
588 # Make the file read-only in the cache. This has a few side-effects since
589 # the file node is modified, so every directory entries to this file becomes
590 # read-only. It's fine here because it is a new file.
591 file_path.set_read_only(path, True)
592 with self._lock:
593 self._add(digest, size)
594 return digest
595
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000596 # Internal functions.
597
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400598 def _load(self, trim, time_fn):
599 """Loads state of the cache from json file.
600
601 If cache_dir does not exist on disk, it is created.
602 """
603 self._lock.assert_locked()
604
605 if not fs.isfile(self.state_file):
606 if not fs.isdir(self.cache_dir):
607 fs.makedirs(self.cache_dir)
608 else:
609 # Load state of the cache.
610 try:
611 self._lru = lru.LRUDict.load(self.state_file)
612 except ValueError as err:
613 logging.error('Failed to load cache state: %s' % (err,))
614 # Don't want to keep broken state file.
615 file_path.try_remove(self.state_file)
616 if time_fn:
617 self._lru.time_fn = time_fn
618 if trim:
619 self._trim()
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400620
621 def _save(self):
622 """Saves the LRU ordering."""
623 self._lock.assert_locked()
624 if sys.platform != 'win32':
625 d = os.path.dirname(self.state_file)
626 if fs.isdir(d):
627 # Necessary otherwise the file can't be created.
628 file_path.set_read_only(d, False)
629 if fs.isfile(self.state_file):
630 file_path.set_read_only(self.state_file, False)
631 self._lru.save(self.state_file)
632
633 def _trim(self):
634 """Trims anything we don't know, make sure enough free space exists."""
635 self._lock.assert_locked()
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000636 evicted = []
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400637
638 # Trim old items.
639 if self.policies.max_age_secs:
640 cutoff = self._lru.time_fn() - self.policies.max_age_secs
641 while self._lru:
642 oldest = self._lru.get_oldest()
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000643 # (key, (data, ts)
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400644 if oldest[1][1] >= cutoff:
645 break
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000646 evicted.append(self._remove_lru_file(True))
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400647
648 # Ensure maximum cache size.
649 if self.policies.max_cache_size:
650 total_size = sum(self._lru.itervalues())
651 while total_size > self.policies.max_cache_size:
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000652 e = self._remove_lru_file(True)
653 evicted.append(e)
654 total_size -= e
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400655
656 # Ensure maximum number of items in the cache.
657 if self.policies.max_items and len(self._lru) > self.policies.max_items:
658 for _ in xrange(len(self._lru) - self.policies.max_items):
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000659 evicted.append(self._remove_lru_file(True))
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400660
661 # Ensure enough free space.
662 self._free_disk = file_path.get_free_space(self.cache_dir)
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400663 while (
664 self.policies.min_free_space and
665 self._lru and
666 self._free_disk < self.policies.min_free_space):
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000667 # self._free_disk is updated by this call.
668 evicted.append(self._remove_lru_file(True))
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400669
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000670 if evicted:
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400671 total_usage = sum(self._lru.itervalues())
672 usage_percent = 0.
673 if total_usage:
674 usage_percent = 100. * float(total_usage) / self.policies.max_cache_size
675
676 logging.warning(
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000677 'Trimmed %d file(s) (%.1fkb) due to not enough free disk space:'
678 ' %.1fkb free, %.1fkb cache (%.1f%% of its maximum capacity of '
679 '%.1fkb)',
680 len(evicted), sum(evicted) / 1024.,
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400681 self._free_disk / 1024.,
682 total_usage / 1024.,
683 usage_percent,
684 self.policies.max_cache_size / 1024.)
685 self._save()
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000686 return evicted
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400687
688 def _path(self, digest):
689 """Returns the path to one item."""
690 return os.path.join(self.cache_dir, digest)
691
692 def _remove_lru_file(self, allow_protected):
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000693 """Removes the lastest recently used file and returns its size.
694
695 Updates self._free_disk.
696 """
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400697 self._lock.assert_locked()
698 try:
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000699 digest, (size, _ts) = self._lru.get_oldest()
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400700 if not allow_protected and digest == self._protected:
701 total_size = sum(self._lru.itervalues())+size
702 msg = (
703 'Not enough space to fetch the whole isolated tree.\n'
704 ' %s\n cache=%dbytes, %d items; %sb free_space') % (
705 self.policies, total_size, len(self._lru)+1, self._free_disk)
706 raise NoMoreSpace(msg)
707 except KeyError:
708 # That means an internal error.
709 raise NoMoreSpace('Nothing to remove, can\'t happend')
710 digest, (size, _) = self._lru.pop_oldest()
711 logging.debug('Removing LRU file %s', digest)
712 self._delete_file(digest, size)
713 return size
714
715 def _add(self, digest, size=UNKNOWN_FILE_SIZE):
716 """Adds an item into LRU cache marking it as a newest one."""
717 self._lock.assert_locked()
718 if size == UNKNOWN_FILE_SIZE:
719 size = fs.stat(self._path(digest)).st_size
720 self._added.append(size)
721 self._lru.add(digest, size)
722 self._free_disk -= size
723 # Do a quicker version of self._trim(). It only enforces free disk space,
724 # not cache size limits. It doesn't actually look at real free disk space,
725 # only uses its cache values. self._trim() will be called later to enforce
726 # real trimming but doing this quick version here makes it possible to map
727 # an isolated that is larger than the current amount of free disk space when
728 # the cache size is already large.
729 while (
730 self.policies.min_free_space and
731 self._lru and
732 self._free_disk < self.policies.min_free_space):
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000733 # self._free_disk is updated by this call.
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400734 if self._remove_lru_file(False) == -1:
735 break
736
737 def _delete_file(self, digest, size=UNKNOWN_FILE_SIZE):
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000738 """Deletes cache file from the file system.
739
740 Updates self._free_disk.
741 """
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400742 self._lock.assert_locked()
743 try:
744 if size == UNKNOWN_FILE_SIZE:
745 try:
746 size = fs.stat(self._path(digest)).st_size
747 except OSError:
748 size = 0
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000749 if file_path.try_remove(self._path(digest)):
750 self._free_disk += size
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400751 except OSError as e:
752 if e.errno != errno.ENOENT:
753 logging.error('Error attempting to delete a file %s:\n%s' % (digest, e))
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400754
755
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400756class NamedCache(Cache):
757 """Manages cache directories.
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400758
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400759 A cache entry is a tuple (name, path), where
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400760 name is a short identifier that describes the contents of the cache, e.g.
761 "git_v8" could be all git repositories required by v8 builds, or
762 "build_chromium" could be build artefacts of the Chromium.
763 path is a directory path relative to the task run dir. Cache installation
764 puts the requested cache directory at the path.
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400765 """
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400766 _DIR_ALPHABET = string.ascii_letters + string.digits
767 STATE_FILE = u'state.json'
Marc-Antoine Ruel9a518d02018-06-16 14:41:12 +0000768 NAMED_DIR = u'named'
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400769
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400770 def __init__(self, cache_dir, policies, time_fn=None):
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400771 """Initializes NamedCaches.
772
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400773 Arguments:
774 - cache_dir is a directory for persistent cache storage.
775 - policies is a CachePolicies instance.
776 - time_fn is a function that returns timestamp (float) and used to take
777 timestamps when new caches are requested. Used in unit tests.
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400778 """
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400779 super(NamedCache, self).__init__(cache_dir)
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400780 self._policies = policies
Marc-Antoine Ruel33e9f102018-06-14 19:08:01 +0000781 # LRU {cache_name -> tuple(cache_location, size)}
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400782 self.state_file = os.path.join(cache_dir, self.STATE_FILE)
783 self._lru = lru.LRUDict()
784 if not fs.isdir(self.cache_dir):
785 fs.makedirs(self.cache_dir)
Marc-Antoine Ruel33e9f102018-06-14 19:08:01 +0000786 elif os.path.isfile(self.state_file):
Marc-Antoine Ruel3543e212018-05-23 01:04:34 +0000787 try:
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400788 self._lru = lru.LRUDict.load(self.state_file)
789 except ValueError:
Marc-Antoine Ruel44699b32018-09-24 23:31:50 +0000790 logging.exception(
791 'NamedCache: failed to load named cache state file; obliterating')
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400792 file_path.rmtree(self.cache_dir)
Marc-Antoine Ruel33e9f102018-06-14 19:08:01 +0000793 with self._lock:
794 self._try_upgrade()
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400795 if time_fn:
796 self._lru.time_fn = time_fn
797
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400798 @property
799 def available(self):
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000800 """Returns a set of names of available caches."""
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400801 with self._lock:
Marc-Antoine Ruel09a76e42018-06-14 19:02:00 +0000802 return set(self._lru)
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400803
804 def install(self, path, name):
805 """Moves the directory for the specified named cache to |path|.
806
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000807 path must be absolute, unicode and must not exist.
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400808
809 Raises NamedCacheError if cannot install the cache.
810 """
Marc-Antoine Ruel44699b32018-09-24 23:31:50 +0000811 logging.info('NamedCache.install(%r, %r)', path, name)
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400812 with self._lock:
813 try:
814 if os.path.isdir(path):
815 raise NamedCacheError(
816 'installation directory %r already exists' % path)
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400817
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000818 link_name = os.path.join(self.cache_dir, name)
819 if fs.exists(link_name):
820 fs.rmtree(link_name)
821
Marc-Antoine Ruel33e9f102018-06-14 19:08:01 +0000822 if name in self._lru:
Marc-Antoine Ruel44699b32018-09-24 23:31:50 +0000823 rel_cache, size = self._lru.get(name)
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400824 abs_cache = os.path.join(self.cache_dir, rel_cache)
825 if os.path.isdir(abs_cache):
Marc-Antoine Ruel44699b32018-09-24 23:31:50 +0000826 logging.info('- reusing %r; size was %d', rel_cache, size)
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400827 file_path.ensure_tree(os.path.dirname(path))
828 fs.rename(abs_cache, path)
829 self._remove(name)
830 return
831
Marc-Antoine Ruel44699b32018-09-24 23:31:50 +0000832 logging.warning('- expected directory %r, does not exist', rel_cache)
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400833 self._remove(name)
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400834
Marc-Antoine Ruel44699b32018-09-24 23:31:50 +0000835 # The named cache does not exist, create an empty directory. When
836 # uninstalling, we will move it back to the cache and create an an
837 # entry.
838 logging.info('- creating new directory')
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400839 file_path.ensure_tree(path)
840 except (IOError, OSError) as ex:
841 raise NamedCacheError(
842 'cannot install cache named %r at %r: %s' % (
843 name, path, ex))
Marc-Antoine Ruel33e9f102018-06-14 19:08:01 +0000844 finally:
845 self._save()
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400846
847 def uninstall(self, path, name):
848 """Moves the cache directory back. Opposite to install().
849
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000850 path must be absolute and unicode.
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400851
852 Raises NamedCacheError if cannot uninstall the cache.
853 """
Marc-Antoine Ruel44699b32018-09-24 23:31:50 +0000854 logging.info('NamedCache.uninstall(%r, %r)', path, name)
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400855 with self._lock:
856 try:
857 if not os.path.isdir(path):
858 logging.warning(
Marc-Antoine Ruel44699b32018-09-24 23:31:50 +0000859 'NamedCache: Directory %r does not exist anymore. Cache lost.',
860 path)
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400861 return
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400862
Marc-Antoine Ruel33e9f102018-06-14 19:08:01 +0000863 if name in self._lru:
864 # This shouldn't happen but just remove the preexisting one and move
865 # on.
Marc-Antoine Ruel44699b32018-09-24 23:31:50 +0000866 logging.error('- overwriting existing cache!')
Marc-Antoine Ruel33e9f102018-06-14 19:08:01 +0000867 self._remove(name)
868 rel_cache = self._allocate_dir()
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400869
870 # Move the dir and create an entry for the named cache.
871 abs_cache = os.path.join(self.cache_dir, rel_cache)
Marc-Antoine Ruel44699b32018-09-24 23:31:50 +0000872 logging.info('- Moving to %r', rel_cache)
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400873 file_path.ensure_tree(os.path.dirname(abs_cache))
874 fs.rename(path, abs_cache)
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400875
Marc-Antoine Ruel33e9f102018-06-14 19:08:01 +0000876 # That succeeded, calculate its new size.
877 size = _get_recursive_size(abs_cache)
878 if not size:
879 # Do not save empty named cache.
880 return
Marc-Antoine Ruel44699b32018-09-24 23:31:50 +0000881 logging.info('- Size is %d', size)
Marc-Antoine Ruel33e9f102018-06-14 19:08:01 +0000882 self._lru.add(name, (rel_cache, size))
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000883 self._added.append(size)
Marc-Antoine Ruel33e9f102018-06-14 19:08:01 +0000884
885 # Create symlink <cache_dir>/<named>/<name> -> <cache_dir>/<short name>
886 # for user convenience.
887 named_path = self._get_named_path(name)
888 if os.path.exists(named_path):
889 file_path.remove(named_path)
890 else:
891 file_path.ensure_tree(os.path.dirname(named_path))
892
893 try:
894 fs.symlink(abs_cache, named_path)
Marc-Antoine Ruel44699b32018-09-24 23:31:50 +0000895 logging.info(
896 'NamedCache: Created symlink %r to %r', named_path, abs_cache)
Marc-Antoine Ruel33e9f102018-06-14 19:08:01 +0000897 except OSError:
898 # Ignore on Windows. It happens when running as a normal user or when
899 # UAC is enabled and the user is a filtered administrator account.
900 if sys.platform != 'win32':
901 raise
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400902 except (IOError, OSError) as ex:
903 raise NamedCacheError(
904 'cannot uninstall cache named %r at %r: %s' % (
905 name, path, ex))
Marc-Antoine Ruel33e9f102018-06-14 19:08:01 +0000906 finally:
Marc-Antoine Ruel29db8452018-08-01 17:46:33 +0000907 # Call save() at every uninstall. The assumptions are:
908 # - The total the number of named caches is low, so the state.json file
909 # is small, so the time it takes to write it to disk is short.
910 # - The number of mapped named caches per task is low, so the number of
911 # times save() is called on tear-down isn't high enough to be
912 # significant.
913 # - uninstall() sometimes throws due to file locking on Windows or
914 # access rights on Linux. We want to keep as many as possible.
Marc-Antoine Ruel33e9f102018-06-14 19:08:01 +0000915 self._save()
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400916
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000917 # Cache interface implementation.
918
919 def __len__(self):
920 with self._lock:
921 return len(self._lru)
922
923 def __iter__(self):
924 # This is not thread-safe.
925 return self._lru.__iter__()
926
927 def __contains__(self, digest):
928 with self._lock:
929 return digest in self._lru
930
931 @property
932 def total_size(self):
933 with self._lock:
934 return sum(size for _rel_path, size in self._lru.itervalues())
935
936 def get_oldest(self):
937 with self._lock:
938 try:
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000939 # (key, (value, ts))
940 return self._lru.get_oldest()[1][1]
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +0000941 except KeyError:
942 return None
943
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000944 def remove_oldest(self):
945 with self._lock:
946 # TODO(maruel): Update self._added.
Marc-Antoine Ruel44699b32018-09-24 23:31:50 +0000947 _name, size = self._remove_lru_item()
948 return size
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000949
Marc-Antoine Ruel29db8452018-08-01 17:46:33 +0000950 def save(self):
951 with self._lock:
952 return self._save()
953
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400954 def trim(self):
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000955 evicted = []
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400956 with self._lock:
957 if not os.path.isdir(self.cache_dir):
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000958 return evicted
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400959
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400960 # Trim according to maximum number of items.
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000961 if self._policies.max_items:
962 while len(self._lru) > self._policies.max_items:
Marc-Antoine Ruel44699b32018-09-24 23:31:50 +0000963 name, size = self._remove_lru_item()
964 evicted.append(size)
965 logging.info(
966 'NamedCache.trim(): Removed %r(%d) due to max_items(%d)',
967 name, size, self._policies.max_items)
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400968
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400969 # Trim according to maximum age.
970 if self._policies.max_age_secs:
971 cutoff = self._lru.time_fn() - self._policies.max_age_secs
972 while self._lru:
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +0000973 _name, (_data, ts) = self._lru.get_oldest()
974 if ts >= cutoff:
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400975 break
Marc-Antoine Ruel44699b32018-09-24 23:31:50 +0000976 name, size = self._remove_lru_item()
977 evicted.append(size)
978 logging.info(
979 'NamedCache.trim(): Removed %r(%d) due to max_age_secs(%d)',
980 name, size, self._policies.max_age_secs)
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400981
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400982 # Trim according to minimum free space.
983 if self._policies.min_free_space:
Marc-Antoine Ruel33e9f102018-06-14 19:08:01 +0000984 while self._lru:
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400985 free_space = file_path.get_free_space(self.cache_dir)
Marc-Antoine Ruel33e9f102018-06-14 19:08:01 +0000986 if free_space >= self._policies.min_free_space:
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -0400987 break
Marc-Antoine Ruel44699b32018-09-24 23:31:50 +0000988 name, size = self._remove_lru_item()
989 evicted.append(size)
990 logging.info(
991 'NamedCache.trim(): Removed %r(%d) due to min_free_space(%d)',
992 name, size, self._policies.min_free_space)
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -0400993
Marc-Antoine Ruel33e9f102018-06-14 19:08:01 +0000994 # Trim according to maximum total size.
995 if self._policies.max_cache_size:
996 while self._lru:
997 total = sum(size for _rel_cache, size in self._lru.itervalues())
998 if total <= self._policies.max_cache_size:
999 break
Marc-Antoine Ruel44699b32018-09-24 23:31:50 +00001000 name, size = self._remove_lru_item()
1001 evicted.append(size)
1002 logging.info(
1003 'NamedCache.trim(): Removed %r(%d) due to max_cache_size(%d)',
1004 name, size, self._policies.max_cache_size)
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -04001005
Marc-Antoine Ruele79ddbf2018-06-13 18:33:07 +00001006 self._save()
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +00001007 return evicted
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -04001008
1009 def cleanup(self):
Marc-Antoine Ruel9a518d02018-06-16 14:41:12 +00001010 """Removes unknown directories.
1011
1012 Does not recalculate the cache size since it's surprisingly slow on some
1013 OSes.
1014 """
1015 success = True
1016 with self._lock:
1017 try:
1018 actual = set(fs.listdir(self.cache_dir))
1019 actual.discard(self.NAMED_DIR)
1020 actual.discard(self.STATE_FILE)
1021 expected = {v[0]: k for k, v in self._lru.iteritems()}
1022 # First, handle the actual cache content.
1023 # Remove missing entries.
1024 for missing in (set(expected) - actual):
Marc-Antoine Ruel44699b32018-09-24 23:31:50 +00001025 name, size = self._lru.pop(expected[missing])
1026 logging.warning(
1027 'NamedCache.cleanup(): Missing on disk %r(%d)', name, size)
Marc-Antoine Ruel9a518d02018-06-16 14:41:12 +00001028 # Remove unexpected items.
1029 for unexpected in (actual - set(expected)):
1030 try:
1031 p = os.path.join(self.cache_dir, unexpected)
Marc-Antoine Ruel44699b32018-09-24 23:31:50 +00001032 logging.warning(
1033 'NamedCache.cleanup(): Unexpected %r', unexpected)
Marc-Antoine Ruel41362222018-06-28 14:52:34 +00001034 if fs.isdir(p) and not fs.islink(p):
Marc-Antoine Ruel9a518d02018-06-16 14:41:12 +00001035 file_path.rmtree(p)
1036 else:
1037 fs.remove(p)
1038 except (IOError, OSError) as e:
1039 logging.error('Failed to remove %s: %s', unexpected, e)
1040 success = False
1041
1042 # Second, fix named cache links.
1043 named = os.path.join(self.cache_dir, self.NAMED_DIR)
1044 if os.path.isdir(named):
1045 actual = set(fs.listdir(named))
1046 expected = set(self._lru)
1047 # Confirm entries. Do not add missing ones for now.
1048 for name in expected.intersection(actual):
1049 p = os.path.join(self.cache_dir, self.NAMED_DIR, name)
1050 expected_link = os.path.join(self.cache_dir, self._lru[name][0])
1051 if fs.islink(p):
Marc-Antoine Ruel5d5ec6d2018-06-18 13:31:34 +00001052 if sys.platform == 'win32':
1053 # TODO(maruel): Implement readlink() on Windows in fs.py, then
1054 # remove this condition.
1055 # https://crbug.com/853721
1056 continue
Marc-Antoine Ruel9a518d02018-06-16 14:41:12 +00001057 link = fs.readlink(p)
1058 if expected_link == link:
1059 continue
1060 logging.warning(
1061 'Unexpected symlink for cache %s: %s, expected %s',
1062 name, link, expected_link)
1063 else:
1064 logging.warning('Unexpected non symlink for cache %s', name)
Marc-Antoine Ruel41362222018-06-28 14:52:34 +00001065 if fs.isdir(p) and not fs.islink(p):
Marc-Antoine Ruel9a518d02018-06-16 14:41:12 +00001066 file_path.rmtree(p)
1067 else:
1068 fs.remove(p)
1069 # Remove unexpected items.
1070 for unexpected in (actual - expected):
1071 try:
1072 p = os.path.join(self.cache_dir, self.NAMED_DIR, unexpected)
1073 if fs.isdir(p):
1074 file_path.rmtree(p)
1075 else:
1076 fs.remove(p)
1077 except (IOError, OSError) as e:
1078 logging.error('Failed to remove %s: %s', unexpected, e)
1079 success = False
1080 finally:
1081 self._save()
1082 return success
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -04001083
Marc-Antoine Ruel5d7606b2018-06-15 19:06:12 +00001084 # Internal functions.
1085
1086 def _try_upgrade(self):
1087 """Upgrades from the old format to the new one if necessary.
1088
1089 This code can be removed so all bots are known to have the right new format.
1090 """
1091 if not self._lru:
1092 return
1093 _name, (data, _ts) = self._lru.get_oldest()
1094 if isinstance(data, (list, tuple)):
1095 return
1096 # Update to v2.
1097 def upgrade(_name, rel_cache):
1098 abs_cache = os.path.join(self.cache_dir, rel_cache)
1099 return rel_cache, _get_recursive_size(abs_cache)
1100 self._lru.transform(upgrade)
1101 self._save()
1102
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +00001103 def _remove_lru_item(self):
1104 """Removes the oldest LRU entry. LRU must not be empty."""
1105 name, ((_rel_path, size), _ts) = self._lru.get_oldest()
1106 logging.info('Removing named cache %r', name)
1107 self._remove(name)
Marc-Antoine Ruel44699b32018-09-24 23:31:50 +00001108 return name, size
Marc-Antoine Ruel7139d912018-06-15 20:04:42 +00001109
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -04001110 def _allocate_dir(self):
1111 """Creates and returns relative path of a new cache directory."""
1112 # We randomly generate directory names that have two lower/upper case
1113 # letters or digits. Total number of possibilities is (26*2 + 10)^2 = 3844.
1114 abc_len = len(self._DIR_ALPHABET)
1115 tried = set()
1116 while len(tried) < 1000:
1117 i = random.randint(0, abc_len * abc_len - 1)
1118 rel_path = (
1119 self._DIR_ALPHABET[i / abc_len] +
1120 self._DIR_ALPHABET[i % abc_len])
1121 if rel_path in tried:
1122 continue
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -04001123 abs_path = os.path.join(self.cache_dir, rel_path)
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -04001124 if not fs.exists(abs_path):
1125 return rel_path
1126 tried.add(rel_path)
1127 raise NamedCacheError(
1128 'could not allocate a new cache dir, too many cache dirs')
1129
1130 def _remove(self, name):
1131 """Removes a cache directory and entry.
1132
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -04001133 Returns:
1134 Number of caches deleted.
1135 """
1136 self._lock.assert_locked()
Marc-Antoine Ruel33e9f102018-06-14 19:08:01 +00001137 # First try to remove the alias if it exists.
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -04001138 named_dir = self._get_named_path(name)
1139 if fs.islink(named_dir):
1140 fs.unlink(named_dir)
1141
Marc-Antoine Ruel33e9f102018-06-14 19:08:01 +00001142 # Then remove the actual data.
1143 if name not in self._lru:
1144 return
1145 rel_path, _size = self._lru.get(name)
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -04001146 abs_path = os.path.join(self.cache_dir, rel_path)
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -04001147 if os.path.isdir(abs_path):
1148 file_path.rmtree(abs_path)
1149 self._lru.pop(name)
1150
Marc-Antoine Ruel49f9f8d2018-05-24 15:57:06 -04001151 def _save(self):
1152 self._lock.assert_locked()
1153 file_path.ensure_tree(self.cache_dir)
1154 self._lru.save(self.state_file)
1155
Marc-Antoine Ruel8b11dbd2018-05-18 14:31:22 -04001156 def _get_named_path(self, name):
Marc-Antoine Ruel9a518d02018-06-16 14:41:12 +00001157 return os.path.join(self.cache_dir, self.NAMED_DIR, name)