1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2026-04-04 19:26:58 +00:00

Reformat everything.

This commit is contained in:
Felix Fontein 2025-11-01 12:08:41 +01:00
parent 3f2213791a
commit 340ff8586d
1008 changed files with 61301 additions and 58309 deletions

View file

@ -59,6 +59,7 @@ from ansible.utils.display import Display
try:
import memcache
HAS_MEMCACHE = True
except ImportError:
HAS_MEMCACHE = False
@ -75,7 +76,7 @@ class ProxyClientPool:
"""
def __init__(self, *args, **kwargs):
self.max_connections = kwargs.pop('max_connections', 1024)
self.max_connections = kwargs.pop("max_connections", 1024)
self.connection_args = args
self.connection_kwargs = kwargs
self.reset()
@ -123,6 +124,7 @@ class ProxyClientPool:
def __getattr__(self, name):
def wrapped(*args, **kwargs):
return self._proxy_client(name, *args, **kwargs)
return wrapped
def _proxy_client(self, name, *args, **kwargs):
@ -139,7 +141,8 @@ class CacheModuleKeys(MutableSet):
A set subclass that keeps track of insertion time and persists
the set in memcached.
"""
PREFIX = 'ansible_cache_keys'
PREFIX = "ansible_cache_keys"
def __init__(self, cache, *args, **kwargs):
self._cache = cache
@ -171,15 +174,14 @@ class CacheModuleKeys(MutableSet):
class CacheModule(BaseCacheModule):
def __init__(self, *args, **kwargs):
connection = ['127.0.0.1:11211']
connection = ["127.0.0.1:11211"]
super().__init__(*args, **kwargs)
if self.get_option('_uri'):
connection = self.get_option('_uri')
self._timeout = self.get_option('_timeout')
self._prefix = self.get_option('_prefix')
if self.get_option("_uri"):
connection = self.get_option("_uri")
self._timeout = self.get_option("_timeout")
self._prefix = self.get_option("_prefix")
if not HAS_MEMCACHE:
raise AnsibleError("python-memcached is required for the memcached fact cache")

View file

@ -51,14 +51,15 @@ class CacheModule(BaseFileCacheModule):
"""
A caching module backed by pickle files.
"""
_persistent = False # prevent unnecessary JSON serialization and key munging
def _load(self, filepath):
# Pickle is a binary format
with open(filepath, 'rb') as f:
return pickle.load(f, encoding='bytes')
with open(filepath, "rb") as f:
return pickle.load(f, encoding="bytes")
def _dump(self, value, filepath):
with open(filepath, 'wb') as f:
with open(filepath, "wb") as f:
# Use pickle protocol 2 which is compatible with Python 2.3+.
pickle.dump(value, f, protocol=2)

View file

@ -77,6 +77,7 @@ from ansible.utils.display import Display
try:
from redis import StrictRedis, VERSION
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
@ -93,32 +94,35 @@ class CacheModule(BaseCacheModule):
to expire keys. This mechanism is used or a pattern matched 'scan' for
performance.
"""
_sentinel_service_name = None
re_url_conn = re.compile(r'^([^:]+|\[[^]]+\]):(\d+):(\d+)(?::(.*))?$')
re_sent_conn = re.compile(r'^(.*):(\d+)$')
re_url_conn = re.compile(r"^([^:]+|\[[^]]+\]):(\d+):(\d+)(?::(.*))?$")
re_sent_conn = re.compile(r"^(.*):(\d+)$")
def __init__(self, *args, **kwargs):
uri = ''
uri = ""
super().__init__(*args, **kwargs)
if self.get_option('_uri'):
uri = self.get_option('_uri')
self._timeout = float(self.get_option('_timeout'))
self._prefix = self.get_option('_prefix')
self._keys_set = self.get_option('_keyset_name')
self._sentinel_service_name = self.get_option('_sentinel_service_name')
if self.get_option("_uri"):
uri = self.get_option("_uri")
self._timeout = float(self.get_option("_timeout"))
self._prefix = self.get_option("_prefix")
self._keys_set = self.get_option("_keyset_name")
self._sentinel_service_name = self.get_option("_sentinel_service_name")
if not HAS_REDIS:
raise AnsibleError("The 'redis' python module (version 2.4.5 or newer) is required for the redis fact cache, 'pip install redis'")
raise AnsibleError(
"The 'redis' python module (version 2.4.5 or newer) is required for the redis fact cache, 'pip install redis'"
)
self._cache = {}
kw = {}
# tls connection
tlsprefix = 'tls://'
tlsprefix = "tls://"
if uri.startswith(tlsprefix):
kw['ssl'] = True
uri = uri[len(tlsprefix):]
kw["ssl"] = True
uri = uri[len(tlsprefix) :]
# redis sentinel connection
if self._sentinel_service_name:
@ -128,7 +132,7 @@ class CacheModule(BaseCacheModule):
connection = self._parse_connection(self.re_url_conn, uri)
self._db = StrictRedis(*connection, **kw)
display.vv(f'Redis connection: {self._db}')
display.vv(f"Redis connection: {self._db}")
@staticmethod
def _parse_connection(re_patt, uri):
@ -146,33 +150,32 @@ class CacheModule(BaseCacheModule):
except ImportError:
raise AnsibleError("The 'redis' python module (version 2.9.0 or newer) is required to use redis sentinel.")
if ';' not in uri:
raise AnsibleError('_uri does not have sentinel syntax.')
if ";" not in uri:
raise AnsibleError("_uri does not have sentinel syntax.")
# format: "localhost:26379;localhost2:26379;0:changeme"
connections = uri.split(';')
connections = uri.split(";")
connection_args = connections.pop(-1)
if len(connection_args) > 0: # handle if no db nr is given
connection_args = connection_args.split(':')
kw['db'] = connection_args.pop(0)
connection_args = connection_args.split(":")
kw["db"] = connection_args.pop(0)
try:
kw['password'] = connection_args.pop(0)
kw["password"] = connection_args.pop(0)
except IndexError:
pass # password is optional
sentinels = [self._parse_connection(self.re_sent_conn, shost) for shost in connections]
display.vv(f'\nUsing redis sentinels: {sentinels}')
display.vv(f"\nUsing redis sentinels: {sentinels}")
scon = Sentinel(sentinels, **kw)
try:
return scon.master_for(self._sentinel_service_name, socket_timeout=0.2)
except Exception as exc:
raise AnsibleError(f'Could not connect to redis sentinel: {exc}')
raise AnsibleError(f"Could not connect to redis sentinel: {exc}")
def _make_key(self, key):
return self._prefix + key
def get(self, key):
if key not in self._cache:
value = self._db.get(self._make_key(key))
# guard against the key not being removed from the zset;
@ -186,7 +189,6 @@ class CacheModule(BaseCacheModule):
return self._cache.get(key)
def set(self, key, value):
value2 = json.dumps(value, cls=AnsibleJSONEncoder, sort_keys=True, indent=4)
if self._timeout > 0: # a timeout of 0 is handled as meaning 'never expire'
self._db.setex(self._make_key(key), int(self._timeout), value2)
@ -210,7 +212,7 @@ class CacheModule(BaseCacheModule):
def contains(self, key):
self._expire_keys()
return (self._db.zrank(self._keys_set, key) is not None)
return self._db.zrank(self._keys_set, key) is not None
def delete(self, key):
if key in self._cache:

View file

@ -58,9 +58,9 @@ class CacheModule(BaseFileCacheModule):
"""
def _load(self, filepath):
with open(os.path.abspath(filepath), 'r', encoding='utf-8') as f:
with open(os.path.abspath(filepath), "r", encoding="utf-8") as f:
return AnsibleLoader(f).get_single_data()
def _dump(self, value, filepath):
with open(os.path.abspath(filepath), 'w', encoding='utf-8') as f:
with open(os.path.abspath(filepath), "w", encoding="utf-8") as f:
yaml.dump(value, f, Dumper=AnsibleDumper, default_flow_style=False)