| 1 |
# (c) 2014, Michael DeHaan <[email protected]> |
| 2 |
# (c) 2018, Ansible Project |
| 3 |
# |
| 4 |
# This file is part of Ansible |
| 5 |
# |
| 6 |
# Ansible is free software: you can redistribute it and/or modify |
| 7 |
# it under the terms of the GNU General Public License as published by |
| 8 |
# the Free Software Foundation, either version 3 of the License, or |
| 9 |
# (at your option) any later version. |
| 10 |
# |
| 11 |
# Ansible is distributed in the hope that it will be useful, |
| 12 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 |
# GNU General Public License for more details. |
| 15 |
# |
| 16 |
# You should have received a copy of the GNU General Public License |
| 17 |
# along with Ansible. If not, see <http://www.gnu.org/licenses/>. |
| 18 |
from __future__ import annotations |
| 19 |
|
| 20 |
import copy |
| 21 |
import hashlib |
| 22 |
import os |
| 23 |
import tempfile |
| 24 |
import time |
| 25 |
import typing as t |
| 26 |
|
| 27 |
from abc import abstractmethod |
| 28 |
from collections import abc as c |
| 29 |
|
| 30 |
from ansible import constants as C |
| 31 |
from ansible.errors import AnsibleError |
| 32 |
from ansible.module_utils.common.file import S_IRWU_RG_RO |
| 33 |
from ansible.module_utils.common.text.converters import to_bytes |
| 34 |
from ansible.plugins import AnsiblePlugin |
| 35 |
from ansible.plugins.loader import cache_loader |
| 36 |
from ansible.utils.collection_loader import resource_from_fqcr |
| 37 |
from ansible.utils.display import Display |
| 38 |
|
| 39 |
display = Display() |
| 40 |
|
| 41 |
|
| 42 |
class BaseCacheModule(AnsiblePlugin): |
| 43 |
|
| 44 |
_PATH_CHARS = frozenset({'/', '..', '<', '>', '|'}) |
| 45 |
|
| 46 |
# Backwards compat only. Just import the global display instead |
| 47 |
_display = display |
| 48 |
_persistent = True |
| 49 |
"""Plugins that do not persist data between runs can set False to bypass schema-version key munging and JSON serialization wrapper.""" |
| 50 |
|
| 51 |
def __init__(self, *args, **kwargs) -> None: |
| 52 |
super().__init__() |
| 53 |
|
| 54 |
self.set_options(var_options=args, direct=kwargs) |
| 55 |
|
| 56 |
@abstractmethod |
| 57 |
def get(self, key: str) -> dict[str, object]: |
| 58 |
pass |
| 59 |
|
| 60 |
@abstractmethod |
| 61 |
def set(self, key: str, value: dict[str, object]) -> None: |
| 62 |
pass |
| 63 |
|
| 64 |
@abstractmethod |
| 65 |
def keys(self) -> t.Sequence[str]: |
| 66 |
pass |
| 67 |
|
| 68 |
@abstractmethod |
| 69 |
def contains(self, key: object) -> bool: |
| 70 |
pass |
| 71 |
|
| 72 |
@abstractmethod |
| 73 |
def delete(self, key: str) -> None: |
| 74 |
pass |
| 75 |
|
| 76 |
@abstractmethod |
| 77 |
def flush(self) -> None: |
| 78 |
pass |
| 79 |
|
| 80 |
|
| 81 |
class BaseFileCacheModule(BaseCacheModule): |
| 82 |
""" |
| 83 |
A caching module backed by file based storage. |
| 84 |
""" |
| 85 |
def __init__(self, *args, **kwargs): |
| 86 |
|
| 87 |
try: |
| 88 |
super(BaseFileCacheModule, self).__init__(*args, **kwargs) |
| 89 |
self._cache_dir = self._get_cache_connection(self.get_option('_uri')) |
| 90 |
self._timeout = float(self.get_option('_timeout')) |
| 91 |
except KeyError: |
| 92 |
self._cache_dir = self._get_cache_connection(C.CACHE_PLUGIN_CONNECTION) |
| 93 |
self._timeout = float(C.CACHE_PLUGIN_TIMEOUT) |
| 94 |
self.plugin_name = resource_from_fqcr(self.__module__) |
| 95 |
self._cache = {} |
| 96 |
self.validate_cache_connection() |
| 97 |
self._sanitized = {} |
| 98 |
self._files = {} |
| 99 |
|
| 100 |
def _get_cache_connection(self, source): |
| 101 |
if source: |
| 102 |
try: |
| 103 |
return os.path.expanduser(os.path.expandvars(source)) |
| 104 |
except TypeError: |
| 105 |
pass |
| 106 |
|
| 107 |
def _sanitize_key(self, key: str) -> str: |
| 108 |
""" |
| 109 |
Ensures key name is safe to use on the filesystem |
| 110 |
""" |
| 111 |
if key not in self._sanitized: |
| 112 |
for invalid in self._PATH_CHARS: |
| 113 |
if invalid in key: |
| 114 |
self._sanitized[key] = hashlib.sha256(key.encode()).hexdigest()[:max(len(key), 12)] |
| 115 |
break |
| 116 |
else: |
| 117 |
self._sanitized[key] = key |
| 118 |
return self._sanitized[key] |
| 119 |
|
| 120 |
def validate_cache_connection(self): |
| 121 |
if not self._cache_dir: |
| 122 |
raise AnsibleError(f"'{self.plugin_name!r}' cache plugin requires the 'fact_caching_connection' configuration option " |
| 123 |
"to be set (to a writeable directory path)") |
| 124 |
|
| 125 |
if not os.path.exists(self._cache_dir): |
| 126 |
try: |
| 127 |
os.makedirs(self._cache_dir) |
| 128 |
except OSError as ex: |
| 129 |
raise AnsibleError(f"Error in {self.plugin_name!r} cache plugin while trying to create cache dir {self._cache_dir!r}.") from ex |
| 130 |
else: |
| 131 |
for x in (os.R_OK, os.W_OK, os.X_OK): |
| 132 |
if not os.access(self._cache_dir, x): |
| 133 |
raise AnsibleError(f"'{self.plugin_name!r}' cache, configured path ({self._cache_dir}) does not have necessary permissions (rwx)," |
| 134 |
" disabling plugin") |
| 135 |
|
| 136 |
def _get_cache_file_name(self, key: str) -> str: |
| 137 |
if key not in self._files: |
| 138 |
safe = self._sanitize_key(key) # use key or filesystem safe hash of key |
| 139 |
prefix = self.get_option('_prefix') |
| 140 |
if not prefix: |
| 141 |
prefix = '' |
| 142 |
self._files[key] = os.path.join(self._cache_dir, prefix + safe) |
| 143 |
return self._files[key] |
| 144 |
|
| 145 |
def get(self, key): |
| 146 |
""" This checks the in memory cache first as the fact was not expired at 'gather time' |
| 147 |
and it would be problematic if the key did expire after some long running tasks and |
| 148 |
user gets 'undefined' error in the same play """ |
| 149 |
|
| 150 |
if key not in self._cache: |
| 151 |
|
| 152 |
if self.has_expired(key) or key == "": |
| 153 |
raise KeyError |
| 154 |
|
| 155 |
cachefile = self._get_cache_file_name(key) |
| 156 |
try: |
| 157 |
value = self._load(cachefile) |
| 158 |
self._cache[key] = value |
| 159 |
except ValueError as e: |
| 160 |
display.warning("error in '%s' cache plugin while trying to read %s : %s. " |
| 161 |
"Most likely a corrupt file, so erasing and failing." % (self.plugin_name, cachefile, to_bytes(e))) |
| 162 |
self.delete(key) |
| 163 |
raise AnsibleError("The cache file %s was corrupt, or did not otherwise contain valid data. " |
| 164 |
"It has been removed, so you can re-run your command now." % cachefile) |
| 165 |
except FileNotFoundError: |
| 166 |
raise KeyError |
| 167 |
except Exception as ex: |
| 168 |
raise AnsibleError(f"Error while accessing the cache file {cachefile!r}.") from ex |
| 169 |
|
| 170 |
return self._cache.get(key) |
| 171 |
|
| 172 |
def set(self, key, value): |
| 173 |
|
| 174 |
self._cache[key] = value |
| 175 |
|
| 176 |
cachefile = self._get_cache_file_name(key) |
| 177 |
tmpfile_handle, tmpfile_path = tempfile.mkstemp(dir=self._cache_dir) |
| 178 |
try: |
| 179 |
try: |
| 180 |
self._dump(value, tmpfile_path) |
| 181 |
except OSError as ex: |
| 182 |
display.error_as_warning(f"Error in {self.plugin_name!r} cache plugin while trying to write to {tmpfile_path!r}.", exception=ex) |
| 183 |
try: |
| 184 |
os.close(tmpfile_handle) # os.rename fails if handle is still open in WSL |
| 185 |
os.rename(tmpfile_path, cachefile) |
| 186 |
os.chmod(cachefile, mode=S_IRWU_RG_RO) |
| 187 |
except OSError as ex: |
| 188 |
display.error_as_warning(f"Error in {self.plugin_name!r} cache plugin while trying to move {tmpfile_path!r} to {cachefile!r}.", exception=ex) |
| 189 |
finally: |
| 190 |
try: |
| 191 |
os.unlink(tmpfile_path) |
| 192 |
except OSError: |
| 193 |
pass |
| 194 |
|
| 195 |
def has_expired(self, key): |
| 196 |
|
| 197 |
if self._timeout == 0: |
| 198 |
return False |
| 199 |
|
| 200 |
cachefile = self._get_cache_file_name(key) |
| 201 |
try: |
| 202 |
st = os.stat(cachefile) |
| 203 |
except FileNotFoundError: |
| 204 |
return False |
| 205 |
except OSError as ex: |
| 206 |
display.error_as_warning(f"Error in {self.plugin_name!r} cache plugin while trying to stat {cachefile!r}.", exception=ex) |
| 207 |
|
| 208 |
return False |
| 209 |
|
| 210 |
if time.time() - st.st_mtime <= self._timeout: |
| 211 |
return False |
| 212 |
|
| 213 |
if key in self._cache: |
| 214 |
del self._cache[key] |
| 215 |
return True |
| 216 |
|
| 217 |
def keys(self): |
| 218 |
# When using a prefix we must remove it from the key name before |
| 219 |
# checking the expiry and returning it to the caller. Keys that do not |
| 220 |
# share the same prefix cannot be fetched from the cache. |
| 221 |
prefix = self.get_option('_prefix') |
| 222 |
prefix_length = len(prefix) |
| 223 |
keys = [] |
| 224 |
for k in os.listdir(self._cache_dir): |
| 225 |
if k.startswith('.') or not k.startswith(prefix): |
| 226 |
continue |
| 227 |
|
| 228 |
k = k[prefix_length:] |
| 229 |
if not self.has_expired(k): |
| 230 |
keys.append(k) |
| 231 |
|
| 232 |
return keys |
| 233 |
|
| 234 |
def contains(self, key): |
| 235 |
cachefile = self._get_cache_file_name(key) |
| 236 |
|
| 237 |
if key in self._cache: |
| 238 |
return True |
| 239 |
|
| 240 |
if self.has_expired(key): |
| 241 |
return False |
| 242 |
try: |
| 243 |
os.stat(cachefile) |
| 244 |
return True |
| 245 |
except FileNotFoundError: |
| 246 |
return False |
| 247 |
except OSError as ex: |
| 248 |
display.error_as_warning(f"Error in {self.plugin_name!r} cache plugin while trying to stat {cachefile!r}.", exception=ex) |
| 249 |
|
| 250 |
def delete(self, key): |
| 251 |
try: |
| 252 |
del self._cache[key] |
| 253 |
except KeyError: |
| 254 |
pass |
| 255 |
try: |
| 256 |
os.remove(self._get_cache_file_name(key)) |
| 257 |
except OSError: |
| 258 |
pass # TODO: only pass on non existing? |
| 259 |
|
| 260 |
def flush(self): |
| 261 |
self._cache = {} |
| 262 |
for key in self.keys(): |
| 263 |
self.delete(key) |
| 264 |
|
| 265 |
@abstractmethod |
| 266 |
def _load(self, filepath: str) -> object: |
| 267 |
""" |
| 268 |
Read data from a filepath and return it as a value |
| 269 |
|
| 270 |
:arg filepath: The filepath to read from. |
| 271 |
:returns: The value stored in the filepath |
| 272 |
|
| 273 |
This method reads from the file on disk and takes care of any parsing |
| 274 |
and transformation of the data before returning it. The value |
| 275 |
returned should be what Ansible would expect if it were uncached data. |
| 276 |
|
| 277 |
.. note:: Filehandles have advantages but calling code doesn't know |
| 278 |
whether this file is text or binary, should be decoded, or accessed via |
| 279 |
a library function. Therefore the API uses a filepath and opens |
| 280 |
the file inside of the method. |
| 281 |
""" |
| 282 |
pass |
| 283 |
|
| 284 |
@abstractmethod |
| 285 |
def _dump(self, value: object, filepath: str) -> None: |
| 286 |
""" |
| 287 |
Write data to a filepath |
| 288 |
|
| 289 |
:arg value: The value to store |
| 290 |
:arg filepath: The filepath to store it at |
| 291 |
""" |
| 292 |
pass |
| 293 |
|
| 294 |
|
| 295 |
class CachePluginAdjudicator(c.MutableMapping): |
| 296 |
"""Batch update wrapper around a cache plugin.""" |
| 297 |
|
| 298 |
def __init__(self, plugin_name='memory', **kwargs): |
| 299 |
self._cache = {} |
| 300 |
self._retrieved = {} |
| 301 |
self._plugin = cache_loader.get(plugin_name, **kwargs) |
| 302 |
|
| 303 |
def update_cache_if_changed(self): |
| 304 |
if self._retrieved != self._cache: |
| 305 |
self.set_cache() |
| 306 |
|
| 307 |
def set_cache(self): |
| 308 |
for top_level_cache_key in self._cache.keys(): |
| 309 |
self._plugin.set(top_level_cache_key, self._cache[top_level_cache_key]) |
| 310 |
|
| 311 |
self._retrieved = copy.deepcopy(self._cache) |
| 312 |
|
| 313 |
def load_whole_cache(self): |
| 314 |
for key in self._plugin.keys(): |
| 315 |
self._cache[key] = self._plugin.get(key) |
| 316 |
|
| 317 |
def __repr__(self): |
| 318 |
return repr(self._cache) |
| 319 |
|
| 320 |
def __iter__(self): |
| 321 |
return iter(self.keys()) |
| 322 |
|
| 323 |
def __len__(self): |
| 324 |
return len(self.keys()) |
| 325 |
|
| 326 |
def _do_load_key(self, key): |
| 327 |
load = False |
| 328 |
|
| 329 |
if key not in self._cache and key not in self._retrieved and self._plugin._persistent and self._plugin.contains(key): |
| 330 |
load = True |
| 331 |
|
| 332 |
return load |
| 333 |
|
| 334 |
def __getitem__(self, key): |
| 335 |
if self._do_load_key(key): |
| 336 |
try: |
| 337 |
self._cache[key] = self._plugin.get(key) |
| 338 |
except KeyError: |
| 339 |
pass |
| 340 |
else: |
| 341 |
self._retrieved[key] = self._cache[key] |
| 342 |
|
| 343 |
return self._cache[key] |
| 344 |
|
| 345 |
def get(self, key, default=None): |
| 346 |
if self._do_load_key(key): |
| 347 |
try: |
| 348 |
self._cache[key] = self._plugin.get(key) |
| 349 |
except KeyError: |
| 350 |
pass |
| 351 |
else: |
| 352 |
self._retrieved[key] = self._cache[key] |
| 353 |
|
| 354 |
return self._cache.get(key, default) |
| 355 |
|
| 356 |
def items(self): |
| 357 |
return self._cache.items() |
| 358 |
|
| 359 |
def values(self): |
| 360 |
return self._cache.values() |
| 361 |
|
| 362 |
def keys(self): |
| 363 |
return self._cache.keys() |
| 364 |
|
| 365 |
def pop(self, key, *args): |
| 366 |
if args: |
| 367 |
return self._cache.pop(key, args[0]) |
| 368 |
|
| 369 |
return self._cache.pop(key) |
| 370 |
|
| 371 |
def __delitem__(self, key): |
| 372 |
del self._cache[key] |
| 373 |
|
| 374 |
def __setitem__(self, key, value): |
| 375 |
self._cache[key] = value |
| 376 |
|
| 377 |
def clear(self): |
| 378 |
self.flush() |
| 379 |
|
| 380 |
def flush(self): |
| 381 |
self._plugin.flush() |
| 382 |
self._cache = {} |
| 383 |
|
| 384 |
def update(self, value): |
| 385 |
self._cache.update(value) |