golden hour
/opt/saltstack/salt/lib/python3.10/site-packages/salt/utils
⬆️ Go Up
Upload
File/Folder
Size
Actions
__init__.py
237 B
Del
OK
__pycache__
-
Del
OK
aggregation.py
5.17 KB
Del
OK
ansible.py
1.48 KB
Del
OK
args.py
18.33 KB
Del
OK
asynchronous.py
4.06 KB
Del
OK
atomicfile.py
5.33 KB
Del
OK
aws.py
20.37 KB
Del
OK
azurearm.py
11.42 KB
Del
OK
beacons.py
517 B
Del
OK
boto3mod.py
8.36 KB
Del
OK
boto_elb_tag.py
3.02 KB
Del
OK
botomod.py
7.98 KB
Del
OK
cache.py
11.49 KB
Del
OK
channel.py
489 B
Del
OK
cloud.py
116.3 KB
Del
OK
color.py
2.72 KB
Del
OK
compat.py
1.89 KB
Del
OK
configcomparer.py
3.88 KB
Del
OK
configparser.py
10.82 KB
Del
OK
context.py
6.8 KB
Del
OK
crypt.py
5 KB
Del
OK
ctx.py
1.42 KB
Del
OK
data.py
53.03 KB
Del
OK
dateutils.py
2.3 KB
Del
OK
debug.py
4.19 KB
Del
OK
decorators
-
Del
OK
dictdiffer.py
16.48 KB
Del
OK
dicttrim.py
3.9 KB
Del
OK
dictupdate.py
11.33 KB
Del
OK
dns.py
35.21 KB
Del
OK
doc.py
2.25 KB
Del
OK
dockermod
-
Del
OK
entrypoints.py
1.83 KB
Del
OK
environment.py
2.2 KB
Del
OK
error.py
1.18 KB
Del
OK
etcd_util.py
33.25 KB
Del
OK
event.py
52.45 KB
Del
OK
extend.py
8.87 KB
Del
OK
extmods.py
6.04 KB
Del
OK
filebuffer.py
3.15 KB
Del
OK
files.py
27.94 KB
Del
OK
find.py
22.08 KB
Del
OK
fsutils.py
3.29 KB
Del
OK
functools.py
6.02 KB
Del
OK
gitfs.py
130.41 KB
Del
OK
github.py
1.52 KB
Del
OK
gzip_util.py
2.86 KB
Del
OK
hashutils.py
5.91 KB
Del
OK
http.py
33.9 KB
Del
OK
iam.py
1.22 KB
Del
OK
icinga2.py
754 B
Del
OK
idem.py
1.22 KB
Del
OK
immutabletypes.py
2.46 KB
Del
OK
itertools.py
2.36 KB
Del
OK
jid.py
3 KB
Del
OK
jinja.py
33.92 KB
Del
OK
job.py
6.89 KB
Del
OK
json.py
3.78 KB
Del
OK
kickstart.py
41.04 KB
Del
OK
kinds.py
493 B
Del
OK
lazy.py
3.06 KB
Del
OK
listdiffer.py
10.9 KB
Del
OK
locales.py
2.06 KB
Del
OK
mac_utils.py
14.01 KB
Del
OK
mako.py
3.97 KB
Del
OK
master.py
29.7 KB
Del
OK
mattermost.py
1.77 KB
Del
OK
memcached.py
3.56 KB
Del
OK
migrations.py
1.46 KB
Del
OK
mine.py
3.68 KB
Del
OK
minion.py
4.13 KB
Del
OK
minions.py
43.38 KB
Del
OK
mount.py
1.15 KB
Del
OK
msazure.py
5.36 KB
Del
OK
msgpack.py
4.69 KB
Del
OK
nacl.py
13.65 KB
Del
OK
namecheap.py
4.32 KB
Del
OK
napalm.py
23.22 KB
Del
OK
nb_popen.py
7.24 KB
Del
OK
network.py
73.86 KB
Del
OK
nxos.py
12.94 KB
Del
OK
nxos_api.py
4 KB
Del
OK
odict.py
13.21 KB
Del
OK
openstack
-
Del
OK
oset.py
6.41 KB
Del
OK
pagerduty.py
3.03 KB
Del
OK
parsers.py
122.69 KB
Del
OK
path.py
11.24 KB
Del
OK
pbm.py
9.81 KB
Del
OK
pkg
-
Del
OK
platform.py
5.84 KB
Del
OK
powershell.py
4.15 KB
Del
OK
preseed.py
2.64 KB
Del
OK
process.py
40.76 KB
Del
OK
profile.py
3.21 KB
Del
OK
proxy.py
331 B
Del
OK
psutil_compat.py
3.63 KB
Del
OK
pushover.py
4.51 KB
Del
OK
pycrypto.py
5.41 KB
Del
OK
pydsl.py
13.74 KB
Del
OK
pyobjects.py
10.75 KB
Del
OK
reactor.py
18.99 KB
Del
OK
reclass.py
752 B
Del
OK
roster_matcher.py
3.55 KB
Del
OK
rsax931.py
8.42 KB
Del
OK
s3.py
8.78 KB
Del
OK
saltclass.py
14.27 KB
Del
OK
sanitizers.py
2.51 KB
Del
OK
schedule.py
71.81 KB
Del
OK
schema.py
54.26 KB
Del
OK
sdb.py
4.04 KB
Del
OK
slack.py
3.58 KB
Del
OK
smb.py
11.16 KB
Del
OK
smtp.py
3.27 KB
Del
OK
ssdp.py
14.75 KB
Del
OK
ssh.py
769 B
Del
OK
state.py
8.43 KB
Del
OK
stringio.py
355 B
Del
OK
stringutils.py
16.95 KB
Del
OK
systemd.py
5.51 KB
Del
OK
templates.py
24.03 KB
Del
OK
textformat.py
5.03 KB
Del
OK
thin.py
31.91 KB
Del
OK
timed_subprocess.py
4.06 KB
Del
OK
timeout.py
1.53 KB
Del
OK
timeutil.py
2.4 KB
Del
OK
url.py
5 KB
Del
OK
user.py
11.86 KB
Del
OK
validate
-
Del
OK
value.py
247 B
Del
OK
vault.py
21.74 KB
Del
OK
verify.py
25.34 KB
Del
OK
versions.py
17.17 KB
Del
OK
virt.py
3.24 KB
Del
OK
virtualbox.py
22.43 KB
Del
OK
vmware.py
129.74 KB
Del
OK
vsan.py
17.18 KB
Del
OK
vt.py
31.47 KB
Del
OK
vt_helper.py
4.4 KB
Del
OK
win_chcp.py
3.7 KB
Del
OK
win_dacl.py
95.49 KB
Del
OK
win_dotnet.py
4.74 KB
Del
OK
win_functions.py
12.69 KB
Del
OK
win_lgpo_auditpol.py
8.48 KB
Del
OK
win_lgpo_netsh.py
17.87 KB
Del
OK
win_lgpo_reg.py
16.98 KB
Del
OK
win_network.py
16.35 KB
Del
OK
win_osinfo.py
2.83 KB
Del
OK
win_pdh.py
13.85 KB
Del
OK
win_reg.py
30.82 KB
Del
OK
win_runas.py
10.53 KB
Del
OK
win_service.py
5.2 KB
Del
OK
win_system.py
14.47 KB
Del
OK
win_update.py
40.36 KB
Del
OK
winapi.py
818 B
Del
OK
x509.py
73.19 KB
Del
OK
xdg.py
316 B
Del
OK
xmlutil.py
13.91 KB
Del
OK
yaml.py
349 B
Del
OK
yamldumper.py
3.37 KB
Del
OK
yamlencoding.py
1.55 KB
Del
OK
yamllint.py
1.61 KB
Del
OK
yamlloader.py
6.04 KB
Del
OK
yamlloader_old.py
8.15 KB
Del
OK
yast.py
619 B
Del
OK
zeromq.py
1.74 KB
Del
OK
zfs.py
19.15 KB
Del
OK
Edit: cache.py
""" In-memory caching used by Salt """ import functools import logging import os import re import shutil import time import salt.config import salt.payload import salt.utils.atomicfile import salt.utils.data import salt.utils.dictupdate import salt.utils.files import salt.utils.msgpack import salt.utils.path import salt.version from salt.utils.zeromq import zmq log = logging.getLogger(__name__) class CacheFactory: """ Cache which can use a number of backends """ @classmethod def factory(cls, backend, ttl, *args, **kwargs): log.debug("Factory backend: %s", backend) if backend == "memory": return CacheDict(ttl, *args, **kwargs) elif backend == "disk": return CacheDisk(ttl, kwargs["minion_cache_path"], *args, **kwargs) else: log.error("CacheFactory received unrecognized cache type") class CacheDict(dict): """ Subclass of dict that will lazily delete items past ttl """ def __init__(self, ttl, *args, **kwargs): dict.__init__(self, *args, **kwargs) self._ttl = ttl self._key_cache_time = {} def _enforce_ttl_key(self, key): """ Enforce the TTL to a specific key, delete if its past TTL """ if key not in self._key_cache_time: return if time.time() - self._key_cache_time[key] > self._ttl: del self._key_cache_time[key] dict.__delitem__(self, key) def __getitem__(self, key): """ Check if the key is ttld out, then do the get """ self._enforce_ttl_key(key) return dict.__getitem__(self, key) def __setitem__(self, key, val): """ Make sure to update the key cache time """ self._key_cache_time[key] = time.time() dict.__setitem__(self, key, val) def __contains__(self, key): self._enforce_ttl_key(key) return dict.__contains__(self, key) class CacheDisk(CacheDict): """ Class that represents itself as a dictionary to a consumer but uses a disk-based backend. Serialization and de-serialization is done with msgpack """ def __init__(self, ttl, path, *args, **kwargs): super().__init__(ttl, *args, **kwargs) self._path = path self._dict = {} self._read() def _enforce_ttl_key(self, key): """ Enforce the TTL to a specific key, delete if its past TTL """ if key not in self._key_cache_time: return if time.time() - self._key_cache_time[key] > self._ttl: del self._key_cache_time[key] self._dict.__delitem__(key) def __contains__(self, key): self._enforce_ttl_key(key) return self._dict.__contains__(key) def __getitem__(self, key): """ Check if the key is ttld out, then do the get """ self._enforce_ttl_key(key) return self._dict.__getitem__(key) def __setitem__(self, key, val): """ Make sure to update the key cache time """ self._key_cache_time[key] = time.time() self._dict.__setitem__(key, val) # Do the same as the parent but also persist self._write() def __delitem__(self, key): """ Make sure to remove the key cache time """ del self._key_cache_time[key] self._dict.__delitem__(key) # Do the same as the parent but also persist self._write() def clear(self): """ Clear the cache """ self._key_cache_time.clear() self._dict.clear() # Do the same as the parent but also persist self._write() def _read(self): """ Read in from disk """ if not salt.utils.msgpack.HAS_MSGPACK or not os.path.exists(self._path): return if 0 == os.path.getsize(self._path): # File exists but empty, treat as empty cache return try: with salt.utils.files.fopen(self._path, "rb") as fp_: cache = salt.utils.msgpack.load( fp_, encoding=__salt_system_encoding__, raw=False ) except FileNotFoundError: # File was deleted after os.path.exists call above, treat as empty cache return except (salt.utils.msgpack.exceptions.UnpackException, ValueError) as exc: # File is unreadable, treat as empty cache if log.isEnabledFor(logging.DEBUG): log.debug("Error reading cache file at %r: %s", self._path, exc) return if "CacheDisk_cachetime" in cache: # new format self._dict = cache["CacheDisk_data"] self._key_cache_time = cache["CacheDisk_cachetime"] else: # old format self._dict = cache timestamp = os.path.getmtime(self._path) for key in self._dict: self._key_cache_time[key] = timestamp if log.isEnabledFor(logging.DEBUG): log.debug("Disk cache retrieved: %s", cache) def _write(self): """ Write out to disk """ if not salt.utils.msgpack.HAS_MSGPACK: return # TODO Add check into preflight to ensure dir exists # TODO Dir hashing? with salt.utils.atomicfile.atomic_open(self._path, "wb+") as fp_: cache = { "CacheDisk_data": self._dict, "CacheDisk_cachetime": self._key_cache_time, } salt.utils.msgpack.dump(cache, fp_) class CacheCli: """ Connection client for the ConCache. Should be used by all components that need the list of currently connected minions """ def __init__(self, opts): """ Sets up the zmq-connection to the ConCache """ self.opts = opts self.cache_sock = os.path.join(self.opts["sock_dir"], "con_cache.ipc") self.cache_upd_sock = os.path.join(self.opts["sock_dir"], "con_upd.ipc") context = zmq.Context() # the socket for talking to the cache self.creq_out = context.socket(zmq.REQ) self.creq_out.setsockopt(zmq.LINGER, 100) self.creq_out.connect("ipc://" + self.cache_sock) # the socket for sending updates to the cache self.cupd_out = context.socket(zmq.PUB) self.cupd_out.setsockopt(zmq.LINGER, 1) self.cupd_out.connect("ipc://" + self.cache_upd_sock) def put_cache(self, minions): """ published the given minions to the ConCache """ self.cupd_out.send(salt.payload.dumps(minions), track=False) def get_cached(self): """ queries the ConCache for a list of currently connected minions """ msg = salt.payload.dumps("minions") self.creq_out.send(msg, track=False) min_list = salt.payload.loads(self.creq_out.recv()) return min_list class CacheRegex: """ Create a regular expression object cache for the most frequently used patterns to minimize compilation of the same patterns over and over again """ def __init__( self, prepend="", append="", size=1000, keep_fraction=0.8, max_age=3600 ): self.prepend = prepend self.append = append self.size = size self.clear_size = int(size - size * (keep_fraction)) if self.clear_size >= size: self.clear_size = int(size / 2) + 1 if self.clear_size > size: self.clear_size = size self.max_age = max_age self.cache = {} self.timestamp = time.time() def clear(self): """ Clear the cache """ self.cache.clear() def sweep(self): """ Sweep the cache and remove the outdated or least frequently used entries """ if self.max_age < time.time() - self.timestamp: self.clear() self.timestamp = time.time() else: paterns = list(self.cache.values()) paterns.sort() for idx in range(self.clear_size): del self.cache[paterns[idx][2]] def get(self, pattern): """ Get a compiled regular expression object based on pattern and cache it when it is not in the cache already """ try: self.cache[pattern][0] += 1 return self.cache[pattern][1] except KeyError: pass if len(self.cache) > self.size: self.sweep() regex = re.compile("{}{}{}".format(self.prepend, pattern, self.append)) self.cache[pattern] = [1, regex, pattern, time.time()] return regex class ContextCache: def __init__(self, opts, name): """ Create a context cache """ self.opts = opts self.cache_path = os.path.join(opts["cachedir"], "context", "{}.p".format(name)) def cache_context(self, context): """ Cache the given context to disk """ if not os.path.isdir(os.path.dirname(self.cache_path)): os.mkdir(os.path.dirname(self.cache_path)) with salt.utils.files.fopen(self.cache_path, "w+b") as cache: salt.payload.dump(context, cache) def get_cache_context(self): """ Retrieve a context cache from disk """ with salt.utils.files.fopen(self.cache_path, "rb") as cache: return salt.utils.data.decode(salt.payload.load(cache)) def context_cache(func): """ A decorator to be used module functions which need to cache their context. To evaluate a __context__ and re-hydrate it if a given key is empty or contains no items, pass a list of keys to evaulate. """ @functools.wraps(func) def context_cache_wrap(*args, **kwargs): try: func_context = func.__globals__["__context__"].value() except AttributeError: func_context = func.__globals__["__context__"] try: func_opts = func.__globals__["__opts__"].value() except AttributeError: func_opts = func.__globals__["__opts__"] func_name = func.__globals__["__name__"] context_cache = ContextCache(func_opts, func_name) if not func_context and os.path.isfile(context_cache.cache_path): salt.utils.dictupdate.update( func_context, context_cache.get_cache_context() ) else: context_cache.cache_context(func_context) return func(*args, **kwargs) return context_cache_wrap def verify_cache_version(cache_path): """ Check that the cached version matches the Salt version. If the cached version does not match the Salt version, wipe the cache. :return: ``True`` if cache version matches, otherwise ``False`` """ if not os.path.isdir(cache_path): os.makedirs(cache_path) with salt.utils.files.fopen( salt.utils.path.join(cache_path, "cache_version"), "a+" ) as file: file.seek(0) data = "\n".join(file.readlines()) if data != salt.version.__version__: log.warning(f"Cache version mismatch clearing: {repr(cache_path)}") file.truncate(0) file.write(salt.version.__version__) for item in os.listdir(cache_path): if item != "cache_version": item_path = salt.utils.path.join(cache_path, item) if os.path.isfile(item_path): os.remove(item_path) else: shutil.rmtree(item_path) return False return True
Save