nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 1 | # Copyright 2016 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 | """This file implements Named Caches.""" |
| 6 | |
| 7 | import contextlib |
maruel | 681d680 | 2017-01-17 16:56:03 -0800 | [diff] [blame] | 8 | import logging |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 9 | import optparse |
| 10 | import os |
| 11 | import random |
| 12 | import re |
| 13 | import string |
| 14 | |
| 15 | from utils import lru |
| 16 | from utils import file_path |
| 17 | from utils import fs |
| 18 | from utils import threading_utils |
| 19 | |
| 20 | |
| 21 | # Keep synced with task_request.py |
| 22 | CACHE_NAME_RE = re.compile(ur'^[a-z0-9_]{1,4096}$') |
| 23 | MAX_CACHE_SIZE = 50 |
| 24 | |
| 25 | |
| 26 | class Error(Exception): |
| 27 | """Named cache specific error.""" |
| 28 | |
| 29 | |
| 30 | class CacheManager(object): |
| 31 | """Manages cache directories exposed to a task as symlinks. |
| 32 | |
| 33 | A task can specify that caches should be present on a bot. A cache is |
| 34 | tuple (name, path), where |
| 35 | name is a short identifier that describes the contents of the cache, e.g. |
| 36 | "git_v8" could be all git repositories required by v8 builds, or |
| 37 | "build_chromium" could be build artefacts of the Chromium. |
| 38 | path is a directory path relative to the task run dir. It will be mapped |
| 39 | to the cache directory persisted on the bot. |
| 40 | """ |
| 41 | |
| 42 | def __init__(self, root_dir): |
| 43 | """Initializes NamedCaches. |
| 44 | |
| 45 | |root_dir| is a directory for persistent cache storage. |
| 46 | """ |
| 47 | assert file_path.isabs(root_dir), root_dir |
| 48 | self.root_dir = unicode(root_dir) |
| 49 | self._lock = threading_utils.LockWithAssert() |
| 50 | # LRU {cache_name -> cache_location} |
| 51 | # It is saved to |root_dir|/state.json. |
| 52 | self._lru = None |
| 53 | |
| 54 | @contextlib.contextmanager |
| 55 | def open(self, time_fn=None): |
| 56 | """Opens NamedCaches for mutation operations, such as request or trim. |
| 57 | |
| 58 | Only on caller can open the cache manager at a time. If the same thread |
| 59 | calls this function after opening it earlier, the call will deadlock. |
| 60 | |
| 61 | time_fn is a function that returns timestamp (float) and used to take |
| 62 | timestamps when new caches are requested. |
| 63 | |
| 64 | Returns a context manager that must be closed as soon as possible. |
| 65 | """ |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 66 | with self._lock: |
nodir | aaeab8e | 2017-03-28 15:56:21 -0700 | [diff] [blame] | 67 | state_path = os.path.join(self.root_dir, u'state.json') |
| 68 | assert self._lru is None, 'acquired lock, but self._lru is not None' |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 69 | if os.path.isfile(state_path): |
nodir | aaeab8e | 2017-03-28 15:56:21 -0700 | [diff] [blame] | 70 | try: |
| 71 | self._lru = lru.LRUDict.load(state_path) |
| 72 | except ValueError: |
| 73 | logging.exception('failed to load named cache state file') |
| 74 | logging.warning('deleting named caches') |
| 75 | file_path.rmtree(self.root_dir) |
| 76 | self._lru = self._lru or lru.LRUDict() |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 77 | if time_fn: |
| 78 | self._lru.time_fn = time_fn |
| 79 | try: |
| 80 | yield |
| 81 | finally: |
| 82 | file_path.ensure_tree(self.root_dir) |
| 83 | self._lru.save(state_path) |
| 84 | self._lru = None |
| 85 | |
| 86 | def __len__(self): |
| 87 | """Returns number of items in the cache. |
| 88 | |
| 89 | Requires NamedCache to be open. |
| 90 | """ |
| 91 | return len(self._lru) |
| 92 | |
| 93 | def request(self, name): |
| 94 | """Returns an absolute path to the directory of the named cache. |
| 95 | |
| 96 | Creates a cache directory if it does not exist yet. |
| 97 | |
| 98 | Requires NamedCache to be open. |
| 99 | """ |
| 100 | self._lock.assert_locked() |
| 101 | assert isinstance(name, basestring), name |
| 102 | path = self._lru.get(name) |
| 103 | create_named_link = False |
| 104 | if path is None: |
| 105 | path = self._allocate_dir() |
| 106 | create_named_link = True |
maruel | 681d680 | 2017-01-17 16:56:03 -0800 | [diff] [blame] | 107 | logging.info('Created %r for %r', path, name) |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 108 | abs_path = os.path.join(self.root_dir, path) |
| 109 | |
maruel | 681d680 | 2017-01-17 16:56:03 -0800 | [diff] [blame] | 110 | # TODO(maruel): That's weird, it should exist already. |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 111 | file_path.ensure_tree(abs_path) |
| 112 | self._lru.add(name, path) |
| 113 | |
| 114 | if create_named_link: |
| 115 | # Create symlink <root_dir>/<named>/<name> -> <root_dir>/<short name> |
| 116 | # for user convenience. |
| 117 | named_path = self._get_named_path(name) |
| 118 | if os.path.exists(named_path): |
| 119 | file_path.remove(named_path) |
| 120 | else: |
| 121 | file_path.ensure_tree(os.path.dirname(named_path)) |
maruel | 681d680 | 2017-01-17 16:56:03 -0800 | [diff] [blame] | 122 | logging.info('Symlink %r to %r', named_path, abs_path) |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 123 | fs.symlink(abs_path, named_path) |
| 124 | |
| 125 | return abs_path |
| 126 | |
| 127 | def get_oldest(self): |
| 128 | """Returns name of the LRU cache or None. |
| 129 | |
| 130 | Requires NamedCache to be open. |
| 131 | """ |
| 132 | self._lock.assert_locked() |
| 133 | try: |
| 134 | return self._lru.get_oldest()[0] |
| 135 | except KeyError: |
| 136 | return None |
| 137 | |
| 138 | def get_timestamp(self, name): |
| 139 | """Returns timestamp of last use of an item. |
| 140 | |
| 141 | Requires NamedCache to be open. |
| 142 | |
| 143 | Raises KeyError if cache is not found. |
| 144 | """ |
| 145 | self._lock.assert_locked() |
| 146 | assert isinstance(name, basestring), name |
| 147 | return self._lru.get_timestamp(name) |
| 148 | |
nodir | d616068 | 2017-02-02 13:03:35 -0800 | [diff] [blame] | 149 | @contextlib.contextmanager |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 150 | def create_symlinks(self, root, named_caches): |
nodir | d616068 | 2017-02-02 13:03:35 -0800 | [diff] [blame] | 151 | """Creates symlinks in |root| for the specified named_caches. |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 152 | |
| 153 | named_caches must be a list of (name, path) tuples. |
| 154 | |
| 155 | Requires NamedCache to be open. |
| 156 | |
| 157 | Raises Error if cannot create a symlink. |
| 158 | """ |
| 159 | self._lock.assert_locked() |
| 160 | for name, path in named_caches: |
maruel | 681d680 | 2017-01-17 16:56:03 -0800 | [diff] [blame] | 161 | logging.info('Named cache %r -> %r', name, path) |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 162 | try: |
nodir | d616068 | 2017-02-02 13:03:35 -0800 | [diff] [blame] | 163 | _validate_named_cache_path(path) |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 164 | symlink_path = os.path.abspath(os.path.join(root, path)) |
| 165 | file_path.ensure_tree(os.path.dirname(symlink_path)) |
maruel | 681d680 | 2017-01-17 16:56:03 -0800 | [diff] [blame] | 166 | requested = self.request(name) |
| 167 | logging.info('Symlink %r to %r', symlink_path, requested) |
| 168 | fs.symlink(requested, symlink_path) |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 169 | except (OSError, Error) as ex: |
| 170 | raise Error( |
| 171 | 'cannot create a symlink for cache named "%s" at "%s": %s' % ( |
| 172 | name, symlink_path, ex)) |
| 173 | |
nodir | d616068 | 2017-02-02 13:03:35 -0800 | [diff] [blame] | 174 | def delete_symlinks(self, root, named_caches): |
| 175 | """Deletes symlinks from |root| for the specified named_caches. |
| 176 | |
| 177 | named_caches must be a list of (name, path) tuples. |
| 178 | """ |
| 179 | for name, path in named_caches: |
| 180 | logging.info('Unlinking named cache "%s"', name) |
| 181 | try: |
| 182 | _validate_named_cache_path(path) |
| 183 | symlink_path = os.path.abspath(os.path.join(root, path)) |
| 184 | fs.unlink(symlink_path) |
| 185 | except (OSError, Error) as ex: |
| 186 | raise Error( |
| 187 | 'cannot unlink cache named "%s" at "%s": %s' % ( |
| 188 | name, symlink_path, ex)) |
| 189 | |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 190 | def trim(self, min_free_space): |
| 191 | """Purges cache. |
| 192 | |
| 193 | Removes cache directories that were not accessed for a long time |
| 194 | until there is enough free space and the number of caches is sane. |
| 195 | |
| 196 | If min_free_space is None, disk free space is not checked. |
| 197 | |
| 198 | Requires NamedCache to be open. |
maruel | e6fc938 | 2017-05-04 09:03:48 -0700 | [diff] [blame^] | 199 | |
| 200 | Returns: |
| 201 | Number of caches deleted. |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 202 | """ |
| 203 | self._lock.assert_locked() |
| 204 | if not os.path.isdir(self.root_dir): |
maruel | e6fc938 | 2017-05-04 09:03:48 -0700 | [diff] [blame^] | 205 | return 0 |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 206 | |
maruel | e6fc938 | 2017-05-04 09:03:48 -0700 | [diff] [blame^] | 207 | total = 0 |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 208 | free_space = 0 |
maruel | 681d680 | 2017-01-17 16:56:03 -0800 | [diff] [blame] | 209 | if min_free_space: |
| 210 | free_space = file_path.get_free_space(self.root_dir) |
| 211 | while ((min_free_space and free_space < min_free_space) |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 212 | or len(self._lru) > MAX_CACHE_SIZE): |
maruel | 681d680 | 2017-01-17 16:56:03 -0800 | [diff] [blame] | 213 | logging.info( |
| 214 | 'Making space for named cache %s > %s or %s > %s', |
| 215 | free_space, min_free_space, len(self._lru), MAX_CACHE_SIZE) |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 216 | try: |
| 217 | name, (path, _) = self._lru.get_oldest() |
| 218 | except KeyError: |
maruel | e6fc938 | 2017-05-04 09:03:48 -0700 | [diff] [blame^] | 219 | return total |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 220 | named_dir = self._get_named_path(name) |
| 221 | if fs.islink(named_dir): |
| 222 | fs.unlink(named_dir) |
| 223 | path_abs = os.path.join(self.root_dir, path) |
| 224 | if os.path.isdir(path_abs): |
maruel | 681d680 | 2017-01-17 16:56:03 -0800 | [diff] [blame] | 225 | logging.info('Removing named cache %s', path_abs) |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 226 | file_path.rmtree(path_abs) |
maruel | 681d680 | 2017-01-17 16:56:03 -0800 | [diff] [blame] | 227 | if min_free_space: |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 228 | free_space = file_path.get_free_space(self.root_dir) |
| 229 | self._lru.pop(name) |
maruel | e6fc938 | 2017-05-04 09:03:48 -0700 | [diff] [blame^] | 230 | total += 1 |
| 231 | return total |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 232 | |
| 233 | _DIR_ALPHABET = string.ascii_letters + string.digits |
| 234 | |
| 235 | def _allocate_dir(self): |
| 236 | """Creates and returns relative path of a new cache directory.""" |
| 237 | # We randomly generate directory names that have two lower/upper case |
| 238 | # letters or digits. Total number of possibilities is (26*2 + 10)^2 = 3844. |
| 239 | abc_len = len(self._DIR_ALPHABET) |
| 240 | tried = set() |
| 241 | while len(tried) < 1000: |
nodir | 939a5dd | 2016-11-16 10:26:45 -0800 | [diff] [blame] | 242 | i = random.randint(0, abc_len * abc_len - 1) |
nodir | f33b8d6 | 2016-10-26 22:34:58 -0700 | [diff] [blame] | 243 | rel_path = ( |
| 244 | self._DIR_ALPHABET[i / abc_len] + |
| 245 | self._DIR_ALPHABET[i % abc_len]) |
| 246 | if rel_path in tried: |
| 247 | continue |
| 248 | abs_path = os.path.join(self.root_dir, rel_path) |
| 249 | if not fs.exists(abs_path): |
| 250 | return rel_path |
| 251 | tried.add(rel_path) |
| 252 | raise Error('could not allocate a new cache dir, too many cache dirs') |
| 253 | |
| 254 | def _get_named_path(self, name): |
| 255 | return os.path.join(self.root_dir, 'named', name) |
| 256 | |
| 257 | |
| 258 | def add_named_cache_options(parser): |
| 259 | group = optparse.OptionGroup(parser, 'Named caches') |
| 260 | group.add_option( |
| 261 | '--named-cache', |
| 262 | dest='named_caches', |
| 263 | action='append', |
| 264 | nargs=2, |
| 265 | default=[], |
| 266 | help='A named cache to request. Accepts two arguments, name and path. ' |
| 267 | 'name identifies the cache, must match regex [a-z0-9_]{1,4096}. ' |
| 268 | 'path is a path relative to the run dir where the cache directory ' |
| 269 | 'must be symlinked to. ' |
| 270 | 'This option can be specified more than once.') |
| 271 | group.add_option( |
| 272 | '--named-cache-root', |
| 273 | help='Cache root directory. Default=%default') |
| 274 | parser.add_option_group(group) |
| 275 | |
| 276 | |
| 277 | def process_named_cache_options(parser, options): |
| 278 | """Validates named cache options and returns a CacheManager.""" |
| 279 | if options.named_caches and not options.named_cache_root: |
| 280 | parser.error('--named-cache is specified, but --named-cache-root is empty') |
| 281 | for name, path in options.named_caches: |
| 282 | if not CACHE_NAME_RE.match(name): |
| 283 | parser.error( |
| 284 | 'cache name "%s" does not match %s' % (name, CACHE_NAME_RE.pattern)) |
| 285 | if not path: |
| 286 | parser.error('cache path cannot be empty') |
| 287 | if options.named_cache_root: |
| 288 | return CacheManager(os.path.abspath(options.named_cache_root)) |
| 289 | return None |
nodir | d616068 | 2017-02-02 13:03:35 -0800 | [diff] [blame] | 290 | |
| 291 | |
| 292 | def _validate_named_cache_path(path): |
| 293 | if os.path.isabs(path): |
| 294 | raise Error('named cache path must not be absolute') |
| 295 | if '..' in path.split(os.path.sep): |
| 296 | raise Error('named cache path must not contain ".."') |