2014-11-01 19:34:14 +00:00
|
|
|
# (c) 2014, Michael DeHaan <michael.dehaan@gmail.com>
|
2018-12-04 19:17:31 +00:00
|
|
|
# (c) 2018, Ansible Project
|
2014-11-01 19:34:14 +00:00
|
|
|
#
|
|
|
|
# This file is part of Ansible
|
|
|
|
#
|
|
|
|
# Ansible is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# Ansible is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
2015-04-13 20:28:01 +00:00
|
|
|
from __future__ import (absolute_import, division, print_function)
|
|
|
|
__metaclass__ = type
|
2014-11-01 19:34:14 +00:00
|
|
|
|
2019-03-06 18:12:35 +00:00
|
|
|
import copy
|
2017-03-23 05:26:10 +00:00
|
|
|
import os
|
|
|
|
import time
|
|
|
|
import errno
|
|
|
|
from abc import ABCMeta, abstractmethod
|
2014-11-01 19:34:14 +00:00
|
|
|
|
|
|
|
from ansible import constants as C
|
2016-12-13 19:34:58 +00:00
|
|
|
from ansible.errors import AnsibleError
|
2017-03-23 20:35:05 +00:00
|
|
|
from ansible.module_utils.six import with_metaclass
|
2019-03-06 18:12:35 +00:00
|
|
|
from ansible.module_utils._text import to_bytes, to_text
|
2018-10-05 08:22:25 +00:00
|
|
|
from ansible.module_utils.common._collections_compat import MutableMapping
|
2019-03-06 18:12:35 +00:00
|
|
|
from ansible.plugins import AnsiblePlugin
|
2017-08-15 20:38:59 +00:00
|
|
|
from ansible.plugins.loader import cache_loader
|
2018-11-20 23:06:51 +00:00
|
|
|
from ansible.utils.display import Display
|
2018-12-04 19:17:31 +00:00
|
|
|
from ansible.vars.fact_cache import FactCache as RealFactCache
|
2014-11-01 19:34:14 +00:00
|
|
|
|
2018-11-20 23:06:51 +00:00
|
|
|
display = Display()
|
2015-07-23 14:24:50 +00:00
|
|
|
|
2015-11-11 16:38:49 +00:00
|
|
|
|
2018-12-04 19:17:31 +00:00
|
|
|
class FactCache(RealFactCache):
|
|
|
|
"""
|
|
|
|
This is for backwards compatibility. Will be removed after deprecation. It was removed as it
|
|
|
|
wasn't actually part of the cache plugin API. It's actually the code to make use of cache
|
|
|
|
plugins, not the cache plugin itself. Subclassing it wouldn't yield a usable Cache Plugin and
|
|
|
|
there was no facility to use it as anything else.
|
|
|
|
"""
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
display.deprecated('ansible.plugins.cache.FactCache has been moved to'
|
|
|
|
' ansible.vars.fact_cache.FactCache. If you are looking for the class'
|
|
|
|
' to subclass for a cache plugin, you want'
|
|
|
|
' ansible.plugins.cache.BaseCacheModule or one of its subclasses.',
|
|
|
|
version='2.12')
|
|
|
|
super(FactCache, self).__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
|
2019-03-06 18:12:35 +00:00
|
|
|
class BaseCacheModule(AnsiblePlugin):
|
2017-03-23 05:26:10 +00:00
|
|
|
|
|
|
|
# Backwards compat only. Just import the global display instead
|
|
|
|
_display = display
|
|
|
|
|
2019-03-06 18:12:35 +00:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self._load_name = self.__module__.split('.')[-1]
|
|
|
|
super(BaseCacheModule, self).__init__()
|
|
|
|
self.set_options(var_options=args, direct=kwargs)
|
|
|
|
|
2017-03-23 05:26:10 +00:00
|
|
|
@abstractmethod
|
|
|
|
def get(self, key):
|
|
|
|
pass
|
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
def set(self, key, value):
|
|
|
|
pass
|
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
def keys(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
def contains(self, key):
|
|
|
|
pass
|
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
def delete(self, key):
|
|
|
|
pass
|
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
def flush(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
def copy(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class BaseFileCacheModule(BaseCacheModule):
|
|
|
|
"""
|
|
|
|
A caching module backed by file based storage.
|
|
|
|
"""
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
|
2019-03-06 18:12:35 +00:00
|
|
|
try:
|
|
|
|
super(BaseFileCacheModule, self).__init__(*args, **kwargs)
|
|
|
|
self._cache_dir = self._get_cache_connection(self.get_option('_uri'))
|
|
|
|
self._timeout = float(self.get_option('_timeout'))
|
|
|
|
except KeyError:
|
|
|
|
self._cache_dir = self._get_cache_connection(C.CACHE_PLUGIN_CONNECTION)
|
|
|
|
self._timeout = float(C.CACHE_PLUGIN_TIMEOUT)
|
2017-03-23 05:26:10 +00:00
|
|
|
self.plugin_name = self.__module__.split('.')[-1]
|
|
|
|
self._cache = {}
|
2018-01-23 00:33:14 +00:00
|
|
|
self.validate_cache_connection()
|
2017-03-23 05:26:10 +00:00
|
|
|
|
2018-01-23 00:33:14 +00:00
|
|
|
def _get_cache_connection(self, source):
|
|
|
|
if source:
|
|
|
|
try:
|
|
|
|
return os.path.expanduser(os.path.expandvars(source))
|
|
|
|
except TypeError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
def validate_cache_connection(self):
|
2017-03-23 05:26:10 +00:00
|
|
|
if not self._cache_dir:
|
2017-06-02 11:14:11 +00:00
|
|
|
raise AnsibleError("error, '%s' cache plugin requires the 'fact_caching_connection' config option "
|
|
|
|
"to be set (to a writeable directory path)" % self.plugin_name)
|
2017-03-23 05:26:10 +00:00
|
|
|
|
|
|
|
if not os.path.exists(self._cache_dir):
|
|
|
|
try:
|
|
|
|
os.makedirs(self._cache_dir)
|
2017-06-02 11:14:11 +00:00
|
|
|
except (OSError, IOError) as e:
|
2017-03-23 05:26:10 +00:00
|
|
|
raise AnsibleError("error in '%s' cache plugin while trying to create cache dir %s : %s" % (self.plugin_name, self._cache_dir, to_bytes(e)))
|
|
|
|
else:
|
|
|
|
for x in (os.R_OK, os.W_OK, os.X_OK):
|
|
|
|
if not os.access(self._cache_dir, x):
|
|
|
|
raise AnsibleError("error in '%s' cache, configured path (%s) does not have necessary permissions (rwx), disabling plugin" % (
|
|
|
|
self.plugin_name, self._cache_dir))
|
|
|
|
|
|
|
|
def get(self, key):
|
|
|
|
""" This checks the in memory cache first as the fact was not expired at 'gather time'
|
|
|
|
and it would be problematic if the key did expire after some long running tasks and
|
|
|
|
user gets 'undefined' error in the same play """
|
|
|
|
|
2017-09-07 16:17:16 +00:00
|
|
|
if key not in self._cache:
|
2017-03-23 05:26:10 +00:00
|
|
|
|
2017-09-07 16:17:16 +00:00
|
|
|
if self.has_expired(key) or key == "":
|
|
|
|
raise KeyError
|
2017-03-23 05:26:10 +00:00
|
|
|
|
2017-09-07 16:17:16 +00:00
|
|
|
cachefile = "%s/%s" % (self._cache_dir, key)
|
2017-03-23 05:26:10 +00:00
|
|
|
try:
|
2017-09-07 17:20:44 +00:00
|
|
|
value = self._load(cachefile)
|
|
|
|
self._cache[key] = value
|
|
|
|
except ValueError as e:
|
|
|
|
display.warning("error in '%s' cache plugin while trying to read %s : %s. "
|
|
|
|
"Most likely a corrupt file, so erasing and failing." % (self.plugin_name, cachefile, to_bytes(e)))
|
|
|
|
self.delete(key)
|
|
|
|
raise AnsibleError("The cache file %s was corrupt, or did not otherwise contain valid data. "
|
|
|
|
"It has been removed, so you can re-run your command now." % cachefile)
|
2017-09-07 16:17:16 +00:00
|
|
|
except (OSError, IOError) as e:
|
|
|
|
display.warning("error in '%s' cache plugin while trying to read %s : %s" % (self.plugin_name, cachefile, to_bytes(e)))
|
|
|
|
raise KeyError
|
|
|
|
except Exception as e:
|
|
|
|
raise AnsibleError("Error while decoding the cache file %s: %s" % (cachefile, to_bytes(e)))
|
|
|
|
|
|
|
|
return self._cache.get(key)
|
2017-03-23 05:26:10 +00:00
|
|
|
|
|
|
|
def set(self, key, value):
|
|
|
|
|
|
|
|
self._cache[key] = value
|
|
|
|
|
|
|
|
cachefile = "%s/%s" % (self._cache_dir, key)
|
|
|
|
try:
|
|
|
|
self._dump(value, cachefile)
|
2017-06-02 11:14:11 +00:00
|
|
|
except (OSError, IOError) as e:
|
2017-03-23 05:26:10 +00:00
|
|
|
display.warning("error in '%s' cache plugin while trying to write to %s : %s" % (self.plugin_name, cachefile, to_bytes(e)))
|
|
|
|
|
|
|
|
def has_expired(self, key):
|
|
|
|
|
|
|
|
if self._timeout == 0:
|
2018-05-25 16:13:51 +00:00
|
|
|
return False
|
2017-03-23 05:26:10 +00:00
|
|
|
|
|
|
|
cachefile = "%s/%s" % (self._cache_dir, key)
|
|
|
|
try:
|
|
|
|
st = os.stat(cachefile)
|
2017-06-02 11:14:11 +00:00
|
|
|
except (OSError, IOError) as e:
|
2017-03-23 05:26:10 +00:00
|
|
|
if e.errno == errno.ENOENT:
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
display.warning("error in '%s' cache plugin while trying to stat %s : %s" % (self.plugin_name, cachefile, to_bytes(e)))
|
|
|
|
return False
|
|
|
|
|
|
|
|
if time.time() - st.st_mtime <= self._timeout:
|
|
|
|
return False
|
|
|
|
|
|
|
|
if key in self._cache:
|
|
|
|
del self._cache[key]
|
|
|
|
return True
|
|
|
|
|
|
|
|
def keys(self):
|
|
|
|
keys = []
|
|
|
|
for k in os.listdir(self._cache_dir):
|
|
|
|
if not (k.startswith('.') or self.has_expired(k)):
|
|
|
|
keys.append(k)
|
|
|
|
return keys
|
|
|
|
|
|
|
|
def contains(self, key):
|
|
|
|
cachefile = "%s/%s" % (self._cache_dir, key)
|
|
|
|
|
|
|
|
if key in self._cache:
|
|
|
|
return True
|
|
|
|
|
|
|
|
if self.has_expired(key):
|
|
|
|
return False
|
|
|
|
try:
|
|
|
|
os.stat(cachefile)
|
|
|
|
return True
|
2017-06-02 11:14:11 +00:00
|
|
|
except (OSError, IOError) as e:
|
2017-03-23 05:26:10 +00:00
|
|
|
if e.errno == errno.ENOENT:
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
display.warning("error in '%s' cache plugin while trying to stat %s : %s" % (self.plugin_name, cachefile, to_bytes(e)))
|
|
|
|
|
|
|
|
def delete(self, key):
|
|
|
|
try:
|
|
|
|
del self._cache[key]
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
try:
|
|
|
|
os.remove("%s/%s" % (self._cache_dir, key))
|
|
|
|
except (OSError, IOError):
|
2017-06-02 11:14:11 +00:00
|
|
|
pass # TODO: only pass on non existing?
|
2017-03-23 05:26:10 +00:00
|
|
|
|
|
|
|
def flush(self):
|
|
|
|
self._cache = {}
|
|
|
|
for key in self.keys():
|
|
|
|
self.delete(key)
|
|
|
|
|
|
|
|
def copy(self):
|
|
|
|
ret = dict()
|
|
|
|
for key in self.keys():
|
|
|
|
ret[key] = self.get(key)
|
|
|
|
return ret
|
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
def _load(self, filepath):
|
|
|
|
"""
|
|
|
|
Read data from a filepath and return it as a value
|
|
|
|
|
|
|
|
:arg filepath: The filepath to read from.
|
|
|
|
:returns: The value stored in the filepath
|
|
|
|
|
|
|
|
This method reads from the file on disk and takes care of any parsing
|
|
|
|
and transformation of the data before returning it. The value
|
|
|
|
returned should be what Ansible would expect if it were uncached data.
|
|
|
|
|
|
|
|
.. note:: Filehandles have advantages but calling code doesn't know
|
|
|
|
whether this file is text or binary, should be decoded, or accessed via
|
|
|
|
a library function. Therefore the API uses a filepath and opens
|
|
|
|
the file inside of the method.
|
|
|
|
"""
|
|
|
|
pass
|
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
def _dump(self, value, filepath):
|
|
|
|
"""
|
|
|
|
Write data to a filepath
|
|
|
|
|
|
|
|
:arg value: The value to store
|
|
|
|
:arg filepath: The filepath to store it at
|
|
|
|
"""
|
|
|
|
pass
|
|
|
|
|
2017-06-02 11:14:11 +00:00
|
|
|
|
2019-03-06 18:12:35 +00:00
|
|
|
class CachePluginAdjudicator(MutableMapping):
|
2018-01-23 00:33:14 +00:00
|
|
|
"""
|
2019-03-06 18:12:35 +00:00
|
|
|
Intermediary between a cache dictionary and a CacheModule
|
2018-01-23 00:33:14 +00:00
|
|
|
"""
|
2019-03-06 18:12:35 +00:00
|
|
|
def __init__(self, plugin_name='memory', **kwargs):
|
2018-01-23 00:33:14 +00:00
|
|
|
self._cache = {}
|
2019-03-06 18:12:35 +00:00
|
|
|
self._retrieved = {}
|
2018-01-23 00:33:14 +00:00
|
|
|
|
2019-03-06 18:12:35 +00:00
|
|
|
self._plugin = cache_loader.get(plugin_name, **kwargs)
|
|
|
|
if not self._plugin:
|
|
|
|
raise AnsibleError('Unable to load the cache plugin (%s).' % plugin_name)
|
2018-01-23 00:33:14 +00:00
|
|
|
|
2019-03-06 18:12:35 +00:00
|
|
|
self._plugin_name = plugin_name
|
2018-01-23 00:33:14 +00:00
|
|
|
|
2019-03-06 18:12:35 +00:00
|
|
|
def update_cache_if_changed(self):
|
|
|
|
if self._retrieved != self._cache:
|
|
|
|
self.set_cache()
|
2018-01-23 00:33:14 +00:00
|
|
|
|
2019-03-06 18:12:35 +00:00
|
|
|
def set_cache(self):
|
|
|
|
for top_level_cache_key in self._cache.keys():
|
|
|
|
self._plugin.set(top_level_cache_key, self._cache[top_level_cache_key])
|
|
|
|
self._retrieved = copy.deepcopy(self._cache)
|
2018-01-23 00:33:14 +00:00
|
|
|
|
2019-03-06 18:12:35 +00:00
|
|
|
def load_whole_cache(self):
|
|
|
|
for key in self._plugin.keys():
|
|
|
|
self._cache[key] = self._plugin.get(key)
|
2018-01-23 00:33:14 +00:00
|
|
|
|
2019-03-06 18:12:35 +00:00
|
|
|
def __repr__(self):
|
|
|
|
return to_text(self._cache)
|
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
return iter(self.keys())
|
2018-01-23 00:33:14 +00:00
|
|
|
|
2019-03-06 18:12:35 +00:00
|
|
|
def __len__(self):
|
|
|
|
return len(self.keys())
|
|
|
|
|
|
|
|
def _do_load_key(self, key):
|
|
|
|
load = False
|
|
|
|
if key not in self._cache and key not in self._retrieved and self._plugin_name != 'memory':
|
|
|
|
if isinstance(self._plugin, BaseFileCacheModule):
|
|
|
|
load = True
|
|
|
|
elif not isinstance(self._plugin, BaseFileCacheModule) and self._plugin.contains(key):
|
|
|
|
# Database-backed caches don't raise KeyError for expired keys, so only load if the key is valid by checking contains()
|
|
|
|
load = True
|
|
|
|
return load
|
|
|
|
|
|
|
|
def __getitem__(self, key):
|
|
|
|
if self._do_load_key(key):
|
|
|
|
try:
|
|
|
|
self._cache[key] = self._plugin.get(key)
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
self._retrieved[key] = self._cache[key]
|
|
|
|
return self._cache[key]
|
|
|
|
|
|
|
|
def get(self, key, default=None):
|
|
|
|
if self._do_load_key(key):
|
|
|
|
try:
|
|
|
|
self._cache[key] = self._plugin.get(key)
|
|
|
|
except KeyError as e:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
self._retrieved[key] = self._cache[key]
|
|
|
|
return self._cache.get(key, default)
|
|
|
|
|
|
|
|
def items(self):
|
|
|
|
return self._cache.items()
|
|
|
|
|
|
|
|
def values(self):
|
|
|
|
return self._cache.values()
|
|
|
|
|
|
|
|
def keys(self):
|
|
|
|
return self._cache.keys()
|
|
|
|
|
|
|
|
def pop(self, key, *args):
|
|
|
|
if args:
|
|
|
|
return self._cache.pop(key, args[0])
|
|
|
|
return self._cache.pop(key)
|
|
|
|
|
|
|
|
def __delitem__(self, key):
|
|
|
|
del self._cache[key]
|
|
|
|
|
|
|
|
def __setitem__(self, key, value):
|
|
|
|
self._cache[key] = value
|
|
|
|
|
|
|
|
def flush(self):
|
|
|
|
for key in self._cache.keys():
|
|
|
|
self._plugin.delete(key)
|
|
|
|
self._cache = {}
|
2018-01-23 00:33:14 +00:00
|
|
|
|
2019-03-06 18:12:35 +00:00
|
|
|
def update(self, value):
|
|
|
|
self._cache.update(value)
|