Debian Codegraph @

ansible_collections/community/general/plugins/cache/memcached.py

raw
1 # Copyright (c) 2014, Brian Coca, Josh Drake, et al
2 # Copyright (c) 2017 Ansible Project
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 author: Unknown (!UNKNOWN)
10 name: memcached
11 short_description: Use memcached DB for cache
12 description:
13 - This cache uses JSON formatted, per host records saved in memcached.
14 requirements:
15 - memcache (python lib)
16 options:
17 _uri:
18 description:
19 - List of connection information for the memcached DBs.
20 default: ['127.0.0.1:11211']
21 type: list
22 elements: string
23 env:
24 - name: ANSIBLE_CACHE_PLUGIN_CONNECTION
25 ini:
26 - key: fact_caching_connection
27 section: defaults
28 _prefix:
29 description: User defined prefix to use when creating the DB entries.
30 type: string
31 default: ansible_facts
32 env:
33 - name: ANSIBLE_CACHE_PLUGIN_PREFIX
34 ini:
35 - key: fact_caching_prefix
36 section: defaults
37 _timeout:
38 default: 86400
39 type: integer
40 # TODO: determine whether it is OK to change to: type: float
41 description: Expiration timeout in seconds for the cache plugin data. Set to 0 to never expire.
42 env:
43 - name: ANSIBLE_CACHE_PLUGIN_TIMEOUT
44 ini:
45 - key: fact_caching_timeout
46 section: defaults
47 """
48
49 import collections
50 import os
51 import time
52 from collections.abc import MutableSet
53 from itertools import chain
54 from multiprocessing import Lock
55
56 from ansible.errors import AnsibleError
57 from ansible.plugins.cache import BaseCacheModule
58 from ansible.utils.display import Display
59
60 try:
61 import memcache
62
63 HAS_MEMCACHE = True
64 except ImportError:
65 HAS_MEMCACHE = False
66
67 display = Display()
68
69
70 class ProxyClientPool:
71 """
72 Memcached connection pooling for thread/fork safety. Inspired by py-redis
73 connection pool.
74
75 Available connections are maintained in a deque and released in a FIFO manner.
76 """
77
78 def __init__(self, *args, **kwargs):
79 self.max_connections = kwargs.pop("max_connections", 1024)
80 self.connection_args = args
81 self.connection_kwargs = kwargs
82 self.reset()
83
84 def reset(self):
85 self.pid = os.getpid()
86 self._num_connections = 0
87 self._available_connections = collections.deque(maxlen=self.max_connections)
88 self._locked_connections = set()
89 self._lock = Lock()
90
91 def _check_safe(self):
92 if self.pid != os.getpid():
93 with self._lock:
94 if self.pid == os.getpid():
95 # bail out - another thread already acquired the lock
96 return
97 self.disconnect_all()
98 self.reset()
99
100 def get_connection(self):
101 self._check_safe()
102 try:
103 connection = self._available_connections.popleft()
104 except IndexError:
105 connection = self.create_connection()
106 self._locked_connections.add(connection)
107 return connection
108
109 def create_connection(self):
110 if self._num_connections >= self.max_connections:
111 raise RuntimeError("Too many memcached connections")
112 self._num_connections += 1
113 return memcache.Client(*self.connection_args, **self.connection_kwargs)
114
115 def release_connection(self, connection):
116 self._check_safe()
117 self._locked_connections.remove(connection)
118 self._available_connections.append(connection)
119
120 def disconnect_all(self):
121 for conn in chain(self._available_connections, self._locked_connections):
122 conn.disconnect_all()
123
124 def __getattr__(self, name):
125 def wrapped(*args, **kwargs):
126 return self._proxy_client(name, *args, **kwargs)
127
128 return wrapped
129
130 def _proxy_client(self, name, *args, **kwargs):
131 conn = self.get_connection()
132
133 try:
134 return getattr(conn, name)(*args, **kwargs)
135 finally:
136 self.release_connection(conn)
137
138
139 class CacheModuleKeys(MutableSet):
140 """
141 A set subclass that keeps track of insertion time and persists
142 the set in memcached.
143 """
144
145 PREFIX = "ansible_cache_keys"
146
147 def __init__(self, cache, *args, **kwargs):
148 self._cache = cache
149 self._keyset = dict(*args, **kwargs)
150
151 def __contains__(self, key):
152 return key in self._keyset
153
154 def __iter__(self):
155 return iter(self._keyset)
156
157 def __len__(self):
158 return len(self._keyset)
159
160 def add(self, value):
161 self._keyset[value] = time.time()
162 self._cache.set(self.PREFIX, self._keyset)
163
164 def discard(self, value):
165 del self._keyset[value]
166 self._cache.set(self.PREFIX, self._keyset)
167
168 def remove_by_timerange(self, s_min, s_max):
169 for k in list(self._keyset.keys()):
170 t = self._keyset[k]
171 if s_min < t < s_max:
172 del self._keyset[k]
173 self._cache.set(self.PREFIX, self._keyset)
174
175
176 class CacheModule(BaseCacheModule):
177 def __init__(self, *args, **kwargs):
178 connection = ["127.0.0.1:11211"]
179
180 super().__init__(*args, **kwargs)
181 if self.get_option("_uri"):
182 connection = self.get_option("_uri")
183 self._timeout = self.get_option("_timeout")
184 self._prefix = self.get_option("_prefix")
185
186 if not HAS_MEMCACHE:
187 raise AnsibleError("python-memcached is required for the memcached fact cache")
188
189 self._cache = {}
190 self._db = ProxyClientPool(connection, debug=0)
191 self._keys = CacheModuleKeys(self._db, self._db.get(CacheModuleKeys.PREFIX) or [])
192
193 def _make_key(self, key):
194 return f"{self._prefix}{key}"
195
196 def _expire_keys(self):
197 if self._timeout > 0:
198 expiry_age = time.time() - self._timeout
199 self._keys.remove_by_timerange(0, expiry_age)
200
201 def get(self, key):
202 if key not in self._cache:
203 value = self._db.get(self._make_key(key))
204 # guard against the key not being removed from the keyset;
205 # this could happen in cases where the timeout value is changed
206 # between invocations
207 if value is None:
208 self.delete(key)
209 raise KeyError
210 self._cache[key] = value
211
212 return self._cache.get(key)
213
214 def set(self, key, value):
215 self._db.set(self._make_key(key), value, time=self._timeout, min_compress_len=1)
216 self._cache[key] = value
217 self._keys.add(key)
218
219 def keys(self):
220 self._expire_keys()
221 return list(iter(self._keys))
222
223 def contains(self, key):
224 self._expire_keys()
225 return key in self._keys
226
227 def delete(self, key):
228 del self._cache[key]
229 self._db.delete(self._make_key(key))
230 self._keys.discard(key)
231
232 def flush(self):
233 for key in self.keys():
234 self.delete(key)
235
236 def copy(self):
237 return self._keys.copy()
238
239 def __getstate__(self):
240 return dict()
241
242 def __setstate__(self, data):
243 self.__init__()