Debian Codegraph @

ansible_collections/community/general/plugins/cache/redis.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 from __future__ import annotations
6
7 DOCUMENTATION = r"""
8 author: Unknown (!UNKNOWN)
9 name: redis
10 short_description: Use Redis DB for cache
11 description:
12 - This cache uses JSON formatted, per host records saved in Redis.
13 requirements:
14 - redis>=2.4.5 (python lib)
15 options:
16 _uri:
17 description:
18 - A colon separated string of connection information for Redis.
19 - The format is V(host:port:db:password), for example V(localhost:6379:0:changeme).
20 - To use encryption in transit, prefix the connection with V(tls://), as in V(tls://localhost:6379:0:changeme).
21 - To use redis sentinel, use separator V(;), for example V(localhost:26379;localhost:26379;0:changeme). Requires redis>=2.9.0.
22 type: string
23 required: true
24 env:
25 - name: ANSIBLE_CACHE_PLUGIN_CONNECTION
26 ini:
27 - key: fact_caching_connection
28 section: defaults
29 _prefix:
30 description: User defined prefix to use when creating the DB entries.
31 type: string
32 default: ansible_facts
33 env:
34 - name: ANSIBLE_CACHE_PLUGIN_PREFIX
35 ini:
36 - key: fact_caching_prefix
37 section: defaults
38 _keyset_name:
39 description: User defined name for cache keyset name.
40 type: string
41 default: ansible_cache_keys
42 env:
43 - name: ANSIBLE_CACHE_REDIS_KEYSET_NAME
44 ini:
45 - key: fact_caching_redis_keyset_name
46 section: defaults
47 version_added: 1.3.0
48 _sentinel_service_name:
49 description: The redis sentinel service name (or referenced as cluster name).
50 type: string
51 env:
52 - name: ANSIBLE_CACHE_REDIS_SENTINEL
53 ini:
54 - key: fact_caching_redis_sentinel
55 section: defaults
56 version_added: 1.3.0
57 _timeout:
58 default: 86400
59 type: integer
60 # TODO: determine whether it is OK to change to: type: float
61 description: Expiration timeout in seconds for the cache plugin data. Set to 0 to never expire.
62 env:
63 - name: ANSIBLE_CACHE_PLUGIN_TIMEOUT
64 ini:
65 - key: fact_caching_timeout
66 section: defaults
67 """
68
69 import json
70 import re
71 import time
72
73 from ansible.errors import AnsibleError
74 from ansible.parsing.ajson import AnsibleJSONDecoder, AnsibleJSONEncoder
75 from ansible.plugins.cache import BaseCacheModule
76 from ansible.utils.display import Display
77
78 try:
79 from redis import VERSION, StrictRedis
80
81 HAS_REDIS = True
82 except ImportError:
83 HAS_REDIS = False
84
85 display = Display()
86
87
88 class CacheModule(BaseCacheModule):
89 """
90 A caching module backed by redis.
91
92 Keys are maintained in a zset with their score being the timestamp
93 when they are inserted. This allows for the usage of 'zremrangebyscore'
94 to expire keys. This mechanism is used or a pattern matched 'scan' for
95 performance.
96 """
97
98 _sentinel_service_name = None
99 re_url_conn = re.compile(r"^([^:]+|\[[^]]+\]):(\d+):(\d+)(?::(.*))?$")
100 re_sent_conn = re.compile(r"^(.*):(\d+)$")
101
102 def __init__(self, *args, **kwargs):
103 uri = ""
104
105 super().__init__(*args, **kwargs)
106 if self.get_option("_uri"):
107 uri = self.get_option("_uri")
108 self._timeout = float(self.get_option("_timeout"))
109 self._prefix = self.get_option("_prefix")
110 self._keys_set = self.get_option("_keyset_name")
111 self._sentinel_service_name = self.get_option("_sentinel_service_name")
112
113 if not HAS_REDIS:
114 raise AnsibleError(
115 "The 'redis' python module (version 2.4.5 or newer) is required for the redis fact cache, 'pip install redis'"
116 )
117
118 self._cache = {}
119 kw = {}
120
121 # tls connection
122 tlsprefix = "tls://"
123 if uri.startswith(tlsprefix):
124 kw["ssl"] = True
125 uri = uri[len(tlsprefix) :]
126
127 # redis sentinel connection
128 if self._sentinel_service_name:
129 self._db = self._get_sentinel_connection(uri, kw)
130 # normal connection
131 else:
132 connection = self._parse_connection(self.re_url_conn, uri)
133 self._db = StrictRedis(*connection, **kw)
134
135 display.vv(f"Redis connection: {self._db}")
136
137 @staticmethod
138 def _parse_connection(re_patt, uri):
139 match = re_patt.match(uri)
140 if not match:
141 raise AnsibleError("Unable to parse connection string")
142 return match.groups()
143
144 def _get_sentinel_connection(self, uri, kw):
145 """
146 get sentinel connection details from _uri
147 """
148 try:
149 from redis.sentinel import Sentinel
150 except ImportError as e:
151 raise AnsibleError(
152 "The 'redis' python module (version 2.9.0 or newer) is required to use redis sentinel."
153 ) from e
154
155 if ";" not in uri:
156 raise AnsibleError("_uri does not have sentinel syntax.")
157
158 # format: "localhost:26379;localhost2:26379;0:changeme"
159 connections = uri.split(";")
160 connection_args = connections.pop(-1)
161 if len(connection_args) > 0: # handle if no db nr is given
162 connection_args = connection_args.split(":")
163 kw["db"] = connection_args.pop(0)
164 try:
165 kw["password"] = connection_args.pop(0)
166 except IndexError:
167 pass # password is optional
168
169 sentinels = [self._parse_connection(self.re_sent_conn, shost) for shost in connections]
170 display.vv(f"\nUsing redis sentinels: {sentinels}")
171 scon = Sentinel(sentinels, **kw)
172 try:
173 return scon.master_for(self._sentinel_service_name, socket_timeout=0.2)
174 except Exception as exc:
175 raise AnsibleError(f"Could not connect to redis sentinel: {exc}") from exc
176
177 def _make_key(self, key):
178 return self._prefix + key
179
180 def get(self, key):
181 if key not in self._cache:
182 value = self._db.get(self._make_key(key))
183 # guard against the key not being removed from the zset;
184 # this could happen in cases where the timeout value is changed
185 # between invocations
186 if value is None:
187 self.delete(key)
188 raise KeyError
189 self._cache[key] = json.loads(value, cls=AnsibleJSONDecoder)
190
191 return self._cache.get(key)
192
193 def set(self, key, value):
194 value2 = json.dumps(value, cls=AnsibleJSONEncoder, sort_keys=True, indent=4)
195 if self._timeout > 0: # a timeout of 0 is handled as meaning 'never expire'
196 self._db.setex(self._make_key(key), int(self._timeout), value2)
197 else:
198 self._db.set(self._make_key(key), value2)
199
200 if VERSION[0] == 2:
201 self._db.zadd(self._keys_set, time.time(), key)
202 else:
203 self._db.zadd(self._keys_set, {key: time.time()})
204 self._cache[key] = value
205
206 def _expire_keys(self):
207 if self._timeout > 0:
208 expiry_age = time.time() - self._timeout
209 self._db.zremrangebyscore(self._keys_set, 0, expiry_age)
210
211 def keys(self):
212 self._expire_keys()
213 return self._db.zrange(self._keys_set, 0, -1)
214
215 def contains(self, key):
216 self._expire_keys()
217 return self._db.zrank(self._keys_set, key) is not None
218
219 def delete(self, key):
220 if key in self._cache:
221 del self._cache[key]
222 self._db.delete(self._make_key(key))
223 self._db.zrem(self._keys_set, key)
224
225 def flush(self):
226 for key in list(self.keys()):
227 self.delete(key)
228
229 def copy(self):
230 # TODO: there is probably a better way to do this in redis
231 ret = {k: self.get(k) for k in self.keys()}
232 return ret
233
234 def __getstate__(self):
235 return dict()
236
237 def __setstate__(self, data):
238 self.__init__()