File: __init__.py

package info (click to toggle)
ansible-core 2.19.0~beta6-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 32,628 kB
  • sloc: python: 180,313; cs: 4,929; sh: 4,601; xml: 34; makefile: 21
file content (365 lines) | stat: -rw-r--r-- 11,930 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# (c) 2014, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2018, Ansible Project
#
# 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/>.
from __future__ import annotations

import copy
import os
import tempfile
import time
import typing as t

from abc import abstractmethod
from collections import abc as c

from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.module_utils.common.file import S_IRWU_RG_RO
from ansible.module_utils.common.text.converters import to_bytes
from ansible.plugins import AnsiblePlugin
from ansible.plugins.loader import cache_loader
from ansible.utils.collection_loader import resource_from_fqcr
from ansible.utils.display import Display

display = Display()


class BaseCacheModule(AnsiblePlugin):

    # Backwards compat only.  Just import the global display instead
    _display = display
    _persistent = True
    """Plugins that do not persist data between runs can set False to bypass schema-version key munging and JSON serialization wrapper."""

    def __init__(self, *args, **kwargs) -> None:
        super().__init__()

        self.set_options(var_options=args, direct=kwargs)

    @abstractmethod
    def get(self, key: str) -> dict[str, object]:
        pass

    @abstractmethod
    def set(self, key: str, value: dict[str, object]) -> None:
        pass

    @abstractmethod
    def keys(self) -> t.Sequence[str]:
        pass

    @abstractmethod
    def contains(self, key: object) -> bool:
        pass

    @abstractmethod
    def delete(self, key: str) -> None:
        pass

    @abstractmethod
    def flush(self) -> None:
        pass


class BaseFileCacheModule(BaseCacheModule):
    """
    A caching module backed by file based storage.
    """
    def __init__(self, *args, **kwargs):

        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)
        self.plugin_name = resource_from_fqcr(self.__module__)
        self._cache = {}
        self.validate_cache_connection()

    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):
        if not self._cache_dir:
            raise AnsibleError("error, '%s' cache plugin requires the 'fact_caching_connection' config option "
                               "to be set (to a writeable directory path)" % self.plugin_name)

        if not os.path.exists(self._cache_dir):
            try:
                os.makedirs(self._cache_dir)
            except OSError as ex:
                raise AnsibleError(f"Error in {self.plugin_name!r} cache plugin while trying to create cache dir {self._cache_dir!r}.") from ex
        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_cache_file_name(self, key: str) -> str:
        prefix = self.get_option('_prefix')
        if prefix:
            cachefile = "%s/%s%s" % (self._cache_dir, prefix, key)
        else:
            cachefile = "%s/%s" % (self._cache_dir, key)
        return cachefile

    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 """

        if key not in self._cache:

            if self.has_expired(key) or key == "":
                raise KeyError

            cachefile = self._get_cache_file_name(key)
            try:
                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)
            except FileNotFoundError:
                raise KeyError
            except Exception as ex:
                raise AnsibleError(f"Error while accessing the cache file {cachefile!r}.") from ex

        return self._cache.get(key)

    def set(self, key, value):

        self._cache[key] = value

        cachefile = self._get_cache_file_name(key)
        tmpfile_handle, tmpfile_path = tempfile.mkstemp(dir=os.path.dirname(cachefile))
        try:
            try:
                self._dump(value, tmpfile_path)
            except OSError as ex:
                display.error_as_warning(f"Error in {self.plugin_name!r} cache plugin while trying to write to {tmpfile_path!r}.", exception=ex)
            try:
                os.rename(tmpfile_path, cachefile)
                os.chmod(cachefile, mode=S_IRWU_RG_RO)
            except OSError as ex:
                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)
        finally:
            try:
                os.unlink(tmpfile_path)
            except OSError:
                pass

    def has_expired(self, key):

        if self._timeout == 0:
            return False

        cachefile = self._get_cache_file_name(key)
        try:
            st = os.stat(cachefile)
        except FileNotFoundError:
            return False
        except OSError as ex:
            display.error_as_warning(f"Error in {self.plugin_name!r} cache plugin while trying to stat {cachefile!r}.", exception=ex)

            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):
        # When using a prefix we must remove it from the key name before
        # checking the expiry and returning it to the caller. Keys that do not
        # share the same prefix cannot be fetched from the cache.
        prefix = self.get_option('_prefix')
        prefix_length = len(prefix)
        keys = []
        for k in os.listdir(self._cache_dir):
            if k.startswith('.') or not k.startswith(prefix):
                continue

            k = k[prefix_length:]
            if not self.has_expired(k):
                keys.append(k)

        return keys

    def contains(self, key):
        cachefile = self._get_cache_file_name(key)

        if key in self._cache:
            return True

        if self.has_expired(key):
            return False
        try:
            os.stat(cachefile)
            return True
        except FileNotFoundError:
            return False
        except OSError as ex:
            display.error_as_warning(f"Error in {self.plugin_name!r} cache plugin while trying to stat {cachefile!r}.", exception=ex)

    def delete(self, key):
        try:
            del self._cache[key]
        except KeyError:
            pass
        try:
            os.remove(self._get_cache_file_name(key))
        except OSError:
            pass  # TODO: only pass on non existing?

    def flush(self):
        self._cache = {}
        for key in self.keys():
            self.delete(key)

    @abstractmethod
    def _load(self, filepath: str) -> object:
        """
        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: object, filepath: str) -> None:
        """
        Write data to a filepath

        :arg value: The value to store
        :arg filepath: The filepath to store it at
        """
        pass


class CachePluginAdjudicator(c.MutableMapping):
    """Batch update wrapper around a cache plugin."""

    def __init__(self, plugin_name='memory', **kwargs):
        self._cache = {}
        self._retrieved = {}
        self._plugin = cache_loader.get(plugin_name, **kwargs)

    def update_cache_if_changed(self):
        if self._retrieved != self._cache:
            self.set_cache()

    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)

    def load_whole_cache(self):
        for key in self._plugin.keys():
            self._cache[key] = self._plugin.get(key)

    def __repr__(self):
        return repr(self._cache)

    def __iter__(self):
        return iter(self.keys())

    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._persistent and self._plugin.contains(key):
            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:
                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 clear(self):
        self.flush()

    def flush(self):
        self._plugin.flush()
        self._cache = {}

    def update(self, value):
        self._cache.update(value)