repository_name
stringclasses 316
values | func_path_in_repository
stringlengths 6
223
| func_name
stringlengths 1
134
| language
stringclasses 1
value | func_code_string
stringlengths 57
65.5k
| func_documentation_string
stringlengths 1
46.3k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
| called_functions
listlengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
|---|---|---|---|---|---|---|---|---|---|
saltstack/salt
|
salt/modules/saltutil.py
|
_sync
|
python
|
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
|
Sync the given directory in the given environment
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L101-L123
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def sync(opts,\n form,\n saltenv=None,\n extmod_whitelist=None,\n extmod_blacklist=None):\n '''\n Sync custom modules into the extension_modules directory\n '''\n if saltenv is None:\n saltenv = ['base']\n\n if extmod_whitelist is None:\n extmod_whitelist = opts['extmod_whitelist']\n elif isinstance(extmod_whitelist, six.string_types):\n extmod_whitelist = {form: extmod_whitelist.split(',')}\n elif not isinstance(extmod_whitelist, dict):\n log.error('extmod_whitelist must be a string or dictionary: %s',\n extmod_whitelist)\n\n if extmod_blacklist is None:\n extmod_blacklist = opts['extmod_blacklist']\n elif isinstance(extmod_blacklist, six.string_types):\n extmod_blacklist = {form: extmod_blacklist.split(',')}\n elif not isinstance(extmod_blacklist, dict):\n log.error('extmod_blacklist must be a string or dictionary: %s',\n extmod_blacklist)\n\n if isinstance(saltenv, six.string_types):\n saltenv = saltenv.split(',')\n ret = []\n remote = set()\n source = salt.utils.url.create('_' + form)\n mod_dir = os.path.join(opts['extension_modules'], '{0}'.format(form))\n touched = False\n with salt.utils.files.set_umask(0o077):\n try:\n if not os.path.isdir(mod_dir):\n log.info('Creating module dir \\'%s\\'', mod_dir)\n try:\n os.makedirs(mod_dir)\n except (IOError, OSError):\n log.error(\n 'Cannot create cache module directory %s. Check '\n 'permissions.', mod_dir\n )\n fileclient = salt.fileclient.get_file_client(opts)\n for sub_env in saltenv:\n log.info(\n 'Syncing %s for environment \\'%s\\'', form, sub_env\n )\n cache = []\n log.info('Loading cache from %s, for %s', source, sub_env)\n # Grab only the desired files (.py, .pyx, .so)\n cache.extend(\n fileclient.cache_dir(\n source, sub_env, include_empty=False,\n include_pat=r'E@\\.(pyx?|so|zip)$', exclude_pat=None\n )\n )\n local_cache_dir = os.path.join(\n opts['cachedir'],\n 'files',\n sub_env,\n '_{0}'.format(form)\n )\n log.debug('Local cache dir: \\'%s\\'', local_cache_dir)\n for fn_ in cache:\n relpath = os.path.relpath(fn_, local_cache_dir)\n relname = os.path.splitext(relpath)[0].replace(os.sep, '.')\n if extmod_whitelist and form in extmod_whitelist and relname not in extmod_whitelist[form]:\n continue\n if extmod_blacklist and form in extmod_blacklist and relname in extmod_blacklist[form]:\n continue\n remote.add(relpath)\n dest = os.path.join(mod_dir, relpath)\n log.info('Copying \\'%s\\' to \\'%s\\'', fn_, dest)\n if os.path.isfile(dest):\n # The file is present, if the sum differs replace it\n hash_type = opts.get('hash_type', 'md5')\n src_digest = salt.utils.hashutils.get_hash(fn_, hash_type)\n dst_digest = salt.utils.hashutils.get_hash(dest, hash_type)\n if src_digest != dst_digest:\n # The downloaded file differs, replace!\n shutil.copyfile(fn_, dest)\n ret.append('{0}.{1}'.format(form, relname))\n else:\n dest_dir = os.path.dirname(dest)\n if not os.path.isdir(dest_dir):\n os.makedirs(dest_dir)\n shutil.copyfile(fn_, dest)\n ret.append('{0}.{1}'.format(form, relname))\n\n # If the synchronized module is an utils\n # directory, we add it to sys.path\n for util_dir in opts['utils_dirs']:\n if mod_dir.endswith(util_dir) and mod_dir not in sys.path:\n sys.path.append(mod_dir)\n\n touched = bool(ret)\n if opts['clean_dynamic_modules'] is True:\n current = set(_listdir_recursively(mod_dir))\n for fn_ in current - remote:\n full = os.path.join(mod_dir, fn_)\n if os.path.isfile(full):\n touched = True\n os.remove(full)\n # Cleanup empty dirs\n while True:\n emptydirs = _list_emptydirs(mod_dir)\n if not emptydirs:\n break\n for emptydir in emptydirs:\n touched = True\n shutil.rmtree(emptydir, ignore_errors=True)\n except Exception as exc:\n log.error('Failed to sync %s module: %s', form, exc)\n return ret, touched\n",
"def _get_top_file_envs():\n '''\n Get all environments from the top file\n '''\n try:\n return __context__['saltutil._top_file_envs']\n except KeyError:\n try:\n st_ = salt.state.HighState(__opts__,\n initial_pillar=__pillar__)\n top = st_.get_top()\n if top:\n envs = list(st_.top_matches(top).keys()) or 'base'\n else:\n envs = 'base'\n except SaltRenderError as exc:\n raise CommandExecutionError(\n 'Unable to render top file(s): {0}'.format(exc)\n )\n __context__['saltutil._top_file_envs'] = envs\n return envs\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
update
|
python
|
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
|
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L126-L189
| null |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
sync_beacons
|
python
|
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
|
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L192-L228
|
[
"def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):\n '''\n Sync the given directory in the given environment\n '''\n if saltenv is None:\n saltenv = _get_top_file_envs()\n if isinstance(saltenv, six.string_types):\n saltenv = saltenv.split(',')\n ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,\n extmod_blacklist=extmod_blacklist)\n # Dest mod_dir is touched? trigger reload if requested\n if touched:\n mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')\n with salt.utils.files.fopen(mod_file, 'a'):\n pass\n if form == 'grains' and \\\n __opts__.get('grains_cache') and \\\n os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):\n try:\n os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))\n except OSError:\n log.error('Could not remove grains cache!')\n return ret\n",
"def refresh_beacons():\n '''\n Signal the minion to refresh the beacons.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' saltutil.refresh_beacons\n '''\n try:\n ret = __salt__['event.fire']({}, 'beacons_refresh')\n except KeyError:\n log.error('Event module not available. Module refresh failed.')\n ret = False # Effectively a no-op, since we can't really return without an event system\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
sync_sdb
|
python
|
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
|
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L231-L264
|
[
"def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):\n '''\n Sync the given directory in the given environment\n '''\n if saltenv is None:\n saltenv = _get_top_file_envs()\n if isinstance(saltenv, six.string_types):\n saltenv = saltenv.split(',')\n ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,\n extmod_blacklist=extmod_blacklist)\n # Dest mod_dir is touched? trigger reload if requested\n if touched:\n mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')\n with salt.utils.files.fopen(mod_file, 'a'):\n pass\n if form == 'grains' and \\\n __opts__.get('grains_cache') and \\\n os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):\n try:\n os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))\n except OSError:\n log.error('Could not remove grains cache!')\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
sync_modules
|
python
|
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
|
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L267-L320
|
[
"def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):\n '''\n Sync the given directory in the given environment\n '''\n if saltenv is None:\n saltenv = _get_top_file_envs()\n if isinstance(saltenv, six.string_types):\n saltenv = saltenv.split(',')\n ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,\n extmod_blacklist=extmod_blacklist)\n # Dest mod_dir is touched? trigger reload if requested\n if touched:\n mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')\n with salt.utils.files.fopen(mod_file, 'a'):\n pass\n if form == 'grains' and \\\n __opts__.get('grains_cache') and \\\n os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):\n try:\n os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))\n except OSError:\n log.error('Could not remove grains cache!')\n return ret\n",
"def refresh_modules(**kwargs):\n '''\n Signal the minion to refresh the module and grain data\n\n The default is to refresh module asynchronously. To block\n until the module refresh is complete, set the 'async' flag\n to False.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' saltutil.refresh_modules\n '''\n asynchronous = bool(kwargs.get('async', True))\n try:\n if asynchronous:\n # If we're going to block, first setup a listener\n ret = __salt__['event.fire']({}, 'module_refresh')\n else:\n eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)\n ret = __salt__['event.fire']({'notify': True}, 'module_refresh')\n # Wait for the finish event to fire\n log.trace('refresh_modules waiting for module refresh to complete')\n # Blocks until we hear this event or until the timeout expires\n eventer.get_event(\n tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)\n except KeyError:\n log.error('Event module not available. Module refresh failed.')\n ret = False # Effectively a no-op, since we can't really return without an event system\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
refresh_grains
|
python
|
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
|
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L362-L392
|
[
"def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n",
"def invalid_kwargs(invalid_kwargs, raise_exc=True):\n '''\n Raise a SaltInvocationError if invalid_kwargs is non-empty\n '''\n if invalid_kwargs:\n if isinstance(invalid_kwargs, dict):\n new_invalid = [\n '{0}={1}'.format(x, y)\n for x, y in six.iteritems(invalid_kwargs)\n ]\n invalid_kwargs = new_invalid\n msg = (\n 'The following keyword arguments are not valid: {0}'\n .format(', '.join(invalid_kwargs))\n )\n if raise_exc:\n raise SaltInvocationError(msg)\n else:\n return msg\n",
"def refresh_modules(**kwargs):\n '''\n Signal the minion to refresh the module and grain data\n\n The default is to refresh module asynchronously. To block\n until the module refresh is complete, set the 'async' flag\n to False.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' saltutil.refresh_modules\n '''\n asynchronous = bool(kwargs.get('async', True))\n try:\n if asynchronous:\n # If we're going to block, first setup a listener\n ret = __salt__['event.fire']({}, 'module_refresh')\n else:\n eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)\n ret = __salt__['event.fire']({'notify': True}, 'module_refresh')\n # Wait for the finish event to fire\n log.trace('refresh_modules waiting for module refresh to complete')\n # Blocks until we hear this event or until the timeout expires\n eventer.get_event(\n tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)\n except KeyError:\n log.error('Event module not available. Module refresh failed.')\n ret = False # Effectively a no-op, since we can't really return without an event system\n return ret\n",
"def refresh_pillar(**kwargs):\n '''\n Signal the minion to refresh the pillar data.\n\n .. versionchanged:: Neon\n The ``async`` argument has been added. The default value is True.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' saltutil.refresh_pillar\n salt '*' saltutil.refresh_pillar async=False\n '''\n asynchronous = bool(kwargs.get('async', True))\n try:\n if asynchronous:\n # If we're going to block, first setup a listener\n ret = __salt__['event.fire']({}, 'pillar_refresh')\n else:\n eventer = salt.utils.event.get_event(\n 'minion', opts=__opts__, listen=True)\n ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')\n # Wait for the finish event to fire\n log.trace('refresh_pillar waiting for pillar refresh to complete')\n # Blocks until we hear this event or until the timeout expires\n eventer.get_event(\n tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)\n except KeyError:\n log.error('Event module not available. Pillar refresh failed.')\n ret = False # Effectively a no-op, since we can't really return without an event system\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
sync_grains
|
python
|
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
|
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L395-L433
|
[
"def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):\n '''\n Sync the given directory in the given environment\n '''\n if saltenv is None:\n saltenv = _get_top_file_envs()\n if isinstance(saltenv, six.string_types):\n saltenv = saltenv.split(',')\n ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,\n extmod_blacklist=extmod_blacklist)\n # Dest mod_dir is touched? trigger reload if requested\n if touched:\n mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')\n with salt.utils.files.fopen(mod_file, 'a'):\n pass\n if form == 'grains' and \\\n __opts__.get('grains_cache') and \\\n os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):\n try:\n os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))\n except OSError:\n log.error('Could not remove grains cache!')\n return ret\n",
"def refresh_modules(**kwargs):\n '''\n Signal the minion to refresh the module and grain data\n\n The default is to refresh module asynchronously. To block\n until the module refresh is complete, set the 'async' flag\n to False.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' saltutil.refresh_modules\n '''\n asynchronous = bool(kwargs.get('async', True))\n try:\n if asynchronous:\n # If we're going to block, first setup a listener\n ret = __salt__['event.fire']({}, 'module_refresh')\n else:\n eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)\n ret = __salt__['event.fire']({'notify': True}, 'module_refresh')\n # Wait for the finish event to fire\n log.trace('refresh_modules waiting for module refresh to complete')\n # Blocks until we hear this event or until the timeout expires\n eventer.get_event(\n tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)\n except KeyError:\n log.error('Event module not available. Module refresh failed.')\n ret = False # Effectively a no-op, since we can't really return without an event system\n return ret\n",
"def refresh_pillar(**kwargs):\n '''\n Signal the minion to refresh the pillar data.\n\n .. versionchanged:: Neon\n The ``async`` argument has been added. The default value is True.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' saltutil.refresh_pillar\n salt '*' saltutil.refresh_pillar async=False\n '''\n asynchronous = bool(kwargs.get('async', True))\n try:\n if asynchronous:\n # If we're going to block, first setup a listener\n ret = __salt__['event.fire']({}, 'pillar_refresh')\n else:\n eventer = salt.utils.event.get_event(\n 'minion', opts=__opts__, listen=True)\n ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')\n # Wait for the finish event to fire\n log.trace('refresh_pillar waiting for pillar refresh to complete')\n # Blocks until we hear this event or until the timeout expires\n eventer.get_event(\n tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)\n except KeyError:\n log.error('Event module not available. Pillar refresh failed.')\n ret = False # Effectively a no-op, since we can't really return without an event system\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
sync_matchers
|
python
|
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
|
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L553-L588
|
[
"def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):\n '''\n Sync the given directory in the given environment\n '''\n if saltenv is None:\n saltenv = _get_top_file_envs()\n if isinstance(saltenv, six.string_types):\n saltenv = saltenv.split(',')\n ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,\n extmod_blacklist=extmod_blacklist)\n # Dest mod_dir is touched? trigger reload if requested\n if touched:\n mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')\n with salt.utils.files.fopen(mod_file, 'a'):\n pass\n if form == 'grains' and \\\n __opts__.get('grains_cache') and \\\n os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):\n try:\n os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))\n except OSError:\n log.error('Could not remove grains cache!')\n return ret\n",
"def refresh_modules(**kwargs):\n '''\n Signal the minion to refresh the module and grain data\n\n The default is to refresh module asynchronously. To block\n until the module refresh is complete, set the 'async' flag\n to False.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' saltutil.refresh_modules\n '''\n asynchronous = bool(kwargs.get('async', True))\n try:\n if asynchronous:\n # If we're going to block, first setup a listener\n ret = __salt__['event.fire']({}, 'module_refresh')\n else:\n eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)\n ret = __salt__['event.fire']({'notify': True}, 'module_refresh')\n # Wait for the finish event to fire\n log.trace('refresh_modules waiting for module refresh to complete')\n # Blocks until we hear this event or until the timeout expires\n eventer.get_event(\n tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)\n except KeyError:\n log.error('Event module not available. Module refresh failed.')\n ret = False # Effectively a no-op, since we can't really return without an event system\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
list_extmods
|
python
|
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
|
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L859-L880
|
[
"def os_walk(top, *args, **kwargs):\n '''\n This is a helper than ensures that all paths returned from os.walk are\n unicode.\n '''\n if six.PY2 and salt.utils.platform.is_windows():\n top_query = top\n else:\n top_query = salt.utils.stringutils.to_str(top)\n for item in os.walk(top_query, *args, **kwargs):\n yield salt.utils.data.decode(item, preserve_tuples=True)\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
sync_pillar
|
python
|
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
|
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L922-L960
|
[
"def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):\n '''\n Sync the given directory in the given environment\n '''\n if saltenv is None:\n saltenv = _get_top_file_envs()\n if isinstance(saltenv, six.string_types):\n saltenv = saltenv.split(',')\n ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,\n extmod_blacklist=extmod_blacklist)\n # Dest mod_dir is touched? trigger reload if requested\n if touched:\n mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')\n with salt.utils.files.fopen(mod_file, 'a'):\n pass\n if form == 'grains' and \\\n __opts__.get('grains_cache') and \\\n os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):\n try:\n os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))\n except OSError:\n log.error('Could not remove grains cache!')\n return ret\n",
"def refresh_modules(**kwargs):\n '''\n Signal the minion to refresh the module and grain data\n\n The default is to refresh module asynchronously. To block\n until the module refresh is complete, set the 'async' flag\n to False.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' saltutil.refresh_modules\n '''\n asynchronous = bool(kwargs.get('async', True))\n try:\n if asynchronous:\n # If we're going to block, first setup a listener\n ret = __salt__['event.fire']({}, 'module_refresh')\n else:\n eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)\n ret = __salt__['event.fire']({'notify': True}, 'module_refresh')\n # Wait for the finish event to fire\n log.trace('refresh_modules waiting for module refresh to complete')\n # Blocks until we hear this event or until the timeout expires\n eventer.get_event(\n tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)\n except KeyError:\n log.error('Event module not available. Module refresh failed.')\n ret = False # Effectively a no-op, since we can't really return without an event system\n return ret\n",
"def refresh_pillar(**kwargs):\n '''\n Signal the minion to refresh the pillar data.\n\n .. versionchanged:: Neon\n The ``async`` argument has been added. The default value is True.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' saltutil.refresh_pillar\n salt '*' saltutil.refresh_pillar async=False\n '''\n asynchronous = bool(kwargs.get('async', True))\n try:\n if asynchronous:\n # If we're going to block, first setup a listener\n ret = __salt__['event.fire']({}, 'pillar_refresh')\n else:\n eventer = salt.utils.event.get_event(\n 'minion', opts=__opts__, listen=True)\n ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')\n # Wait for the finish event to fire\n log.trace('refresh_pillar waiting for pillar refresh to complete')\n # Blocks until we hear this event or until the timeout expires\n eventer.get_event(\n tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)\n except KeyError:\n log.error('Event module not available. Pillar refresh failed.')\n ret = False # Effectively a no-op, since we can't really return without an event system\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
sync_all
|
python
|
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
|
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L963-L1034
|
[
"def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):\n '''\n .. versionadded:: 2017.7.0\n\n Sync cloud modules from ``salt://_cloud`` to the minion\n\n saltenv : base\n The fileserver environment from which to sync. To sync from more than\n one environment, pass a comma-separated list.\n\n refresh : True\n If ``True``, refresh the available execution modules on the minion.\n This refresh will be performed even if no new utility modules are\n synced. Set to ``False`` to prevent this refresh.\n\n extmod_whitelist : None\n comma-seperated list of modules to sync\n\n extmod_blacklist : None\n comma-seperated list of modules to blacklist based on type\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' saltutil.sync_clouds\n salt '*' saltutil.sync_clouds saltenv=dev\n salt '*' saltutil.sync_clouds saltenv=base,dev\n '''\n ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)\n if refresh:\n refresh_modules()\n return ret\n",
"def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):\n '''\n .. versionadded:: 0.10.0\n\n Sync execution modules from ``salt://_modules`` to the minion\n\n saltenv\n The fileserver environment from which to sync. To sync from more than\n one environment, pass a comma-separated list.\n\n If not passed, then all environments configured in the :ref:`top files\n <states-top>` will be checked for execution modules to sync. If no top\n files are found, then the ``base`` environment will be synced.\n\n refresh : True\n If ``True``, refresh the available execution modules on the minion.\n This refresh will be performed even if no new execution modules are\n synced. Set to ``False`` to prevent this refresh.\n\n .. important::\n\n If this function is executed using a :py:func:`module.run\n <salt.states.module.run>` state, the SLS file will not have access to\n newly synced execution modules unless a ``refresh`` argument is\n added to the state, like so:\n\n .. code-block:: yaml\n\n load_my_custom_module:\n module.run:\n - name: saltutil.sync_modules\n - refresh: True\n\n See :ref:`here <reloading-modules>` for a more detailed explanation of\n why this is necessary.\n\n extmod_whitelist : None\n comma-seperated list of modules to sync\n\n extmod_blacklist : None\n comma-seperated list of modules to blacklist based on type\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' saltutil.sync_modules\n salt '*' saltutil.sync_modules saltenv=dev\n salt '*' saltutil.sync_modules saltenv=base,dev\n '''\n ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)\n if refresh:\n refresh_modules()\n return ret\n",
"def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):\n '''\n .. versionadded:: 0.10.0\n\n Sync state modules from ``salt://_states`` to the minion\n\n saltenv\n The fileserver environment from which to sync. To sync from more than\n one environment, pass a comma-separated list.\n\n If not passed, then all environments configured in the :ref:`top files\n <states-top>` will be checked for state modules to sync. If no top\n files are found, then the ``base`` environment will be synced.\n\n refresh : True\n If ``True``, refresh the available states on the minion. This refresh\n will be performed even if no new state modules are synced. Set to\n ``False`` to prevent this refresh.\n\n extmod_whitelist : None\n comma-seperated list of modules to sync\n\n extmod_blacklist : None\n comma-seperated list of modules to blacklist based on type\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' saltutil.sync_states\n salt '*' saltutil.sync_states saltenv=dev\n salt '*' saltutil.sync_states saltenv=base,dev\n '''\n ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)\n if refresh:\n refresh_modules()\n return ret\n",
"def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):\n '''\n .. versionadded:: 0.10.0\n\n Sync grains modules from ``salt://_grains`` to the minion\n\n saltenv\n The fileserver environment from which to sync. To sync from more than\n one environment, pass a comma-separated list.\n\n If not passed, then all environments configured in the :ref:`top files\n <states-top>` will be checked for grains modules to sync. If no top\n files are found, then the ``base`` environment will be synced.\n\n refresh : True\n If ``True``, refresh the available execution modules and recompile\n pillar data for the minion. This refresh will be performed even if no\n new grains modules are synced. Set to ``False`` to prevent this\n refresh.\n\n extmod_whitelist : None\n comma-seperated list of modules to sync\n\n extmod_blacklist : None\n comma-seperated list of modules to blacklist based on type\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' saltutil.sync_grains\n salt '*' saltutil.sync_grains saltenv=dev\n salt '*' saltutil.sync_grains saltenv=base,dev\n '''\n ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)\n if refresh:\n refresh_modules()\n refresh_pillar()\n return ret\n",
"def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):\n '''\n .. versionadded:: 0.10.0\n\n Sync renderers from ``salt://_renderers`` to the minion\n\n saltenv\n The fileserver environment from which to sync. To sync from more than\n one environment, pass a comma-separated list.\n\n If not passed, then all environments configured in the :ref:`top files\n <states-top>` will be checked for renderers to sync. If no top files\n are found, then the ``base`` environment will be synced.\n\n refresh : True\n If ``True``, refresh the available execution modules on the minion.\n This refresh will be performed even if no new renderers are synced.\n Set to ``False`` to prevent this refresh. Set to ``False`` to prevent\n this refresh.\n\n extmod_whitelist : None\n comma-seperated list of modules to sync\n\n extmod_blacklist : None\n comma-seperated list of modules to blacklist based on type\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' saltutil.sync_renderers\n salt '*' saltutil.sync_renderers saltenv=dev\n salt '*' saltutil.sync_renderers saltenv=base,dev\n '''\n ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)\n if refresh:\n refresh_modules()\n return ret\n",
"def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):\n '''\n .. versionadded:: 0.10.0\n\n Sync returners from ``salt://_returners`` to the minion\n\n saltenv\n The fileserver environment from which to sync. To sync from more than\n one environment, pass a comma-separated list.\n\n If not passed, then all environments configured in the :ref:`top files\n <states-top>` will be checked for returners to sync. If no top files\n are found, then the ``base`` environment will be synced.\n\n refresh : True\n If ``True``, refresh the available execution modules on the minion.\n This refresh will be performed even if no new returners are synced. Set\n to ``False`` to prevent this refresh.\n\n extmod_whitelist : None\n comma-seperated list of modules to sync\n\n extmod_blacklist : None\n comma-seperated list of modules to blacklist based on type\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' saltutil.sync_returners\n salt '*' saltutil.sync_returners saltenv=dev\n '''\n ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)\n if refresh:\n refresh_modules()\n return ret\n",
"def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):\n '''\n Sync outputters from ``salt://_output`` to the minion\n\n saltenv\n The fileserver environment from which to sync. To sync from more than\n one environment, pass a comma-separated list.\n\n If not passed, then all environments configured in the :ref:`top files\n <states-top>` will be checked for outputters to sync. If no top files\n are found, then the ``base`` environment will be synced.\n\n refresh : True\n If ``True``, refresh the available execution modules on the minion.\n This refresh will be performed even if no new outputters are synced.\n Set to ``False`` to prevent this refresh.\n\n extmod_whitelist : None\n comma-seperated list of modules to sync\n\n extmod_blacklist : None\n comma-seperated list of modules to blacklist based on type\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' saltutil.sync_output\n salt '*' saltutil.sync_output saltenv=dev\n salt '*' saltutil.sync_output saltenv=base,dev\n '''\n ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)\n if refresh:\n refresh_modules()\n return ret\n",
"def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):\n '''\n .. versionadded:: 2015.8.2\n\n Sync proxy modules from ``salt://_proxy`` to the minion\n\n saltenv\n The fileserver environment from which to sync. To sync from more than\n one environment, pass a comma-separated list.\n\n If not passed, then all environments configured in the :ref:`top files\n <states-top>` will be checked for proxy modules to sync. If no top\n files are found, then the ``base`` environment will be synced.\n\n refresh : True\n If ``True``, refresh the available execution modules on the minion.\n This refresh will be performed even if no new proxy modules are synced.\n Set to ``False`` to prevent this refresh.\n\n extmod_whitelist : None\n comma-seperated list of modules to sync\n\n extmod_blacklist : None\n comma-seperated list of modules to blacklist based on type\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' saltutil.sync_proxymodules\n salt '*' saltutil.sync_proxymodules saltenv=dev\n salt '*' saltutil.sync_proxymodules saltenv=base,dev\n '''\n ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)\n if refresh:\n refresh_modules()\n return ret\n",
"def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):\n '''\n .. versionadded:: 2016.3.0\n\n Sync engine modules from ``salt://_engines`` to the minion\n\n saltenv\n The fileserver environment from which to sync. To sync from more than\n one environment, pass a comma-separated list.\n\n If not passed, then all environments configured in the :ref:`top files\n <states-top>` will be checked for engines to sync. If no top files are\n found, then the ``base`` environment will be synced.\n\n refresh : True\n If ``True``, refresh the available execution modules on the minion.\n This refresh will be performed even if no new engine modules are synced.\n Set to ``False`` to prevent this refresh.\n\n extmod_whitelist : None\n comma-seperated list of modules to sync\n\n extmod_blacklist : None\n comma-seperated list of modules to blacklist based on type\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' saltutil.sync_engines\n salt '*' saltutil.sync_engines saltenv=base,dev\n '''\n ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)\n if refresh:\n refresh_modules()\n return ret\n",
"def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):\n '''\n .. versionadded:: 2018.3.0\n\n Sync Thorium modules from ``salt://_thorium`` to the minion\n\n saltenv\n The fileserver environment from which to sync. To sync from more than\n one environment, pass a comma-separated list.\n\n If not passed, then all environments configured in the :ref:`top files\n <states-top>` will be checked for engines to sync. If no top files are\n found, then the ``base`` environment will be synced.\n\n refresh: ``True``\n If ``True``, refresh the available execution modules on the minion.\n This refresh will be performed even if no new Thorium modules are synced.\n Set to ``False`` to prevent this refresh.\n\n extmod_whitelist\n comma-seperated list of modules to sync\n\n extmod_blacklist\n comma-seperated list of modules to blacklist based on type\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' saltutil.sync_thorium\n salt '*' saltutil.sync_thorium saltenv=base,dev\n '''\n ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)\n if refresh:\n refresh_modules()\n return ret\n",
"def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):\n '''\n .. versionadded:: 2015.8.11,2016.3.2\n\n Sync pillar modules from the ``salt://_pillar`` directory on the Salt\n fileserver. This function is environment-aware, pass the desired\n environment to grab the contents of the ``_pillar`` directory from that\n environment. The default environment, if none is specified, is ``base``.\n\n refresh : True\n Also refresh the execution modules available to the minion, and refresh\n pillar data.\n\n extmod_whitelist : None\n comma-seperated list of modules to sync\n\n extmod_blacklist : None\n comma-seperated list of modules to blacklist based on type\n\n .. note::\n This function will raise an error if executed on a traditional (i.e.\n not masterless) minion\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' saltutil.sync_pillar\n salt '*' saltutil.sync_pillar saltenv=dev\n '''\n if __opts__['file_client'] != 'local':\n raise CommandExecutionError(\n 'Pillar modules can only be synced to masterless minions'\n )\n ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)\n if refresh:\n refresh_modules()\n refresh_pillar()\n return ret\n",
"def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):\n '''\n .. versionadded:: 2014.7.0\n\n Sync utility modules from ``salt://_utils`` to the minion\n\n saltenv\n The fileserver environment from which to sync. To sync from more than\n one environment, pass a comma-separated list.\n\n If not passed, then all environments configured in the :ref:`top files\n <states-top>` will be checked for utility modules to sync. If no top\n files are found, then the ``base`` environment will be synced.\n\n refresh : True\n If ``True``, refresh the available execution modules on the minion.\n This refresh will be performed even if no new utility modules are\n synced. Set to ``False`` to prevent this refresh.\n\n extmod_whitelist : None\n comma-seperated list of modules to sync\n\n extmod_blacklist : None\n comma-seperated list of modules to blacklist based on type\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' saltutil.sync_utils\n salt '*' saltutil.sync_utils saltenv=dev\n salt '*' saltutil.sync_utils saltenv=base,dev\n '''\n ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)\n if refresh:\n refresh_modules()\n return ret\n",
"def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):\n '''\n .. versionadded:: 2015.5.8,2015.8.3\n\n Sync sdb modules from ``salt://_sdb`` to the minion\n\n saltenv\n The fileserver environment from which to sync. To sync from more than\n one environment, pass a comma-separated list.\n\n If not passed, then all environments configured in the :ref:`top files\n <states-top>` will be checked for sdb modules to sync. If no top files\n are found, then the ``base`` environment will be synced.\n\n refresh : False\n This argument has no affect and is included for consistency with the\n other sync functions.\n\n extmod_whitelist : None\n comma-seperated list of modules to sync\n\n extmod_blacklist : None\n comma-seperated list of modules to blacklist based on type\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' saltutil.sync_sdb\n salt '*' saltutil.sync_sdb saltenv=dev\n salt '*' saltutil.sync_sdb saltenv=base,dev\n '''\n ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)\n return ret\n",
"def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):\n '''\n .. versionadded:: 2019.2.0\n\n Sync serializers from ``salt://_serializers`` to the minion\n\n saltenv\n The fileserver environment from which to sync. To sync from more than\n one environment, pass a comma-separated list.\n\n If not passed, then all environments configured in the :ref:`top files\n <states-top>` will be checked for serializer modules to sync. If no top\n files are found, then the ``base`` environment will be synced.\n\n refresh : True\n If ``True``, refresh the available execution modules on the minion.\n This refresh will be performed even if no new serializer modules are\n synced. Set to ``False`` to prevent this refresh.\n\n extmod_whitelist : None\n comma-seperated list of modules to sync\n\n extmod_blacklist : None\n comma-seperated list of modules to blacklist based on type\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' saltutil.sync_serializers\n salt '*' saltutil.sync_serializers saltenv=dev\n salt '*' saltutil.sync_serializers saltenv=base,dev\n '''\n ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)\n if refresh:\n refresh_modules()\n return ret\n",
"def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):\n '''\n .. versionadded:: 2015.5.1\n\n Sync beacons from ``salt://_beacons`` to the minion\n\n saltenv\n The fileserver environment from which to sync. To sync from more than\n one environment, pass a comma-separated list.\n\n If not passed, then all environments configured in the :ref:`top files\n <states-top>` will be checked for beacons to sync. If no top files are\n found, then the ``base`` environment will be synced.\n\n refresh : True\n If ``True``, refresh the available beacons on the minion. This refresh\n will be performed even if no new beacons are synced. Set to ``False``\n to prevent this refresh.\n\n extmod_whitelist : None\n comma-seperated list of modules to sync\n\n extmod_blacklist : None\n comma-seperated list of modules to blacklist based on type\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' saltutil.sync_beacons\n salt '*' saltutil.sync_beacons saltenv=dev\n salt '*' saltutil.sync_beacons saltenv=base,dev\n '''\n ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)\n if refresh:\n refresh_beacons()\n return ret\n",
"def refresh_modules(**kwargs):\n '''\n Signal the minion to refresh the module and grain data\n\n The default is to refresh module asynchronously. To block\n until the module refresh is complete, set the 'async' flag\n to False.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' saltutil.refresh_modules\n '''\n asynchronous = bool(kwargs.get('async', True))\n try:\n if asynchronous:\n # If we're going to block, first setup a listener\n ret = __salt__['event.fire']({}, 'module_refresh')\n else:\n eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)\n ret = __salt__['event.fire']({'notify': True}, 'module_refresh')\n # Wait for the finish event to fire\n log.trace('refresh_modules waiting for module refresh to complete')\n # Blocks until we hear this event or until the timeout expires\n eventer.get_event(\n tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)\n except KeyError:\n log.error('Event module not available. Module refresh failed.')\n ret = False # Effectively a no-op, since we can't really return without an event system\n return ret\n",
"def refresh_pillar(**kwargs):\n '''\n Signal the minion to refresh the pillar data.\n\n .. versionchanged:: Neon\n The ``async`` argument has been added. The default value is True.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' saltutil.refresh_pillar\n salt '*' saltutil.refresh_pillar async=False\n '''\n asynchronous = bool(kwargs.get('async', True))\n try:\n if asynchronous:\n # If we're going to block, first setup a listener\n ret = __salt__['event.fire']({}, 'pillar_refresh')\n else:\n eventer = salt.utils.event.get_event(\n 'minion', opts=__opts__, listen=True)\n ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')\n # Wait for the finish event to fire\n log.trace('refresh_pillar waiting for pillar refresh to complete')\n # Blocks until we hear this event or until the timeout expires\n eventer.get_event(\n tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)\n except KeyError:\n log.error('Event module not available. Pillar refresh failed.')\n ret = False # Effectively a no-op, since we can't really return without an event system\n return ret\n",
"def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):\n '''\n .. versionadded:: 2019.2.0\n\n Sync engine modules from ``salt://_matchers`` to the minion\n\n saltenv\n The fileserver environment from which to sync. To sync from more than\n one environment, pass a comma-separated list.\n\n If not passed, then all environments configured in the :ref:`top files\n <states-top>` will be checked for engines to sync. If no top files are\n found, then the ``base`` environment will be synced.\n\n refresh : True\n If ``True``, refresh the available execution modules on the minion.\n This refresh will be performed even if no new matcher modules are synced.\n Set to ``False`` to prevent this refresh.\n\n extmod_whitelist : None\n comma-separated list of modules to sync\n\n extmod_blacklist : None\n comma-separated list of modules to blacklist based on type\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' saltutil.sync_matchers\n salt '*' saltutil.sync_matchers saltenv=base,dev\n '''\n ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)\n if refresh:\n refresh_modules()\n return ret\n",
"def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):\n '''\n .. versionadded:: Neon\n\n Sync executors from ``salt://_executors`` to the minion\n\n saltenv\n The fileserver environment from which to sync. To sync from more than\n one environment, pass a comma-separated list.\n\n If not passed, then all environments configured in the :ref:`top files\n <states-top>` will be checked for executor modules to sync. If no top\n files are found, then the ``base`` environment will be synced.\n\n refresh : True\n If ``True``, refresh the available execution modules on the minion.\n This refresh will be performed even if no new serializer modules are\n synced. Set to ``False`` to prevent this refresh.\n\n extmod_whitelist : None\n comma-seperated list of modules to sync\n\n extmod_blacklist : None\n comma-seperated list of modules to blacklist based on type\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' saltutil.sync_executors\n salt '*' saltutil.sync_executors saltenv=dev\n salt '*' saltutil.sync_executors saltenv=base,dev\n '''\n ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)\n if refresh:\n refresh_modules()\n return ret\n",
"def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):\n '''\n .. versionadded:: 2015.8.0\n\n Sync log handlers from ``salt://_log_handlers`` to the minion\n\n saltenv\n The fileserver environment from which to sync. To sync from more than\n one environment, pass a comma-separated list.\n\n If not passed, then all environments configured in the :ref:`top files\n <states-top>` will be checked for log handlers to sync. If no top files\n are found, then the ``base`` environment will be synced.\n\n refresh : True\n If ``True``, refresh the available execution modules on the minion.\n This refresh will be performed even if no new log handlers are synced.\n Set to ``False`` to prevent this refresh.\n\n extmod_whitelist : None\n comma-seperated list of modules to sync\n\n extmod_blacklist : None\n comma-seperated list of modules to blacklist based on type\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' saltutil.sync_log_handlers\n salt '*' saltutil.sync_log_handlers saltenv=dev\n salt '*' saltutil.sync_log_handlers saltenv=base,dev\n '''\n ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)\n if refresh:\n refresh_modules()\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
refresh_pillar
|
python
|
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
|
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1073-L1104
|
[
"def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n",
"def get_event(self,\n wait=5,\n tag='',\n full=False,\n match_type=None,\n no_block=False,\n auto_reconnect=False):\n '''\n Get a single publication.\n If no publication is available, then block for up to ``wait`` seconds.\n Return publication if it is available or ``None`` if no publication is\n available.\n\n If wait is 0, then block forever.\n\n tag\n Only return events matching the given tag. If not specified, or set\n to an empty string, all events are returned. It is recommended to\n always be selective on what is to be returned in the event that\n multiple requests are being multiplexed.\n\n match_type\n Set the function to match the search tag with event tags.\n - 'startswith' : search for event tags that start with tag\n - 'endswith' : search for event tags that end with tag\n - 'find' : search for event tags that contain tag\n - 'regex' : regex search '^' + tag event tags\n - 'fnmatch' : fnmatch tag event tags matching\n Default is opts['event_match_type'] or 'startswith'\n\n .. versionadded:: 2015.8.0\n\n no_block\n Define if getting the event should be a blocking call or not.\n Defaults to False to keep backwards compatibility.\n\n .. versionadded:: 2015.8.0\n\n Notes:\n\n Searches cached publications first. If no cached publications are found\n that match the given tag specification, new publications are received\n and checked.\n\n If a publication is received that does not match the tag specification,\n it is DISCARDED unless it is subscribed to via subscribe() which will\n cause it to be cached.\n\n If a caller is not going to call get_event immediately after sending a\n request, it MUST subscribe the result to ensure the response is not lost\n should other regions of code call get_event for other purposes.\n '''\n assert self._run_io_loop_sync\n\n match_func = self._get_match_func(match_type)\n\n ret = self._check_pending(tag, match_func)\n if ret is None:\n with salt.utils.asynchronous.current_ioloop(self.io_loop):\n if auto_reconnect:\n raise_errors = self.raise_errors\n self.raise_errors = True\n while True:\n try:\n ret = self._get_event(wait, tag, match_func, no_block)\n break\n except tornado.iostream.StreamClosedError:\n self.close_pub()\n self.connect_pub(timeout=wait)\n continue\n self.raise_errors = raise_errors\n else:\n ret = self._get_event(wait, tag, match_func, no_block)\n\n if ret is None or full:\n return ret\n else:\n return ret['data']\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
is_running
|
python
|
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
|
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1143-L1159
|
[
"def running():\n '''\n Return the data on all running salt processes on the minion\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' saltutil.running\n '''\n return salt.utils.minion.running(__opts__)\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
clear_cache
|
python
|
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
|
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1175-L1204
|
[
"def safe_walk(top, topdown=True, onerror=None, followlinks=True, _seen=None):\n '''\n A clone of the python os.walk function with some checks for recursive\n symlinks. Unlike os.walk this follows symlinks by default.\n '''\n if _seen is None:\n _seen = set()\n\n # We may not have read permission for top, in which case we can't\n # get a list of the files the directory contains. os.path.walk\n # always suppressed the exception then, rather than blow up for a\n # minor reason when (say) a thousand readable directories are still\n # left to visit. That logic is copied here.\n try:\n # Note that listdir and error are globals in this module due\n # to earlier import-*.\n names = os.listdir(top)\n except os.error as err:\n if onerror is not None:\n onerror(err)\n return\n\n if followlinks:\n status = os.stat(top)\n # st_ino is always 0 on some filesystems (FAT, NTFS); ignore them\n if status.st_ino != 0:\n node = (status.st_dev, status.st_ino)\n if node in _seen:\n return\n _seen.add(node)\n\n dirs, nondirs = [], []\n for name in names:\n full_path = os.path.join(top, name)\n if os.path.isdir(full_path):\n dirs.append(name)\n else:\n nondirs.append(name)\n\n if topdown:\n yield top, dirs, nondirs\n for name in dirs:\n new_path = os.path.join(top, name)\n if followlinks or not os.path.islink(new_path):\n for x in safe_walk(new_path, topdown, onerror, followlinks, _seen):\n yield x\n if not topdown:\n yield top, dirs, nondirs\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
clear_job_cache
|
python
|
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
|
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1207-L1234
|
[
"def safe_walk(top, topdown=True, onerror=None, followlinks=True, _seen=None):\n '''\n A clone of the python os.walk function with some checks for recursive\n symlinks. Unlike os.walk this follows symlinks by default.\n '''\n if _seen is None:\n _seen = set()\n\n # We may not have read permission for top, in which case we can't\n # get a list of the files the directory contains. os.path.walk\n # always suppressed the exception then, rather than blow up for a\n # minor reason when (say) a thousand readable directories are still\n # left to visit. That logic is copied here.\n try:\n # Note that listdir and error are globals in this module due\n # to earlier import-*.\n names = os.listdir(top)\n except os.error as err:\n if onerror is not None:\n onerror(err)\n return\n\n if followlinks:\n status = os.stat(top)\n # st_ino is always 0 on some filesystems (FAT, NTFS); ignore them\n if status.st_ino != 0:\n node = (status.st_dev, status.st_ino)\n if node in _seen:\n return\n _seen.add(node)\n\n dirs, nondirs = [], []\n for name in names:\n full_path = os.path.join(top, name)\n if os.path.isdir(full_path):\n dirs.append(name)\n else:\n nondirs.append(name)\n\n if topdown:\n yield top, dirs, nondirs\n for name in dirs:\n new_path = os.path.join(top, name)\n if followlinks or not os.path.islink(new_path):\n for x in safe_walk(new_path, topdown, onerror, followlinks, _seen):\n yield x\n if not topdown:\n yield top, dirs, nondirs\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
find_cached_job
|
python
|
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
|
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1289-L1322
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
signal_job
|
python
|
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
|
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1325-L1360
|
[
"def running():\n '''\n Return the data on all running salt processes on the minion\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' saltutil.running\n '''\n return salt.utils.minion.running(__opts__)\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
term_all_jobs
|
python
|
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
|
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1376-L1389
|
[
"def running():\n '''\n Return the data on all running salt processes on the minion\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' saltutil.running\n '''\n return salt.utils.minion.running(__opts__)\n",
"def signal_job(jid, sig):\n '''\n Sends a signal to the named salt job's process\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' saltutil.signal_job <job id> 15\n '''\n if HAS_PSUTIL is False:\n log.warning('saltutil.signal job called, but psutil is not installed. '\n 'Install psutil to ensure more reliable and accurate PID '\n 'management.')\n for data in running():\n if data['jid'] == jid:\n try:\n if HAS_PSUTIL:\n for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):\n proc.send_signal(sig)\n os.kill(int(data['pid']), sig)\n if HAS_PSUTIL is False and 'child_pids' in data:\n for pid in data['child_pids']:\n os.kill(int(pid), sig)\n return 'Signal {0} sent to job {1} at pid {2}'.format(\n int(sig),\n jid,\n data['pid']\n )\n except OSError:\n path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))\n if os.path.isfile(path):\n os.remove(path)\n return ('Job {0} was not running and job data has been '\n ' cleaned up').format(jid)\n return ''\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
kill_all_jobs
|
python
|
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
|
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1407-L1422
|
[
"def running():\n '''\n Return the data on all running salt processes on the minion\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' saltutil.running\n '''\n return salt.utils.minion.running(__opts__)\n",
"def signal_job(jid, sig):\n '''\n Sends a signal to the named salt job's process\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' saltutil.signal_job <job id> 15\n '''\n if HAS_PSUTIL is False:\n log.warning('saltutil.signal job called, but psutil is not installed. '\n 'Install psutil to ensure more reliable and accurate PID '\n 'management.')\n for data in running():\n if data['jid'] == jid:\n try:\n if HAS_PSUTIL:\n for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):\n proc.send_signal(sig)\n os.kill(int(data['pid']), sig)\n if HAS_PSUTIL is False and 'child_pids' in data:\n for pid in data['child_pids']:\n os.kill(int(pid), sig)\n return 'Signal {0} sent to job {1} at pid {2}'.format(\n int(sig),\n jid,\n data['pid']\n )\n except OSError:\n path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))\n if os.path.isfile(path):\n os.remove(path)\n return ('Job {0} was not running and job data has been '\n ' cleaned up').format(jid)\n return ''\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
regen_keys
|
python
|
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
|
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1425-L1444
|
[
"def factory(opts, **kwargs):\n # All Sync interfaces are just wrappers around the Async ones\n sync = SyncWrapper(AsyncReqChannel.factory, (opts,), kwargs)\n return sync\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
revoke_auth
|
python
|
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
|
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1447-L1483
|
[
"def factory(opts, **kwargs):\n # All Sync interfaces are just wrappers around the Async ones\n sync = SyncWrapper(AsyncReqChannel.factory, (opts,), kwargs)\n return sync\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
cmd
|
python
|
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
|
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1537-L1584
|
[
"def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):\n fcn_ret = {}\n seen = 0\n if 'batch' in kwargs:\n _cmd = client.cmd_batch\n cmd_kwargs = {\n 'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,\n 'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],\n }\n del kwargs['batch']\n elif 'subset' in kwargs:\n _cmd = client.cmd_subset\n cmd_kwargs = {\n 'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,\n 'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],\n }\n del kwargs['subset']\n elif kwargs.get('asynchronous'):\n cmd_kwargs = {\n 'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,\n 'ret': ret, 'kwarg': kwarg\n }\n del kwargs['asynchronous']\n # run_job doesnt need processing like the others\n return client.run_job(**cmd_kwargs)\n else:\n _cmd = client.cmd_iter\n cmd_kwargs = {\n 'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,\n 'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,\n }\n cmd_kwargs.update(kwargs)\n for ret_comp in _cmd(**cmd_kwargs):\n fcn_ret.update(ret_comp)\n seen += 1\n # fcn_ret can be empty, so we cannot len the whole return dict\n if tgt_type == 'list' and len(tgt) == seen:\n # do not wait for timeout when explicit list matching\n # and all results are there\n break\n return fcn_ret\n",
"def _get_ssh_or_api_client(cfgfile, ssh=False):\n if ssh:\n client = salt.client.ssh.client.SSHClient(cfgfile)\n else:\n client = salt.client.get_local_client(cfgfile)\n return client\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
cmd_iter
|
python
|
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
|
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1587-L1622
|
[
"def get_local_client(\n c_path=os.path.join(syspaths.CONFIG_DIR, 'master'),\n mopts=None,\n skip_perm_errors=False,\n io_loop=None,\n auto_reconnect=False):\n '''\n .. versionadded:: 2014.7.0\n\n Read in the config and return the correct LocalClient object based on\n the configured transport\n\n :param IOLoop io_loop: io_loop used for events.\n Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n if mopts:\n opts = mopts\n else:\n # Late import to prevent circular import\n import salt.config\n opts = salt.config.client_config(c_path)\n\n # TODO: AIO core is separate from transport\n return LocalClient(\n mopts=opts,\n skip_perm_errors=skip_perm_errors,\n io_loop=io_loop,\n auto_reconnect=auto_reconnect)\n",
"def cmd_iter(\n self,\n tgt,\n fun,\n arg=(),\n timeout=None,\n tgt_type='glob',\n ret='',\n kwarg=None,\n **kwargs):\n '''\n Yields the individual minion returns as they come in\n\n The function signature is the same as :py:meth:`cmd` with the\n following exceptions.\n\n Normally :py:meth:`cmd_iter` does not yield results for minions that\n are not connected. If you want it to return results for disconnected\n minions set `expect_minions=True` in `kwargs`.\n\n :return: A generator yielding the individual minion returns\n\n .. code-block:: python\n\n >>> ret = local.cmd_iter('*', 'test.ping')\n >>> for i in ret:\n ... print(i)\n {'jerry': {'ret': True}}\n {'dave': {'ret': True}}\n {'stewart': {'ret': True}}\n '''\n was_listening = self.event.cpub\n\n try:\n pub_data = self.run_job(\n tgt,\n fun,\n arg,\n tgt_type,\n ret,\n timeout,\n kwarg=kwarg,\n listen=True,\n **kwargs)\n\n if not pub_data:\n yield pub_data\n else:\n if kwargs.get('yield_pub_data'):\n yield pub_data\n for fn_ret in self.get_iter_returns(pub_data['jid'],\n pub_data['minions'],\n timeout=self._get_timeout(timeout),\n tgt=tgt,\n tgt_type=tgt_type,\n **kwargs):\n if not fn_ret:\n continue\n yield fn_ret\n self._clean_up_subscriptions(pub_data['jid'])\n finally:\n if not was_listening:\n self.event.close_pub()\n",
"def cmd_iter(\n self,\n tgt,\n fun,\n arg=(),\n timeout=None,\n tgt_type='glob',\n ret='',\n kwarg=None,\n **kwargs):\n '''\n Execute a single command via the salt-ssh subsystem and return a\n generator\n\n .. versionadded:: 2015.5.0\n '''\n ssh = self._prep_ssh(\n tgt,\n fun,\n arg,\n timeout,\n tgt_type,\n kwarg,\n **kwargs)\n for ret in ssh.run_iter(jid=kwargs.get('jid', None)):\n yield ret\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
runner
|
python
|
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
|
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1625-L1697
|
[
"def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False):\n '''\n Reads in the master configuration file and sets up default options\n\n This is useful for running the actual master daemon. For running\n Master-side client interfaces that need the master opts see\n :py:func:`salt.client.client_config`.\n '''\n if defaults is None:\n defaults = DEFAULT_MASTER_OPTS.copy()\n\n if not os.environ.get(env_var, None):\n # No valid setting was given using the configuration variable.\n # Lets see is SALT_CONFIG_DIR is of any use\n salt_config_dir = os.environ.get('SALT_CONFIG_DIR', None)\n if salt_config_dir:\n env_config_file_path = os.path.join(salt_config_dir, 'master')\n if salt_config_dir and os.path.isfile(env_config_file_path):\n # We can get a configuration file using SALT_CONFIG_DIR, let's\n # update the environment with this information\n os.environ[env_var] = env_config_file_path\n\n overrides = load_config(path, env_var, DEFAULT_MASTER_OPTS['conf_file'])\n default_include = overrides.get('default_include',\n defaults['default_include'])\n include = overrides.get('include', [])\n\n overrides.update(include_config(default_include, path, verbose=False,\n exit_on_config_errors=exit_on_config_errors))\n overrides.update(include_config(include, path, verbose=True,\n exit_on_config_errors=exit_on_config_errors))\n opts = apply_master_config(overrides, defaults)\n _validate_ssh_minion_opts(opts)\n _validate_opts(opts)\n # If 'nodegroups:' is uncommented in the master config file, and there are\n # no nodegroups defined, opts['nodegroups'] will be None. Fix this by\n # reverting this value to the default, as if 'nodegroups:' was commented\n # out or not present.\n if opts.get('nodegroups') is None:\n opts['nodegroups'] = DEFAULT_MASTER_OPTS.get('nodegroups', {})\n if salt.utils.data.is_dictlist(opts['nodegroups']):\n opts['nodegroups'] = salt.utils.data.repack_dictlist(opts['nodegroups'])\n apply_sdb(opts)\n return opts\n",
"def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n",
"def get_function_argspec(func, is_class_method=None):\n '''\n A small wrapper around getargspec that also supports callable classes\n :param is_class_method: Pass True if you are sure that the function being passed\n is a class method. The reason for this is that on Python 3\n ``inspect.ismethod`` only returns ``True`` for bound methods,\n while on Python 2, it returns ``True`` for bound and unbound\n methods. So, on Python 3, in case of a class method, you'd\n need the class to which the function belongs to be instantiated\n and this is not always wanted.\n '''\n if not callable(func):\n raise TypeError('{0} is not a callable'.format(func))\n\n if six.PY2:\n if is_class_method is True:\n aspec = inspect.getargspec(func)\n del aspec.args[0] # self\n elif inspect.isfunction(func):\n aspec = inspect.getargspec(func)\n elif inspect.ismethod(func):\n aspec = inspect.getargspec(func)\n del aspec.args[0] # self\n elif isinstance(func, object):\n aspec = inspect.getargspec(func.__call__)\n del aspec.args[0] # self\n else:\n raise TypeError(\n 'Cannot inspect argument list for \\'{0}\\''.format(func)\n )\n else:\n if is_class_method is True:\n aspec = _getargspec(func)\n del aspec.args[0] # self\n elif inspect.isfunction(func):\n aspec = _getargspec(func) # pylint: disable=redefined-variable-type\n elif inspect.ismethod(func):\n aspec = _getargspec(func)\n del aspec.args[0] # self\n elif isinstance(func, object):\n aspec = _getargspec(func.__call__)\n del aspec.args[0] # self\n else:\n raise TypeError(\n 'Cannot inspect argument list for \\'{0}\\''.format(func)\n )\n return aspec\n",
"def fire_args(opts, jid, tag_data, prefix=''):\n '''\n Fire an event containing the arguments passed to an orchestration job\n '''\n try:\n tag_suffix = [jid, 'args']\n except NameError:\n pass\n else:\n tag = tagify(tag_suffix, prefix)\n try:\n _event = get_master_event(opts, opts['sock_dir'], listen=False)\n _event.fire_event(tag_data, tag=tag)\n except Exception as exc:\n # Don't let a problem here hold up the rest of the orchestration\n log.warning(\n 'Failed to fire args event %s with data %s: %s',\n tag, tag_data, exc\n )\n",
"def get_master_key(key_user, opts, skip_perm_errors=False):\n if key_user == 'root':\n if opts.get('user', 'root') != 'root':\n key_user = opts.get('user', 'root')\n if key_user.startswith('sudo_'):\n key_user = opts.get('user', 'root')\n if salt.utils.platform.is_windows():\n # The username may contain '\\' if it is in Windows\n # 'DOMAIN\\username' format. Fix this for the keyfile path.\n key_user = key_user.replace('\\\\', '_')\n keyfile = os.path.join(opts['cachedir'],\n '.{0}_key'.format(key_user))\n # Make sure all key parent directories are accessible\n salt.utils.verify.check_path_traversal(opts['cachedir'],\n key_user,\n skip_perm_errors)\n\n try:\n with salt.utils.files.fopen(keyfile, 'r') as key:\n return key.read()\n except (OSError, IOError):\n # Fall back to eauth\n return ''\n",
"def cmd_async(self, low):\n '''\n Execute a runner function asynchronously; eauth is respected\n\n This function requires that :conf_master:`external_auth` is configured\n and the user is authorized to execute runner functions: (``@runner``).\n\n .. code-block:: python\n\n runner.eauth_async({\n 'fun': 'jobs.list_jobs',\n 'username': 'saltdev',\n 'password': 'saltdev',\n 'eauth': 'pam',\n })\n '''\n reformatted_low = self._reformat_low(low)\n\n return mixins.AsyncClientMixin.cmd_async(self, reformatted_low)\n",
"def cmd(self, fun, arg=None, pub_data=None, kwarg=None, print_event=True, full_return=False):\n '''\n Execute a function\n '''\n return super(RunnerClient, self).cmd(fun,\n arg,\n pub_data,\n kwarg,\n print_event,\n full_return)\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
wheel
|
python
|
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
|
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1700-L1794
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def get_function_argspec(func, is_class_method=None):\n '''\n A small wrapper around getargspec that also supports callable classes\n :param is_class_method: Pass True if you are sure that the function being passed\n is a class method. The reason for this is that on Python 3\n ``inspect.ismethod`` only returns ``True`` for bound methods,\n while on Python 2, it returns ``True`` for bound and unbound\n methods. So, on Python 3, in case of a class method, you'd\n need the class to which the function belongs to be instantiated\n and this is not always wanted.\n '''\n if not callable(func):\n raise TypeError('{0} is not a callable'.format(func))\n\n if six.PY2:\n if is_class_method is True:\n aspec = inspect.getargspec(func)\n del aspec.args[0] # self\n elif inspect.isfunction(func):\n aspec = inspect.getargspec(func)\n elif inspect.ismethod(func):\n aspec = inspect.getargspec(func)\n del aspec.args[0] # self\n elif isinstance(func, object):\n aspec = inspect.getargspec(func.__call__)\n del aspec.args[0] # self\n else:\n raise TypeError(\n 'Cannot inspect argument list for \\'{0}\\''.format(func)\n )\n else:\n if is_class_method is True:\n aspec = _getargspec(func)\n del aspec.args[0] # self\n elif inspect.isfunction(func):\n aspec = _getargspec(func) # pylint: disable=redefined-variable-type\n elif inspect.ismethod(func):\n aspec = _getargspec(func)\n del aspec.args[0] # self\n elif isinstance(func, object):\n aspec = _getargspec(func.__call__)\n del aspec.args[0] # self\n else:\n raise TypeError(\n 'Cannot inspect argument list for \\'{0}\\''.format(func)\n )\n return aspec\n",
"def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None):\n '''\n Load Master configuration data\n\n Usage:\n\n .. code-block:: python\n\n import salt.config\n master_opts = salt.config.client_config('/etc/salt/master')\n\n Returns a dictionary of the Salt Master configuration file with necessary\n options needed to communicate with a locally-running Salt Master daemon.\n This function searches for client specific configurations and adds them to\n the data from the master configuration.\n\n This is useful for master-side operations like\n :py:class:`~salt.client.LocalClient`.\n '''\n if defaults is None:\n defaults = DEFAULT_MASTER_OPTS.copy()\n\n xdg_dir = salt.utils.xdg.xdg_config_dir()\n if os.path.isdir(xdg_dir):\n client_config_dir = xdg_dir\n saltrc_config_file = 'saltrc'\n else:\n client_config_dir = os.path.expanduser('~')\n saltrc_config_file = '.saltrc'\n\n # Get the token file path from the provided defaults. If not found, specify\n # our own, sane, default\n opts = {\n 'token_file': defaults.get(\n 'token_file',\n os.path.join(client_config_dir, 'salt_token')\n )\n }\n # Update options with the master configuration, either from the provided\n # path, salt's defaults or provided defaults\n opts.update(\n master_config(path, defaults=defaults)\n )\n # Update with the users salt dot file or with the environment variable\n saltrc_config = os.path.join(client_config_dir, saltrc_config_file)\n opts.update(\n load_config(\n saltrc_config,\n env_var,\n saltrc_config\n )\n )\n # Make sure we have a proper and absolute path to the token file\n if 'token_file' in opts:\n opts['token_file'] = os.path.abspath(\n os.path.expanduser(\n opts['token_file']\n )\n )\n # If the token file exists, read and store the contained token\n if os.path.isfile(opts['token_file']):\n # Make sure token is still valid\n expire = opts.get('token_expire', 43200)\n if os.stat(opts['token_file']).st_mtime + expire > time.mktime(time.localtime()):\n with salt.utils.files.fopen(opts['token_file']) as fp_:\n opts['token'] = fp_.read().strip()\n # On some platforms, like OpenBSD, 0.0.0.0 won't catch a master running on localhost\n if opts['interface'] == '0.0.0.0':\n opts['interface'] = '127.0.0.1'\n\n # Make sure the master_uri is set\n if 'master_uri' not in opts:\n opts['master_uri'] = 'tcp://{ip}:{port}'.format(\n ip=salt.utils.zeromq.ip_bracket(opts['interface']),\n port=opts['ret_port']\n )\n\n # Return the client options\n _validate_opts(opts)\n return opts\n",
"def fire_args(opts, jid, tag_data, prefix=''):\n '''\n Fire an event containing the arguments passed to an orchestration job\n '''\n try:\n tag_suffix = [jid, 'args']\n except NameError:\n pass\n else:\n tag = tagify(tag_suffix, prefix)\n try:\n _event = get_master_event(opts, opts['sock_dir'], listen=False)\n _event.fire_event(tag_data, tag=tag)\n except Exception as exc:\n # Don't let a problem here hold up the rest of the orchestration\n log.warning(\n 'Failed to fire args event %s with data %s: %s',\n tag, tag_data, exc\n )\n",
"def get_master_key(key_user, opts, skip_perm_errors=False):\n if key_user == 'root':\n if opts.get('user', 'root') != 'root':\n key_user = opts.get('user', 'root')\n if key_user.startswith('sudo_'):\n key_user = opts.get('user', 'root')\n if salt.utils.platform.is_windows():\n # The username may contain '\\' if it is in Windows\n # 'DOMAIN\\username' format. Fix this for the keyfile path.\n key_user = key_user.replace('\\\\', '_')\n keyfile = os.path.join(opts['cachedir'],\n '.{0}_key'.format(key_user))\n # Make sure all key parent directories are accessible\n salt.utils.verify.check_path_traversal(opts['cachedir'],\n key_user,\n skip_perm_errors)\n\n try:\n with salt.utils.files.fopen(keyfile, 'r') as key:\n return key.read()\n except (OSError, IOError):\n # Fall back to eauth\n return ''\n",
"def cmd_async(self, low):\n '''\n Execute a function asynchronously; eauth is respected\n\n This function requires that :conf_master:`external_auth` is configured\n and the user is authorized\n\n .. code-block:: python\n\n >>> wheel.cmd_async({\n 'fun': 'key.finger',\n 'match': 'jerry',\n 'eauth': 'auto',\n 'username': 'saltdev',\n 'password': 'saltdev',\n })\n {'jid': '20131219224744416681', 'tag': 'salt/wheel/20131219224744416681'}\n '''\n fun = low.pop('fun')\n return self.asynchronous(fun, low)\n",
"def cmd(self, fun, arg=None, pub_data=None, kwarg=None, print_event=True, full_return=False):\n '''\n Execute a function\n\n .. code-block:: python\n\n >>> wheel.cmd('key.finger', ['jerry'])\n {'minions': {'jerry': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}}\n '''\n return super(WheelClient, self).cmd(fun,\n arg,\n pub_data,\n kwarg,\n print_event,\n full_return)\n"
] |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
saltstack/salt
|
salt/modules/saltutil.py
|
mmodule
|
python
|
def mmodule(saltenv, fun, *args, **kwargs):
'''
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
'''
mminion = _MMinion(saltenv)
return mminion.functions[fun](*args, **kwargs)
|
Loads minion modules from an environment so that they can be used in pillars
for that environment
CLI Example:
.. code-block:: bash
salt '*' saltutil.mmodule base test.ping
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1830-L1842
| null |
# -*- coding: utf-8 -*-
'''
The Saltutil module is used to manage the state of the salt minion itself. It
is used to manage minion modules as well as automate updates to the salt
minion.
:depends: - esky Python module for update functionality
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import fnmatch
import logging
import os
import signal
import sys
import time
import shutil
# Import 3rd-party libs
# pylint: disable=import-error
try:
import esky
from esky import EskyVersionError
HAS_ESKY = True
except ImportError:
HAS_ESKY = False
# pylint: disable=no-name-in-module
from salt.ext import six
from salt.ext.six.moves.urllib.error import URLError
# pylint: enable=import-error,no-name-in-module
# Fix a nasty bug with Win32 Python not supporting all of the standard signals
try:
salt_SIGKILL = signal.SIGKILL
except AttributeError:
salt_SIGKILL = signal.SIGTERM
# Import salt libs
import salt
import salt.config
import salt.client
import salt.client.ssh.client
import salt.defaults.events
import salt.payload
import salt.runner
import salt.state
import salt.utils.args
import salt.utils.event
import salt.utils.extmods
import salt.utils.files
import salt.utils.functools
import salt.utils.master
import salt.utils.minion
import salt.utils.path
import salt.utils.process
import salt.utils.url
import salt.wheel
import salt.transport.client
HAS_PSUTIL = True
try:
import salt.utils.psutil_compat
except ImportError:
HAS_PSUTIL = False
from salt.exceptions import (
SaltReqTimeoutError, SaltRenderError, CommandExecutionError, SaltInvocationError
)
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs
def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret
def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret
def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret
def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret
def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_states(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync state modules from ``salt://_states`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for state modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available states on the minion. This refresh
will be performed even if no new state modules are synced. Set to
``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_states
salt '*' saltutil.sync_states saltenv=dev
salt '*' saltutil.sync_states saltenv=base,dev
'''
ret = _sync('states', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True
def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_renderers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync renderers from ``salt://_renderers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for renderers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new renderers are synced.
Set to ``False`` to prevent this refresh. Set to ``False`` to prevent
this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_renderers
salt '*' saltutil.sync_renderers saltenv=dev
salt '*' saltutil.sync_renderers saltenv=base,dev
'''
ret = _sync('renderers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_returners(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync returners from ``salt://_returners`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for returners to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new returners are synced. Set
to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_returners
salt '*' saltutil.sync_returners saltenv=dev
'''
ret = _sync('returners', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_proxymodules(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.2
Sync proxy modules from ``salt://_proxy`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for proxy modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new proxy modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_proxymodules
salt '*' saltutil.sync_proxymodules saltenv=dev
salt '*' saltutil.sync_proxymodules saltenv=base,dev
'''
ret = _sync('proxy', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_engines(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2016.3.0
Sync engine modules from ``salt://_engines`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new engine modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_engines
salt '*' saltutil.sync_engines saltenv=base,dev
'''
ret = _sync('engines', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_thorium(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2018.3.0
Sync Thorium modules from ``salt://_thorium`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh: ``True``
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new Thorium modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist
comma-seperated list of modules to sync
extmod_blacklist
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_thorium
salt '*' saltutil.sync_thorium saltenv=base,dev
'''
ret = _sync('thorium', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_output(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync outputters from ``salt://_output`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for outputters to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new outputters are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_output
salt '*' saltutil.sync_output saltenv=dev
salt '*' saltutil.sync_output saltenv=base,dev
'''
ret = _sync('output', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
sync_outputters = salt.utils.functools.alias_function(sync_output, 'sync_outputters')
def sync_clouds(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2017.7.0
Sync cloud modules from ``salt://_cloud`` to the minion
saltenv : base
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_clouds
salt '*' saltutil.sync_clouds saltenv=dev
salt '*' saltutil.sync_clouds saltenv=base,dev
'''
ret = _sync('clouds', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_utils(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2014.7.0
Sync utility modules from ``salt://_utils`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for utility modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new utility modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_utils
salt '*' saltutil.sync_utils saltenv=dev
salt '*' saltutil.sync_utils saltenv=base,dev
'''
ret = _sync('utils', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_serializers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync serializers from ``salt://_serializers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for serializer modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_serializers
salt '*' saltutil.sync_serializers saltenv=dev
salt '*' saltutil.sync_serializers saltenv=base,dev
'''
ret = _sync('serializers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_executors(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: Neon
Sync executors from ``salt://_executors`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for executor modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new serializer modules are
synced. Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_executors
salt '*' saltutil.sync_executors saltenv=dev
salt '*' saltutil.sync_executors saltenv=base,dev
'''
ret = _sync('executors', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret
def sync_log_handlers(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.0
Sync log handlers from ``salt://_log_handlers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for log handlers to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new log handlers are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_log_handlers
salt '*' saltutil.sync_log_handlers saltenv=dev
salt '*' saltutil.sync_log_handlers saltenv=base,dev
'''
ret = _sync('log_handlers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret
def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret
def refresh_beacons():
'''
Signal the minion to refresh the beacons.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_beacons
'''
try:
ret = __salt__['event.fire']({}, 'beacons_refresh')
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_matchers():
'''
Signal the minion to refresh its matchers.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_matchers
'''
try:
ret = __salt__['event.fire']({}, 'matchers_refresh')
except KeyError:
log.error('Event module not available. Matcher refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def refresh_pillar(**kwargs):
'''
Signal the minion to refresh the pillar data.
.. versionchanged:: Neon
The ``async`` argument has been added. The default value is True.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar async=False
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'pillar_refresh')
else:
eventer = salt.utils.event.get_event(
'minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'pillar_refresh')
# Wait for the finish event to fire
log.trace('refresh_pillar waiting for pillar refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_PILLAR_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Pillar refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
pillar_refresh = salt.utils.functools.alias_function(refresh_pillar, 'pillar_refresh')
def refresh_modules(**kwargs):
'''
Signal the minion to refresh the module and grain data
The default is to refresh module asynchronously. To block
until the module refresh is complete, set the 'async' flag
to False.
CLI Example:
.. code-block:: bash
salt '*' saltutil.refresh_modules
'''
asynchronous = bool(kwargs.get('async', True))
try:
if asynchronous:
# If we're going to block, first setup a listener
ret = __salt__['event.fire']({}, 'module_refresh')
else:
eventer = salt.utils.event.get_event('minion', opts=__opts__, listen=True)
ret = __salt__['event.fire']({'notify': True}, 'module_refresh')
# Wait for the finish event to fire
log.trace('refresh_modules waiting for module refresh to complete')
# Blocks until we hear this event or until the timeout expires
eventer.get_event(
tag=salt.defaults.events.MINION_MOD_COMPLETE, wait=30)
except KeyError:
log.error('Event module not available. Module refresh failed.')
ret = False # Effectively a no-op, since we can't really return without an event system
return ret
def is_running(fun):
'''
If the named function is running return the data associated with it/them.
The argument can be a glob
CLI Example:
.. code-block:: bash
salt '*' saltutil.is_running state.highstate
'''
run = running()
ret = []
for data in run:
if fnmatch.fnmatch(data.get('fun', ''), fun):
ret.append(data)
return ret
def running():
'''
Return the data on all running salt processes on the minion
CLI Example:
.. code-block:: bash
salt '*' saltutil.running
'''
return salt.utils.minion.running(__opts__)
def clear_cache(days=-1):
'''
Forcibly removes all caches on a minion.
.. versionadded:: 2014.7.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_cache days=7
'''
threshold = time.time() - days * 24 * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(__opts__['cachedir'], followlinks=False):
for name in files:
try:
file = os.path.join(root, name)
mtime = os.path.getmtime(file)
if mtime < threshold:
os.remove(file)
except OSError as exc:
log.error(
'Attempt to clear cache with saltutil.clear_cache '
'FAILED with: %s', exc
)
return False
return True
def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bash
salt '*' saltutil.clear_job_cache hours=12
'''
threshold = time.time() - hours * 60 * 60
for root, dirs, files in salt.utils.files.safe_walk(os.path.join(__opts__['cachedir'], 'minion_jobs'),
followlinks=False):
for name in dirs:
try:
directory = os.path.join(root, name)
mtime = os.path.getmtime(directory)
if mtime < threshold:
shutil.rmtree(directory)
except OSError as exc:
log.error('Attempt to clear cache with saltutil.clear_job_cache FAILED with: %s', exc)
return False
return True
def find_job(jid):
'''
Return the data for a specific job id that is currently running.
jid
The job id to search for and return data.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_job <job id>
Note that the find_job function only returns job information when the job is still running. If
the job is currently running, the output looks something like this:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
arg:
- 30
fun:
test.sleep
jid:
20160503150049487736
pid:
9601
ret:
tgt:
my-minion
tgt_type:
glob
user:
root
If the job has already completed, the job cannot be found and therefore the function returns
an empty dictionary, which looks like this on the CLI:
.. code-block:: bash
# salt my-minion saltutil.find_job 20160503150049487736
my-minion:
----------
'''
for data in running():
if data['jid'] == jid:
return data
return {}
def find_cached_job(jid):
'''
Return the data for a specific cached job id. Note this only works if
cache_jobs has previously been set to True on the minion.
CLI Example:
.. code-block:: bash
salt '*' saltutil.find_cached_job <job id>
'''
serial = salt.payload.Serial(__opts__)
proc_dir = os.path.join(__opts__['cachedir'], 'minion_jobs')
job_dir = os.path.join(proc_dir, six.text_type(jid))
if not os.path.isdir(job_dir):
if not __opts__.get('cache_jobs'):
return ('Local jobs cache directory not found; you may need to'
' enable cache_jobs on this minion')
else:
return 'Local jobs cache directory {0} not found'.format(job_dir)
path = os.path.join(job_dir, 'return.p')
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
if buf:
try:
data = serial.loads(buf)
except NameError:
# msgpack error in salt-ssh
pass
else:
if isinstance(data, dict):
# if not a dict, this was an invalid serialized object
return data
return None
def signal_job(jid, sig):
'''
Sends a signal to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.signal_job <job id> 15
'''
if HAS_PSUTIL is False:
log.warning('saltutil.signal job called, but psutil is not installed. '
'Install psutil to ensure more reliable and accurate PID '
'management.')
for data in running():
if data['jid'] == jid:
try:
if HAS_PSUTIL:
for proc in salt.utils.psutil_compat.Process(pid=data['pid']).children(recursive=True):
proc.send_signal(sig)
os.kill(int(data['pid']), sig)
if HAS_PSUTIL is False and 'child_pids' in data:
for pid in data['child_pids']:
os.kill(int(pid), sig)
return 'Signal {0} sent to job {1} at pid {2}'.format(
int(sig),
jid,
data['pid']
)
except OSError:
path = os.path.join(__opts__['cachedir'], 'proc', six.text_type(jid))
if os.path.isfile(path):
os.remove(path)
return ('Job {0} was not running and job data has been '
' cleaned up').format(jid)
return ''
def term_job(jid):
'''
Sends a termination signal (SIGTERM 15) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_job <job id>
'''
return signal_job(jid, signal.SIGTERM)
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret
def kill_job(jid):
'''
Sends a kill signal (SIGKILL 9) to the named salt job's process
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_job <job id>
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
return signal_job(jid, salt_SIGKILL)
def kill_all_jobs():
'''
Sends a kill signal (SIGKILL 9) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.kill_all_jobs
'''
# Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
# an appropriate value for the operating system this is running on.
ret = []
for data in running():
ret.append(signal_job(data['jid'], salt_SIGKILL))
return ret
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.error:
pass
# TODO: move this into a channel function? Or auth?
# create a channel again, this will force the key regen
channel = salt.transport.client.ReqChannel.factory(__opts__)
channel.close()
def revoke_auth(preserve_minion_cache=False):
'''
The minion sends a request to the master to revoke its own key.
Note that the minion session will be revoked and the minion may
not be able to return the result of this command back to the master.
If the 'preserve_minion_cache' flag is set to True, the master
cache for this minion will not be removed.
CLI Example:
.. code-block:: bash
salt '*' saltutil.revoke_auth
'''
masters = list()
ret = True
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
tok = channel.auth.gen_token(b'salt')
load = {'cmd': 'revoke_auth',
'id': __opts__['id'],
'tok': tok,
'preserve_minion_cache': preserve_minion_cache}
try:
channel.send(load)
except SaltReqTimeoutError:
ret = False
finally:
channel.close()
return ret
def _get_ssh_or_api_client(cfgfile, ssh=False):
if ssh:
client = salt.client.ssh.client.SSHClient(cfgfile)
else:
client = salt.client.get_local_client(cfgfile)
return client
def _exec(client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs):
fcn_ret = {}
seen = 0
if 'batch' in kwargs:
_cmd = client.cmd_batch
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg, 'batch': kwargs['batch'],
}
del kwargs['batch']
elif 'subset' in kwargs:
_cmd = client.cmd_subset
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'cli': True, 'kwarg': kwarg, 'sub': kwargs['subset'],
}
del kwargs['subset']
elif kwargs.get('asynchronous'):
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type,
'ret': ret, 'kwarg': kwarg
}
del kwargs['asynchronous']
# run_job doesnt need processing like the others
return client.run_job(**cmd_kwargs)
else:
_cmd = client.cmd_iter
cmd_kwargs = {
'tgt': tgt, 'fun': fun, 'arg': arg, 'timeout': timeout,
'tgt_type': tgt_type, 'ret': ret, 'kwarg': kwarg,
}
cmd_kwargs.update(kwargs)
for ret_comp in _cmd(**cmd_kwargs):
fcn_ret.update(ret_comp)
seen += 1
# fcn_ret can be empty, so we cannot len the whole return dict
if tgt_type == 'list' and len(tgt) == seen:
# do not wait for timeout when explicit list matching
# and all results are there
break
return fcn_ret
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd
'''
cfgfile = __opts__['conf_file']
client = _get_ssh_or_api_client(cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
# if return is empty, we may have not used the right conf,
# try with the 'minion relative master configuration counter part
# if available
master_cfgfile = '{0}master'.format(cfgfile[:-6]) # remove 'minion'
if (
not fcn_ret
and cfgfile.endswith('{0}{1}'.format(os.path.sep, 'minion'))
and os.path.exists(master_cfgfile)
):
client = _get_ssh_or_api_client(master_cfgfile, ssh)
fcn_ret = _exec(
client, tgt, fun, arg, timeout, tgt_type, ret, kwarg, **kwargs)
if 'batch' in kwargs:
old_ret, fcn_ret = fcn_ret, {}
for key, value in old_ret.items():
fcn_ret[key] = {
'out': value.get('out', 'highstate') if isinstance(value, dict) else 'highstate',
'ret': value,
}
return fcn_ret
def cmd_iter(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Assuming this minion is a master, execute a salt command
CLI Example:
.. code-block:: bash
salt '*' saltutil.cmd_iter
'''
if ssh:
client = salt.client.ssh.client.SSHClient(__opts__['conf_file'])
else:
client = salt.client.get_local_client(__opts__['conf_file'])
for ret in client.cmd_iter(
tgt,
fun,
arg,
timeout,
tgt_type,
ret,
kwarg,
**kwargs):
yield ret
def runner(name, arg=None, kwarg=None, full_return=False, saltenv='base', jid=None, asynchronous=False, **kwargs):
'''
Execute a runner function. This function must be run on the master,
either by targeting a minion running on a master or by using
salt-call on a master.
.. versionadded:: 2014.7.0
name
The name of the function to run
kwargs
Any keyword arguments to pass to the runner function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
In this example, assume that `master_minion` is a minion running
on a master.
.. code-block:: bash
salt master_minion saltutil.runner jobs.list_jobs
salt master_minion saltutil.runner test.arg arg="['baz']" kwarg="{'foo': 'bar'}"
'''
if arg is None:
arg = []
if kwarg is None:
kwarg = {}
jid = kwargs.pop('__orchestration_jid__', jid)
saltenv = kwargs.pop('__env__', saltenv)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
if kwargs:
kwarg.update(kwargs)
if 'master_job_cache' not in __opts__:
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.master_config(master_config)
rclient = salt.runner.RunnerClient(master_opts)
else:
rclient = salt.runner.RunnerClient(__opts__)
if name in rclient.functions:
aspec = salt.utils.args.get_function_argspec(rclient.functions[name])
if 'saltenv' in aspec.args:
kwarg['saltenv'] = saltenv
if name in ['state.orchestrate', 'state.orch', 'state.sls']:
kwarg['orchestration_jid'] = jid
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'runner', 'name': name, 'args': arg, 'kwargs': kwarg},
prefix='run'
)
if asynchronous:
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': arg, 'kwarg': kwarg, 'fun': name, 'key': master_key}
return rclient.cmd_async(low)
else:
return rclient.cmd(name,
arg=arg,
kwarg=kwarg,
print_event=False,
full_return=full_return)
def wheel(name, *args, **kwargs):
'''
Execute a wheel module and function. This function must be run against a
minion that is local to the master.
.. versionadded:: 2014.7.0
name
The name of the function to run
args
Any positional arguments to pass to the wheel function. A common example
of this would be the ``match`` arg needed for key functions.
.. versionadded:: v2015.8.11
kwargs
Any keyword arguments to pass to the wheel function
asynchronous
Run the salt command but don't wait for a reply.
.. versionadded:: neon
CLI Example:
.. code-block:: bash
salt my-local-minion saltutil.wheel key.accept jerry
salt my-local-minion saltutil.wheel minions.connected
.. note::
Since this function must be run against a minion that is running locally
on the master in order to get accurate returns, if this function is run
against minions that are not local to the master, "empty" returns are
expected. The remote minion does not have access to wheel functions and
their return data.
'''
jid = kwargs.pop('__orchestration_jid__', None)
saltenv = kwargs.pop('__env__', 'base')
if __opts__['__role'] == 'minion':
master_config = os.path.join(os.path.dirname(__opts__['conf_file']),
'master')
master_opts = salt.config.client_config(master_config)
wheel_client = salt.wheel.WheelClient(master_opts)
else:
wheel_client = salt.wheel.WheelClient(__opts__)
# The WheelClient cmd needs args, kwargs, and pub_data separated out from
# the "normal" kwargs structure, which at this point contains __pub_x keys.
pub_data = {}
valid_kwargs = {}
for key, val in six.iteritems(kwargs):
if key.startswith('__'):
pub_data[key] = val
else:
valid_kwargs[key] = val
try:
if name in wheel_client.functions:
aspec = salt.utils.args.get_function_argspec(
wheel_client.functions[name]
)
if 'saltenv' in aspec.args:
valid_kwargs['saltenv'] = saltenv
if jid:
salt.utils.event.fire_args(
__opts__,
jid,
{'type': 'wheel', 'name': name, 'args': valid_kwargs},
prefix='run'
)
if kwargs.pop('asynchronous', False):
master_key = salt.utils.master.get_master_key('root', __opts__)
low = {'arg': args, 'kwarg': kwargs, 'fun': name, 'key': master_key}
ret = wheel_client.cmd_async(low)
else:
ret = wheel_client.cmd(name,
arg=args,
pub_data=pub_data,
kwarg=valid_kwargs,
print_event=False,
full_return=True)
except SaltInvocationError as e:
raise CommandExecutionError(
'This command can only be executed on a minion that is located on '
'the master.'
)
return ret
# this is the only way I could figure out how to get the REAL file_roots
# __opt__['file_roots'] is set to __opt__['pillar_root']
class _MMinion(object):
def __new__(cls, saltenv, reload_env=False):
# this is to break out of salt.loaded.int and make this a true singleton
# hack until https://github.com/saltstack/salt/pull/10273 is resolved
# this is starting to look like PHP
global _mminions # pylint: disable=W0601
if '_mminions' not in globals():
_mminions = {}
if saltenv not in _mminions or reload_env:
opts = copy.deepcopy(__opts__)
del opts['file_roots']
# grains at this point are in the context of the minion
global __grains__ # pylint: disable=W0601
grains = copy.deepcopy(__grains__)
m = salt.minion.MasterMinion(opts)
# this assignment is so that the rest of fxns called by salt still
# have minion context
__grains__ = grains
# this assignment is so that fxns called by mminion have minion
# context
m.opts['grains'] = grains
env_roots = m.opts['file_roots'][saltenv]
m.opts['module_dirs'] = [fp + '/_modules' for fp in env_roots]
m.gen_modules()
_mminions[saltenv] = m
return _mminions[saltenv]
|
saltstack/salt
|
salt/modules/zenoss.py
|
_session
|
python
|
def _session():
'''
Create a session to be used when connecting to Zenoss.
'''
config = __salt__['config.option']('zenoss')
session = requests.session()
session.auth = (config.get('username'), config.get('password'))
session.verify = False
session.headers.update({'Content-type': 'application/json; charset=utf-8'})
return session
|
Create a session to be used when connecting to Zenoss.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zenoss.py#L68-L78
| null |
# -*- coding: utf-8 -*-
'''
Module for working with the Zenoss API
.. versionadded:: 2016.3.0
:depends: requests
:configuration: This module requires a 'zenoss' entry in the master/minion config.
For example:
.. code-block:: yaml
zenoss:
hostname: https://zenoss.example.com
username: admin
password: admin123
'''
from __future__ import absolute_import, print_function, unicode_literals
import re
import logging
try:
import requests
HAS_LIBS = True
except ImportError:
HAS_LIBS = False
import salt.utils.json
# Disable INFO level logs from requests/urllib3
urllib3_logger = logging.getLogger('urllib3')
urllib3_logger.setLevel(logging.WARNING)
log = logging.getLogger(__name__)
__virtualname__ = 'zenoss'
def __virtual__():
'''
Only load if requests is installed
'''
if HAS_LIBS:
return __virtualname__
else:
return False, 'The \'{0}\' module could not be loaded: ' \
'\'requests\' is not installed.'.format(__virtualname__)
ROUTERS = {'MessagingRouter': 'messaging',
'EventsRouter': 'evconsole',
'ProcessRouter': 'process',
'ServiceRouter': 'service',
'DeviceRouter': 'device',
'NetworkRouter': 'network',
'TemplateRouter': 'template',
'DetailNavRouter': 'detailnav',
'ReportRouter': 'report',
'MibRouter': 'mib',
'ZenPackRouter': 'zenpack'}
def _router_request(router, method, data=None):
'''
Make a request to the Zenoss API router
'''
if router not in ROUTERS:
return False
req_data = salt.utils.json.dumps([dict(
action=router,
method=method,
data=data,
type='rpc',
tid=1)])
config = __salt__['config.option']('zenoss')
log.debug('Making request to router %s with method %s', router, method)
url = '{0}/zport/dmd/{1}_router'.format(config.get('hostname'), ROUTERS[router])
response = _session().post(url, data=req_data)
# The API returns a 200 response code even whe auth is bad.
# With bad auth, the login page is displayed. Here I search for
# an element on the login form to determine if auth failed.
if re.search('name="__ac_name"', response.content):
log.error('Request failed. Bad username/password.')
raise Exception('Request failed. Bad username/password.')
return salt.utils.json.loads(response.content).get('result', None)
def _determine_device_class():
'''
If no device class is given when adding a device, this helps determine
'''
if __salt__['grains.get']('kernel') == 'Linux':
return '/Server/Linux'
def find_device(device=None):
'''
Find a device in Zenoss. If device not found, returns None.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default
CLI Example:
salt '*' zenoss.find_device
'''
data = [{'uid': '/zport/dmd/Devices', 'params': {}, 'limit': None}]
all_devices = _router_request('DeviceRouter', 'getDevices', data=data)
for dev in all_devices['devices']:
if dev['name'] == device:
# We need to save the has for later operations
dev['hash'] = all_devices['hash']
log.info('Found device %s in Zenoss', device)
return dev
log.info('Unable to find device %s in Zenoss', device)
return None
def device_exists(device=None):
'''
Check to see if a device already exists in Zenoss.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default
CLI Example:
salt '*' zenoss.device_exists
'''
if not device:
device = __salt__['grains.get']('fqdn')
if find_device(device):
return True
return False
def add_device(device=None, device_class=None, collector='localhost', prod_state=1000):
'''
A function to connect to a zenoss server and add a new device entry.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default.
device_class: (Optional) The device class to use. If none, will determine based on kernel grain.
collector: (Optional) The collector to use for this device. Defaults to 'localhost'.
prod_state: (Optional) The prodState to set on the device. If none, defaults to 1000 ( production )
CLI Example:
salt '*' zenoss.add_device
'''
if not device:
device = __salt__['grains.get']('fqdn')
if not device_class:
device_class = _determine_device_class()
log.info('Adding device %s to zenoss', device)
data = dict(deviceName=device, deviceClass=device_class, model=True, collector=collector, productionState=prod_state)
response = _router_request('DeviceRouter', 'addDevice', data=[data])
return response
def set_prod_state(prod_state, device=None):
'''
A function to set the prod_state in zenoss.
Parameters:
prod_state: (Required) Integer value of the state
device: (Optional) Will use the grain 'fqdn' by default.
CLI Example:
salt zenoss.set_prod_state 1000 hostname
'''
if not device:
device = __salt__['grains.get']('fqdn')
device_object = find_device(device)
if not device_object:
return "Unable to find a device in Zenoss for {0}".format(device)
log.info('Setting prodState to %d on %s device', prod_state, device)
data = dict(uids=[device_object['uid']], prodState=prod_state, hashcheck=device_object['hash'])
return _router_request('DeviceRouter', 'setProductionState', [data])
|
saltstack/salt
|
salt/modules/zenoss.py
|
_router_request
|
python
|
def _router_request(router, method, data=None):
'''
Make a request to the Zenoss API router
'''
if router not in ROUTERS:
return False
req_data = salt.utils.json.dumps([dict(
action=router,
method=method,
data=data,
type='rpc',
tid=1)])
config = __salt__['config.option']('zenoss')
log.debug('Making request to router %s with method %s', router, method)
url = '{0}/zport/dmd/{1}_router'.format(config.get('hostname'), ROUTERS[router])
response = _session().post(url, data=req_data)
# The API returns a 200 response code even whe auth is bad.
# With bad auth, the login page is displayed. Here I search for
# an element on the login form to determine if auth failed.
if re.search('name="__ac_name"', response.content):
log.error('Request failed. Bad username/password.')
raise Exception('Request failed. Bad username/password.')
return salt.utils.json.loads(response.content).get('result', None)
|
Make a request to the Zenoss API router
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zenoss.py#L81-L107
|
[
"def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n",
"def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n",
"def _session():\n '''\n Create a session to be used when connecting to Zenoss.\n '''\n\n config = __salt__['config.option']('zenoss')\n session = requests.session()\n session.auth = (config.get('username'), config.get('password'))\n session.verify = False\n session.headers.update({'Content-type': 'application/json; charset=utf-8'})\n return session\n"
] |
# -*- coding: utf-8 -*-
'''
Module for working with the Zenoss API
.. versionadded:: 2016.3.0
:depends: requests
:configuration: This module requires a 'zenoss' entry in the master/minion config.
For example:
.. code-block:: yaml
zenoss:
hostname: https://zenoss.example.com
username: admin
password: admin123
'''
from __future__ import absolute_import, print_function, unicode_literals
import re
import logging
try:
import requests
HAS_LIBS = True
except ImportError:
HAS_LIBS = False
import salt.utils.json
# Disable INFO level logs from requests/urllib3
urllib3_logger = logging.getLogger('urllib3')
urllib3_logger.setLevel(logging.WARNING)
log = logging.getLogger(__name__)
__virtualname__ = 'zenoss'
def __virtual__():
'''
Only load if requests is installed
'''
if HAS_LIBS:
return __virtualname__
else:
return False, 'The \'{0}\' module could not be loaded: ' \
'\'requests\' is not installed.'.format(__virtualname__)
ROUTERS = {'MessagingRouter': 'messaging',
'EventsRouter': 'evconsole',
'ProcessRouter': 'process',
'ServiceRouter': 'service',
'DeviceRouter': 'device',
'NetworkRouter': 'network',
'TemplateRouter': 'template',
'DetailNavRouter': 'detailnav',
'ReportRouter': 'report',
'MibRouter': 'mib',
'ZenPackRouter': 'zenpack'}
def _session():
'''
Create a session to be used when connecting to Zenoss.
'''
config = __salt__['config.option']('zenoss')
session = requests.session()
session.auth = (config.get('username'), config.get('password'))
session.verify = False
session.headers.update({'Content-type': 'application/json; charset=utf-8'})
return session
def _determine_device_class():
'''
If no device class is given when adding a device, this helps determine
'''
if __salt__['grains.get']('kernel') == 'Linux':
return '/Server/Linux'
def find_device(device=None):
'''
Find a device in Zenoss. If device not found, returns None.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default
CLI Example:
salt '*' zenoss.find_device
'''
data = [{'uid': '/zport/dmd/Devices', 'params': {}, 'limit': None}]
all_devices = _router_request('DeviceRouter', 'getDevices', data=data)
for dev in all_devices['devices']:
if dev['name'] == device:
# We need to save the has for later operations
dev['hash'] = all_devices['hash']
log.info('Found device %s in Zenoss', device)
return dev
log.info('Unable to find device %s in Zenoss', device)
return None
def device_exists(device=None):
'''
Check to see if a device already exists in Zenoss.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default
CLI Example:
salt '*' zenoss.device_exists
'''
if not device:
device = __salt__['grains.get']('fqdn')
if find_device(device):
return True
return False
def add_device(device=None, device_class=None, collector='localhost', prod_state=1000):
'''
A function to connect to a zenoss server and add a new device entry.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default.
device_class: (Optional) The device class to use. If none, will determine based on kernel grain.
collector: (Optional) The collector to use for this device. Defaults to 'localhost'.
prod_state: (Optional) The prodState to set on the device. If none, defaults to 1000 ( production )
CLI Example:
salt '*' zenoss.add_device
'''
if not device:
device = __salt__['grains.get']('fqdn')
if not device_class:
device_class = _determine_device_class()
log.info('Adding device %s to zenoss', device)
data = dict(deviceName=device, deviceClass=device_class, model=True, collector=collector, productionState=prod_state)
response = _router_request('DeviceRouter', 'addDevice', data=[data])
return response
def set_prod_state(prod_state, device=None):
'''
A function to set the prod_state in zenoss.
Parameters:
prod_state: (Required) Integer value of the state
device: (Optional) Will use the grain 'fqdn' by default.
CLI Example:
salt zenoss.set_prod_state 1000 hostname
'''
if not device:
device = __salt__['grains.get']('fqdn')
device_object = find_device(device)
if not device_object:
return "Unable to find a device in Zenoss for {0}".format(device)
log.info('Setting prodState to %d on %s device', prod_state, device)
data = dict(uids=[device_object['uid']], prodState=prod_state, hashcheck=device_object['hash'])
return _router_request('DeviceRouter', 'setProductionState', [data])
|
saltstack/salt
|
salt/modules/zenoss.py
|
find_device
|
python
|
def find_device(device=None):
'''
Find a device in Zenoss. If device not found, returns None.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default
CLI Example:
salt '*' zenoss.find_device
'''
data = [{'uid': '/zport/dmd/Devices', 'params': {}, 'limit': None}]
all_devices = _router_request('DeviceRouter', 'getDevices', data=data)
for dev in all_devices['devices']:
if dev['name'] == device:
# We need to save the has for later operations
dev['hash'] = all_devices['hash']
log.info('Found device %s in Zenoss', device)
return dev
log.info('Unable to find device %s in Zenoss', device)
return None
|
Find a device in Zenoss. If device not found, returns None.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default
CLI Example:
salt '*' zenoss.find_device
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zenoss.py#L118-L139
|
[
"def _router_request(router, method, data=None):\n '''\n Make a request to the Zenoss API router\n '''\n if router not in ROUTERS:\n return False\n\n req_data = salt.utils.json.dumps([dict(\n action=router,\n method=method,\n data=data,\n type='rpc',\n tid=1)])\n\n config = __salt__['config.option']('zenoss')\n log.debug('Making request to router %s with method %s', router, method)\n url = '{0}/zport/dmd/{1}_router'.format(config.get('hostname'), ROUTERS[router])\n response = _session().post(url, data=req_data)\n\n # The API returns a 200 response code even whe auth is bad.\n # With bad auth, the login page is displayed. Here I search for\n # an element on the login form to determine if auth failed.\n if re.search('name=\"__ac_name\"', response.content):\n log.error('Request failed. Bad username/password.')\n raise Exception('Request failed. Bad username/password.')\n\n return salt.utils.json.loads(response.content).get('result', None)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for working with the Zenoss API
.. versionadded:: 2016.3.0
:depends: requests
:configuration: This module requires a 'zenoss' entry in the master/minion config.
For example:
.. code-block:: yaml
zenoss:
hostname: https://zenoss.example.com
username: admin
password: admin123
'''
from __future__ import absolute_import, print_function, unicode_literals
import re
import logging
try:
import requests
HAS_LIBS = True
except ImportError:
HAS_LIBS = False
import salt.utils.json
# Disable INFO level logs from requests/urllib3
urllib3_logger = logging.getLogger('urllib3')
urllib3_logger.setLevel(logging.WARNING)
log = logging.getLogger(__name__)
__virtualname__ = 'zenoss'
def __virtual__():
'''
Only load if requests is installed
'''
if HAS_LIBS:
return __virtualname__
else:
return False, 'The \'{0}\' module could not be loaded: ' \
'\'requests\' is not installed.'.format(__virtualname__)
ROUTERS = {'MessagingRouter': 'messaging',
'EventsRouter': 'evconsole',
'ProcessRouter': 'process',
'ServiceRouter': 'service',
'DeviceRouter': 'device',
'NetworkRouter': 'network',
'TemplateRouter': 'template',
'DetailNavRouter': 'detailnav',
'ReportRouter': 'report',
'MibRouter': 'mib',
'ZenPackRouter': 'zenpack'}
def _session():
'''
Create a session to be used when connecting to Zenoss.
'''
config = __salt__['config.option']('zenoss')
session = requests.session()
session.auth = (config.get('username'), config.get('password'))
session.verify = False
session.headers.update({'Content-type': 'application/json; charset=utf-8'})
return session
def _router_request(router, method, data=None):
'''
Make a request to the Zenoss API router
'''
if router not in ROUTERS:
return False
req_data = salt.utils.json.dumps([dict(
action=router,
method=method,
data=data,
type='rpc',
tid=1)])
config = __salt__['config.option']('zenoss')
log.debug('Making request to router %s with method %s', router, method)
url = '{0}/zport/dmd/{1}_router'.format(config.get('hostname'), ROUTERS[router])
response = _session().post(url, data=req_data)
# The API returns a 200 response code even whe auth is bad.
# With bad auth, the login page is displayed. Here I search for
# an element on the login form to determine if auth failed.
if re.search('name="__ac_name"', response.content):
log.error('Request failed. Bad username/password.')
raise Exception('Request failed. Bad username/password.')
return salt.utils.json.loads(response.content).get('result', None)
def _determine_device_class():
'''
If no device class is given when adding a device, this helps determine
'''
if __salt__['grains.get']('kernel') == 'Linux':
return '/Server/Linux'
def device_exists(device=None):
'''
Check to see if a device already exists in Zenoss.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default
CLI Example:
salt '*' zenoss.device_exists
'''
if not device:
device = __salt__['grains.get']('fqdn')
if find_device(device):
return True
return False
def add_device(device=None, device_class=None, collector='localhost', prod_state=1000):
'''
A function to connect to a zenoss server and add a new device entry.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default.
device_class: (Optional) The device class to use. If none, will determine based on kernel grain.
collector: (Optional) The collector to use for this device. Defaults to 'localhost'.
prod_state: (Optional) The prodState to set on the device. If none, defaults to 1000 ( production )
CLI Example:
salt '*' zenoss.add_device
'''
if not device:
device = __salt__['grains.get']('fqdn')
if not device_class:
device_class = _determine_device_class()
log.info('Adding device %s to zenoss', device)
data = dict(deviceName=device, deviceClass=device_class, model=True, collector=collector, productionState=prod_state)
response = _router_request('DeviceRouter', 'addDevice', data=[data])
return response
def set_prod_state(prod_state, device=None):
'''
A function to set the prod_state in zenoss.
Parameters:
prod_state: (Required) Integer value of the state
device: (Optional) Will use the grain 'fqdn' by default.
CLI Example:
salt zenoss.set_prod_state 1000 hostname
'''
if not device:
device = __salt__['grains.get']('fqdn')
device_object = find_device(device)
if not device_object:
return "Unable to find a device in Zenoss for {0}".format(device)
log.info('Setting prodState to %d on %s device', prod_state, device)
data = dict(uids=[device_object['uid']], prodState=prod_state, hashcheck=device_object['hash'])
return _router_request('DeviceRouter', 'setProductionState', [data])
|
saltstack/salt
|
salt/modules/zenoss.py
|
add_device
|
python
|
def add_device(device=None, device_class=None, collector='localhost', prod_state=1000):
'''
A function to connect to a zenoss server and add a new device entry.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default.
device_class: (Optional) The device class to use. If none, will determine based on kernel grain.
collector: (Optional) The collector to use for this device. Defaults to 'localhost'.
prod_state: (Optional) The prodState to set on the device. If none, defaults to 1000 ( production )
CLI Example:
salt '*' zenoss.add_device
'''
if not device:
device = __salt__['grains.get']('fqdn')
if not device_class:
device_class = _determine_device_class()
log.info('Adding device %s to zenoss', device)
data = dict(deviceName=device, deviceClass=device_class, model=True, collector=collector, productionState=prod_state)
response = _router_request('DeviceRouter', 'addDevice', data=[data])
return response
|
A function to connect to a zenoss server and add a new device entry.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default.
device_class: (Optional) The device class to use. If none, will determine based on kernel grain.
collector: (Optional) The collector to use for this device. Defaults to 'localhost'.
prod_state: (Optional) The prodState to set on the device. If none, defaults to 1000 ( production )
CLI Example:
salt '*' zenoss.add_device
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zenoss.py#L161-L183
|
[
"def _router_request(router, method, data=None):\n '''\n Make a request to the Zenoss API router\n '''\n if router not in ROUTERS:\n return False\n\n req_data = salt.utils.json.dumps([dict(\n action=router,\n method=method,\n data=data,\n type='rpc',\n tid=1)])\n\n config = __salt__['config.option']('zenoss')\n log.debug('Making request to router %s with method %s', router, method)\n url = '{0}/zport/dmd/{1}_router'.format(config.get('hostname'), ROUTERS[router])\n response = _session().post(url, data=req_data)\n\n # The API returns a 200 response code even whe auth is bad.\n # With bad auth, the login page is displayed. Here I search for\n # an element on the login form to determine if auth failed.\n if re.search('name=\"__ac_name\"', response.content):\n log.error('Request failed. Bad username/password.')\n raise Exception('Request failed. Bad username/password.')\n\n return salt.utils.json.loads(response.content).get('result', None)\n",
"def _determine_device_class():\n '''\n If no device class is given when adding a device, this helps determine\n '''\n if __salt__['grains.get']('kernel') == 'Linux':\n return '/Server/Linux'\n"
] |
# -*- coding: utf-8 -*-
'''
Module for working with the Zenoss API
.. versionadded:: 2016.3.0
:depends: requests
:configuration: This module requires a 'zenoss' entry in the master/minion config.
For example:
.. code-block:: yaml
zenoss:
hostname: https://zenoss.example.com
username: admin
password: admin123
'''
from __future__ import absolute_import, print_function, unicode_literals
import re
import logging
try:
import requests
HAS_LIBS = True
except ImportError:
HAS_LIBS = False
import salt.utils.json
# Disable INFO level logs from requests/urllib3
urllib3_logger = logging.getLogger('urllib3')
urllib3_logger.setLevel(logging.WARNING)
log = logging.getLogger(__name__)
__virtualname__ = 'zenoss'
def __virtual__():
'''
Only load if requests is installed
'''
if HAS_LIBS:
return __virtualname__
else:
return False, 'The \'{0}\' module could not be loaded: ' \
'\'requests\' is not installed.'.format(__virtualname__)
ROUTERS = {'MessagingRouter': 'messaging',
'EventsRouter': 'evconsole',
'ProcessRouter': 'process',
'ServiceRouter': 'service',
'DeviceRouter': 'device',
'NetworkRouter': 'network',
'TemplateRouter': 'template',
'DetailNavRouter': 'detailnav',
'ReportRouter': 'report',
'MibRouter': 'mib',
'ZenPackRouter': 'zenpack'}
def _session():
'''
Create a session to be used when connecting to Zenoss.
'''
config = __salt__['config.option']('zenoss')
session = requests.session()
session.auth = (config.get('username'), config.get('password'))
session.verify = False
session.headers.update({'Content-type': 'application/json; charset=utf-8'})
return session
def _router_request(router, method, data=None):
'''
Make a request to the Zenoss API router
'''
if router not in ROUTERS:
return False
req_data = salt.utils.json.dumps([dict(
action=router,
method=method,
data=data,
type='rpc',
tid=1)])
config = __salt__['config.option']('zenoss')
log.debug('Making request to router %s with method %s', router, method)
url = '{0}/zport/dmd/{1}_router'.format(config.get('hostname'), ROUTERS[router])
response = _session().post(url, data=req_data)
# The API returns a 200 response code even whe auth is bad.
# With bad auth, the login page is displayed. Here I search for
# an element on the login form to determine if auth failed.
if re.search('name="__ac_name"', response.content):
log.error('Request failed. Bad username/password.')
raise Exception('Request failed. Bad username/password.')
return salt.utils.json.loads(response.content).get('result', None)
def _determine_device_class():
'''
If no device class is given when adding a device, this helps determine
'''
if __salt__['grains.get']('kernel') == 'Linux':
return '/Server/Linux'
def find_device(device=None):
'''
Find a device in Zenoss. If device not found, returns None.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default
CLI Example:
salt '*' zenoss.find_device
'''
data = [{'uid': '/zport/dmd/Devices', 'params': {}, 'limit': None}]
all_devices = _router_request('DeviceRouter', 'getDevices', data=data)
for dev in all_devices['devices']:
if dev['name'] == device:
# We need to save the has for later operations
dev['hash'] = all_devices['hash']
log.info('Found device %s in Zenoss', device)
return dev
log.info('Unable to find device %s in Zenoss', device)
return None
def device_exists(device=None):
'''
Check to see if a device already exists in Zenoss.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default
CLI Example:
salt '*' zenoss.device_exists
'''
if not device:
device = __salt__['grains.get']('fqdn')
if find_device(device):
return True
return False
def set_prod_state(prod_state, device=None):
'''
A function to set the prod_state in zenoss.
Parameters:
prod_state: (Required) Integer value of the state
device: (Optional) Will use the grain 'fqdn' by default.
CLI Example:
salt zenoss.set_prod_state 1000 hostname
'''
if not device:
device = __salt__['grains.get']('fqdn')
device_object = find_device(device)
if not device_object:
return "Unable to find a device in Zenoss for {0}".format(device)
log.info('Setting prodState to %d on %s device', prod_state, device)
data = dict(uids=[device_object['uid']], prodState=prod_state, hashcheck=device_object['hash'])
return _router_request('DeviceRouter', 'setProductionState', [data])
|
saltstack/salt
|
salt/modules/zenoss.py
|
set_prod_state
|
python
|
def set_prod_state(prod_state, device=None):
'''
A function to set the prod_state in zenoss.
Parameters:
prod_state: (Required) Integer value of the state
device: (Optional) Will use the grain 'fqdn' by default.
CLI Example:
salt zenoss.set_prod_state 1000 hostname
'''
if not device:
device = __salt__['grains.get']('fqdn')
device_object = find_device(device)
if not device_object:
return "Unable to find a device in Zenoss for {0}".format(device)
log.info('Setting prodState to %d on %s device', prod_state, device)
data = dict(uids=[device_object['uid']], prodState=prod_state, hashcheck=device_object['hash'])
return _router_request('DeviceRouter', 'setProductionState', [data])
|
A function to set the prod_state in zenoss.
Parameters:
prod_state: (Required) Integer value of the state
device: (Optional) Will use the grain 'fqdn' by default.
CLI Example:
salt zenoss.set_prod_state 1000 hostname
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zenoss.py#L186-L208
|
[
"def _router_request(router, method, data=None):\n '''\n Make a request to the Zenoss API router\n '''\n if router not in ROUTERS:\n return False\n\n req_data = salt.utils.json.dumps([dict(\n action=router,\n method=method,\n data=data,\n type='rpc',\n tid=1)])\n\n config = __salt__['config.option']('zenoss')\n log.debug('Making request to router %s with method %s', router, method)\n url = '{0}/zport/dmd/{1}_router'.format(config.get('hostname'), ROUTERS[router])\n response = _session().post(url, data=req_data)\n\n # The API returns a 200 response code even whe auth is bad.\n # With bad auth, the login page is displayed. Here I search for\n # an element on the login form to determine if auth failed.\n if re.search('name=\"__ac_name\"', response.content):\n log.error('Request failed. Bad username/password.')\n raise Exception('Request failed. Bad username/password.')\n\n return salt.utils.json.loads(response.content).get('result', None)\n",
"def find_device(device=None):\n '''\n Find a device in Zenoss. If device not found, returns None.\n\n Parameters:\n device: (Optional) Will use the grain 'fqdn' by default\n\n CLI Example:\n salt '*' zenoss.find_device\n '''\n\n data = [{'uid': '/zport/dmd/Devices', 'params': {}, 'limit': None}]\n all_devices = _router_request('DeviceRouter', 'getDevices', data=data)\n for dev in all_devices['devices']:\n if dev['name'] == device:\n # We need to save the has for later operations\n dev['hash'] = all_devices['hash']\n log.info('Found device %s in Zenoss', device)\n return dev\n\n log.info('Unable to find device %s in Zenoss', device)\n return None\n"
] |
# -*- coding: utf-8 -*-
'''
Module for working with the Zenoss API
.. versionadded:: 2016.3.0
:depends: requests
:configuration: This module requires a 'zenoss' entry in the master/minion config.
For example:
.. code-block:: yaml
zenoss:
hostname: https://zenoss.example.com
username: admin
password: admin123
'''
from __future__ import absolute_import, print_function, unicode_literals
import re
import logging
try:
import requests
HAS_LIBS = True
except ImportError:
HAS_LIBS = False
import salt.utils.json
# Disable INFO level logs from requests/urllib3
urllib3_logger = logging.getLogger('urllib3')
urllib3_logger.setLevel(logging.WARNING)
log = logging.getLogger(__name__)
__virtualname__ = 'zenoss'
def __virtual__():
'''
Only load if requests is installed
'''
if HAS_LIBS:
return __virtualname__
else:
return False, 'The \'{0}\' module could not be loaded: ' \
'\'requests\' is not installed.'.format(__virtualname__)
ROUTERS = {'MessagingRouter': 'messaging',
'EventsRouter': 'evconsole',
'ProcessRouter': 'process',
'ServiceRouter': 'service',
'DeviceRouter': 'device',
'NetworkRouter': 'network',
'TemplateRouter': 'template',
'DetailNavRouter': 'detailnav',
'ReportRouter': 'report',
'MibRouter': 'mib',
'ZenPackRouter': 'zenpack'}
def _session():
'''
Create a session to be used when connecting to Zenoss.
'''
config = __salt__['config.option']('zenoss')
session = requests.session()
session.auth = (config.get('username'), config.get('password'))
session.verify = False
session.headers.update({'Content-type': 'application/json; charset=utf-8'})
return session
def _router_request(router, method, data=None):
'''
Make a request to the Zenoss API router
'''
if router not in ROUTERS:
return False
req_data = salt.utils.json.dumps([dict(
action=router,
method=method,
data=data,
type='rpc',
tid=1)])
config = __salt__['config.option']('zenoss')
log.debug('Making request to router %s with method %s', router, method)
url = '{0}/zport/dmd/{1}_router'.format(config.get('hostname'), ROUTERS[router])
response = _session().post(url, data=req_data)
# The API returns a 200 response code even whe auth is bad.
# With bad auth, the login page is displayed. Here I search for
# an element on the login form to determine if auth failed.
if re.search('name="__ac_name"', response.content):
log.error('Request failed. Bad username/password.')
raise Exception('Request failed. Bad username/password.')
return salt.utils.json.loads(response.content).get('result', None)
def _determine_device_class():
'''
If no device class is given when adding a device, this helps determine
'''
if __salt__['grains.get']('kernel') == 'Linux':
return '/Server/Linux'
def find_device(device=None):
'''
Find a device in Zenoss. If device not found, returns None.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default
CLI Example:
salt '*' zenoss.find_device
'''
data = [{'uid': '/zport/dmd/Devices', 'params': {}, 'limit': None}]
all_devices = _router_request('DeviceRouter', 'getDevices', data=data)
for dev in all_devices['devices']:
if dev['name'] == device:
# We need to save the has for later operations
dev['hash'] = all_devices['hash']
log.info('Found device %s in Zenoss', device)
return dev
log.info('Unable to find device %s in Zenoss', device)
return None
def device_exists(device=None):
'''
Check to see if a device already exists in Zenoss.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default
CLI Example:
salt '*' zenoss.device_exists
'''
if not device:
device = __salt__['grains.get']('fqdn')
if find_device(device):
return True
return False
def add_device(device=None, device_class=None, collector='localhost', prod_state=1000):
'''
A function to connect to a zenoss server and add a new device entry.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default.
device_class: (Optional) The device class to use. If none, will determine based on kernel grain.
collector: (Optional) The collector to use for this device. Defaults to 'localhost'.
prod_state: (Optional) The prodState to set on the device. If none, defaults to 1000 ( production )
CLI Example:
salt '*' zenoss.add_device
'''
if not device:
device = __salt__['grains.get']('fqdn')
if not device_class:
device_class = _determine_device_class()
log.info('Adding device %s to zenoss', device)
data = dict(deviceName=device, deviceClass=device_class, model=True, collector=collector, productionState=prod_state)
response = _router_request('DeviceRouter', 'addDevice', data=[data])
return response
|
saltstack/salt
|
salt/modules/restartcheck.py
|
_valid_deleted_file
|
python
|
def _valid_deleted_file(path):
'''
Filters file path against unwanted directories and decides whether file is marked as deleted.
Returns:
True if file is desired deleted file, else False.
Args:
path: A string - path to file
'''
ret = False
if path.endswith(' (deleted)'):
ret = True
if re.compile(r"\(path inode=[0-9]+\)$").search(path):
ret = True
regex = re.compile("|".join(LIST_DIRS))
if regex.match(path):
ret = False
return ret
|
Filters file path against unwanted directories and decides whether file is marked as deleted.
Returns:
True if file is desired deleted file, else False.
Args:
path: A string - path to file
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/restartcheck.py#L93-L112
| null |
# -*- coding: utf-8 -*-
'''
checkrestart functionality for Debian and Red Hat Based systems
Identifies services (processes) that are linked against deleted files (for example after downloading an updated
binary of a shared library).
Based on checkrestart script from debian-goodies (written by Matt Zimmerman for the Debian GNU/Linux distribution,
https://packages.debian.org/debian-goodies) and psdel by Sam Morris.
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import subprocess
import sys
import time
# Import salt libs
import salt.exceptions
import salt.utils.args
import salt.utils.files
import salt.utils.path
# Import 3rd partylibs
from salt.ext import six
NILRT_FAMILY_NAME = 'NILinuxRT'
HAS_PSUTIL = False
try:
import psutil
HAS_PSUTIL = True
except ImportError:
pass
LIST_DIRS = [
# We don't care about log files
'^/var/log/',
'^/var/local/log/',
# Or about files under temporary locations
'^/var/run/',
'^/var/local/run/',
# Or about files under /tmp
'^/tmp/',
# Or about files under /dev/shm
'^/dev/shm/',
# Or about files under /run
'^/run/',
# Or about files under /drm
'^/drm',
# Or about files under /var/tmp and /var/local/tmp
'^/var/tmp/',
'^/var/local/tmp/',
# Or /dev/zero
'^/dev/zero',
# Or /dev/pts (used by gpm)
'^/dev/pts/',
# Or /usr/lib/locale
'^/usr/lib/locale/',
# Skip files from the user's home directories
# many processes hold temporafy files there
'^/home/',
# Skip automatically generated files
'^.*icon-theme.cache',
# Skip font files
'^/var/cache/fontconfig/',
# Skip Nagios Spool
'^/var/lib/nagios3/spool/',
# Skip nagios spool files
'^/var/lib/nagios3/spool/checkresults/',
# Skip Postgresql files
'^/var/lib/postgresql/',
# Skip VDR lib files
'^/var/lib/vdr/',
# Skip Aio files found in MySQL servers
'^/[aio]',
# ignore files under /SYSV
'^/SYSV'
]
def __virtual__():
'''
Only run this module if the psutil python module is installed (package python-psutil).
'''
return HAS_PSUTIL
def _deleted_files():
'''
Iterates over /proc/PID/maps and /proc/PID/fd links and returns list of desired deleted files.
Returns:
List of deleted files to analyze, False on failure.
'''
deleted_files = []
for proc in psutil.process_iter(): # pylint: disable=too-many-nested-blocks
try:
pinfo = proc.as_dict(attrs=['pid', 'name'])
try:
with salt.utils.files.fopen('/proc/{0}/maps'.format(pinfo['pid'])) as maps: # pylint: disable=resource-leakage
dirpath = '/proc/' + six.text_type(pinfo['pid']) + '/fd/'
listdir = os.listdir(dirpath)
maplines = maps.readlines()
except (OSError, IOError):
yield False
# /proc/PID/maps
mapline = re.compile(r'^[\da-f]+-[\da-f]+ [r-][w-][x-][sp-] '
r'[\da-f]+ [\da-f]{2}:[\da-f]{2} (\d+) *(.+)( \(deleted\))?\n$')
for line in maplines:
line = salt.utils.stringutils.to_unicode(line)
matched = mapline.match(line)
if not matched:
continue
path = matched.group(2)
if not path:
continue
valid = _valid_deleted_file(path)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], path[0:-10])
if val not in deleted_files:
deleted_files.append(val)
yield val
# /proc/PID/fd
try:
for link in listdir:
path = dirpath + link
readlink = os.readlink(path)
filenames = []
if os.path.isfile(readlink):
filenames.append(readlink)
elif os.path.isdir(readlink) and readlink != '/':
for root, dummy_dirs, files in salt.utils.path.os_walk(readlink, followlinks=True):
for name in files:
filenames.append(os.path.join(root, name))
for filename in filenames:
valid = _valid_deleted_file(filename)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], filename)
if val not in deleted_files:
deleted_files.append(val)
yield val
except OSError:
pass
except psutil.NoSuchProcess:
pass
def _format_output(kernel_restart, packages, verbose, restartable, nonrestartable, restartservicecommands,
restartinitcommands):
'''
Formats the output of the restartcheck module.
Returns:
String - formatted output.
Args:
kernel_restart: indicates that newer kernel is instaled
packages: list of packages that should be restarted
verbose: enables extensive output
restartable: list of restartable packages
nonrestartable: list of non-restartable packages
restartservicecommands: list of commands to restart services
restartinitcommands: list of commands to restart init.d scripts
'''
if not verbose:
packages = restartable + nonrestartable
if kernel_restart:
packages.append('System restart required.')
return packages
else:
ret = ''
if kernel_restart:
ret = 'System restart required.\n\n'
if packages:
ret += "Found {0} processes using old versions of upgraded files.\n".format(len(packages))
ret += "These are the packages:\n"
if restartable:
ret += "Of these, {0} seem to contain systemd service definitions or init scripts " \
"which can be used to restart them:\n".format(len(restartable))
for package in restartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
if restartservicecommands:
ret += "\n\nThese are the systemd services:\n"
ret += '\n'.join(restartservicecommands)
if restartinitcommands:
ret += "\n\nThese are the initd scripts:\n"
ret += '\n'.join(restartinitcommands)
if nonrestartable:
ret += "\n\nThese processes {0} do not seem to have an associated init script " \
"to restart them:\n".format(len(nonrestartable))
for package in nonrestartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
return ret
def _kernel_versions_debian():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kernel_get_selections = __salt__['cmd.run']('dpkg --get-selections linux-image-*')
kernels = []
kernel_versions = []
for line in kernel_get_selections.splitlines():
kernels.append(line)
try:
kernel = kernels[-2]
except IndexError:
kernel = kernels[0]
kernel = kernel.rstrip('\t\tinstall')
kernel_get_version = __salt__['cmd.run']('apt-cache policy ' + kernel)
for line in kernel_get_version.splitlines():
if line.startswith(' Installed: '):
kernel_v = line.strip(' Installed: ')
kernel_versions.append(kernel_v)
break
if __grains__['os'] == 'Ubuntu':
kernel_v = kernel_versions[0].rsplit('.', 1)
kernel_ubuntu_generic = kernel_v[0] + '-generic #' + kernel_v[1]
kernel_ubuntu_lowlatency = kernel_v[0] + '-lowlatency #' + kernel_v[1]
kernel_versions.extend([kernel_ubuntu_generic, kernel_ubuntu_lowlatency])
return kernel_versions
def _kernel_versions_redhat():
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
kernel_get_last = __salt__['cmd.run']('rpm -q --last kernel')
kernels = []
kernel_versions = []
for line in kernel_get_last.splitlines():
if 'kernel-' in line:
kernels.append(line)
kernel = kernels[0].split(' ', 1)[0]
kernel = kernel.strip('kernel-')
kernel_versions.append(kernel)
return kernel_versions
def _kernel_versions_nilrt():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kver = None
def _get_kver_from_bin(kbin):
'''
Get kernel version from a binary image or None if detection fails
'''
kvregex = r'[0-9]+\.[0-9]+\.[0-9]+-rt\S+'
kernel_strings = __salt__['cmd.run']('strings {0}'.format(kbin))
re_result = re.search(kvregex, kernel_strings)
return None if re_result is None else re_result.group(0)
if __grains__.get('lsb_distrib_id') == 'nilrt':
if 'arm' in __grains__.get('cpuarch'):
# the kernel is inside a uboot created itb (FIT) image alongside the
# device tree, ramdisk and a bootscript. There is no package management
# or any other kind of versioning info, so we need to extract the itb.
itb_path = '/boot/linux_runmode.itb'
compressed_kernel = '/var/volatile/tmp/uImage.gz'
uncompressed_kernel = '/var/volatile/tmp/uImage'
__salt__['cmd.run']('dumpimage -i {0} -T flat_dt -p0 kernel -o {1}'
.format(itb_path, compressed_kernel))
__salt__['cmd.run']('gunzip -f {0}'.format(compressed_kernel))
kver = _get_kver_from_bin(uncompressed_kernel)
else:
# the kernel bzImage is copied to rootfs without package management or
# other versioning info.
kver = _get_kver_from_bin('/boot/runmode/bzImage')
else:
# kernels in newer NILRT's are installed via package management and
# have the version appended to the kernel image filename
if 'arm' in __grains__.get('cpuarch'):
kver = os.path.basename(os.readlink('/boot/uImage')).strip('uImage-')
else:
kver = os.path.basename(os.readlink('/boot/bzImage')).strip('bzImage-')
return [] if kver is None else [kver]
def _check_timeout(start_time, timeout):
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
timeout_milisec = timeout * 60000
if timeout_milisec < (int(round(time.time() * 1000)) - start_time):
raise salt.exceptions.TimeoutError('Timeout expired.')
def _file_changed_nilrt(full_filepath):
'''
Detect whether a file changed in an NILinuxRT system using md5sum and timestamp
files from a state directory.
Returns:
- False if md5sum/timestamp state files don't exist
- True/False depending if ``base_filename`` got modified/touched
'''
rs_state_dir = "/var/lib/salt/restartcheck_state"
base_filename = os.path.basename(full_filepath)
timestamp_file = os.path.join(rs_state_dir, '{0}.timestamp'.format(base_filename))
md5sum_file = os.path.join(rs_state_dir, '{0}.md5sum'.format(base_filename))
if not os.path.exists(timestamp_file) or not os.path.exists(md5sum_file):
return True
prev_timestamp = __salt__['file.read'](timestamp_file).rstrip()
# Need timestamp in seconds so floor it using int()
cur_timestamp = str(int(os.path.getmtime(full_filepath)))
if prev_timestamp != cur_timestamp:
return True
return bool(__salt__['cmd.retcode']('md5sum -cs {0}'.format(md5sum_file), output_loglevel="quiet"))
def _kernel_modules_changed_nilrt(kernelversion):
'''
Once a NILRT kernel module is inserted, it can't be rmmod so systems need
rebooting (some modules explicitly ask for reboots even on first install),
hence this functionality of determining if the module state got modified by
testing if depmod was run.
Returns:
- True/False depending if modules.dep got modified/touched
'''
if kernelversion is not None:
return _file_changed_nilrt('/lib/modules/{0}/modules.dep'.format(kernelversion))
return False
def _sysapi_changed_nilrt():
'''
Besides the normal Linux kernel driver interfaces, NILinuxRT-supported hardware features an
extensible, plugin-based device enumeration and configuration interface named "System API".
When an installed package is extending the API it is very hard to know all repercurssions and
actions to be taken, so reboot making sure all drivers are reloaded, hardware reinitialized,
daemons restarted, etc.
Returns:
- True/False depending if nisysapi .ini files got modified/touched
- False if no nisysapi .ini files exist
'''
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path) and _file_changed_nilrt(nisysapi_path):
return True
restartcheck_state_dir = '/var/lib/salt/restartcheck_state'
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
rs_count_file = '{0}/sysapi.conf.d.count'.format(restartcheck_state_dir)
if not os.path.exists(rs_count_file):
return True
with salt.utils.files.fopen(rs_count_file, 'r') as fcount:
current_nb_files = len(os.listdir(nisysapi_conf_d_path))
rs_stored_nb_files = int(fcount.read())
if current_nb_files != rs_stored_nb_files:
return True
for fexpert in os.listdir(nisysapi_conf_d_path):
if _file_changed_nilrt('{0}/{1}'.format(nisysapi_conf_d_path, fexpert)):
return True
return False
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def restartcheck(ignorelist=None, blacklist=None, excludepid=None, **kwargs):
'''
Analyzes files openeded by running processes and seeks for packages which need to be restarted.
Args:
ignorelist: string or list of packages to be ignored
blacklist: string or list of file paths to be ignored
excludepid: string or list of process IDs to be ignored
verbose: boolean, enables extensive output
timeout: int, timeout in minute
Returns:
Dict on error: { 'result': False, 'comment': '<reason>' }
String with checkrestart output if some package seems to need to be restarted or
if no packages need restarting.
.. versionadded:: 2015.8.3
CLI Example:
.. code-block:: bash
salt '*' restartcheck.restartcheck
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
start_time = int(round(time.time() * 1000))
kernel_restart = True
verbose = kwargs.pop('verbose', True)
timeout = kwargs.pop('timeout', 5)
if __grains__.get('os_family') == 'Debian':
cmd_pkg_query = 'dpkg-query --listfiles '
systemd_folder = '/lib/systemd/system/'
systemd = '/bin/systemd'
kernel_versions = _kernel_versions_debian()
elif __grains__.get('os_family') == 'RedHat':
cmd_pkg_query = 'repoquery -l '
systemd_folder = '/usr/lib/systemd/system/'
systemd = '/usr/bin/systemctl'
kernel_versions = _kernel_versions_redhat()
elif __grains__.get('os_family') == NILRT_FAMILY_NAME:
cmd_pkg_query = 'opkg files '
systemd = ''
kernel_versions = _kernel_versions_nilrt()
else:
return {'result': False, 'comment': 'Only available on Debian, Red Hat and NI Linux Real-Time based systems.'}
# Check kernel versions
kernel_current = __salt__['cmd.run']('uname -a')
for kernel in kernel_versions:
_check_timeout(start_time, timeout)
if kernel in kernel_current:
if __grains__.get('os_family') == 'NILinuxRT':
# Check kernel modules and hardware API's for version changes
# If a restartcheck=True event was previously witnessed, propagate it
if not _kernel_modules_changed_nilrt(kernel) and \
not _sysapi_changed_nilrt() and \
not __salt__['system.get_reboot_required_witnessed']():
kernel_restart = False
break
else:
kernel_restart = False
break
packages = {}
running_services = {}
restart_services = []
if ignorelist:
if not isinstance(ignorelist, list):
ignorelist = [ignorelist]
else:
ignorelist = ['screen', 'systemd']
if blacklist:
if not isinstance(blacklist, list):
blacklist = [blacklist]
else:
blacklist = []
if excludepid:
if not isinstance(excludepid, list):
excludepid = [excludepid]
else:
excludepid = []
for service in __salt__['service.get_running']():
_check_timeout(start_time, timeout)
service_show = __salt__['service.show'](service)
if 'ExecMainPID' in service_show:
running_services[service] = int(service_show['ExecMainPID'])
owners_cache = {}
for deleted_file in _deleted_files():
if deleted_file is False:
return {'result': False, 'comment': 'Could not get list of processes.'
' (Do you have root access?)'}
_check_timeout(start_time, timeout)
name, pid, path = deleted_file[0], deleted_file[1], deleted_file[2]
if path in blacklist or pid in excludepid:
continue
try:
readlink = os.readlink('/proc/{0}/exe'.format(pid))
except OSError:
excludepid.append(pid)
continue
try:
packagename = owners_cache[readlink]
except KeyError:
packagename = __salt__['pkg.owner'](readlink)
if not packagename:
packagename = name
owners_cache[readlink] = packagename
for running_service in running_services:
_check_timeout(start_time, timeout)
if running_service not in restart_services and pid == running_services[running_service]:
if packagename and packagename not in ignorelist:
restart_services.append(running_service)
name = running_service
if packagename and packagename not in ignorelist:
program = '\t' + six.text_type(pid) + ' ' + readlink + ' (file: ' + six.text_type(path) + ')'
if packagename not in packages:
packages[packagename] = {'initscripts': [], 'systemdservice': [], 'processes': [program],
'process_name': name}
else:
if program not in packages[packagename]['processes']:
packages[packagename]['processes'].append(program)
if not packages and not kernel_restart:
return 'No packages seem to need to be restarted.'
for package in packages:
_check_timeout(start_time, timeout)
cmd = cmd_pkg_query + package
paths = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
while True:
_check_timeout(start_time, timeout)
line = salt.utils.stringutils.to_unicode(paths.stdout.readline())
if not line:
break
pth = line[:-1]
if pth.startswith('/etc/init.d/') and not pth.endswith('.sh'):
packages[package]['initscripts'].append(pth[12:])
if os.path.exists(systemd) and pth.startswith(systemd_folder) and pth.endswith('.service') and \
pth.find('.wants') == -1:
is_oneshot = False
try:
servicefile = salt.utils.files.fopen(pth) # pylint: disable=resource-leakage
except IOError:
continue
sysfold_len = len(systemd_folder)
for line in servicefile.readlines():
line = salt.utils.stringutils.to_unicode(line)
if line.find('Type=oneshot') > 0:
# scripts that does a single job and then exit
is_oneshot = True
continue
servicefile.close()
if not is_oneshot:
packages[package]['systemdservice'].append(pth[sysfold_len:])
sys.stdout.flush()
paths.stdout.close()
# Alternatively, find init.d script or service that match the process name
for package in packages:
_check_timeout(start_time, timeout)
if not packages[package]['systemdservice'] and not packages[package]['initscripts']:
service = __salt__['service.available'](packages[package]['process_name'])
if service:
if os.path.exists('/etc/init.d/' + packages[package]['process_name']):
packages[package]['initscripts'].append(packages[package]['process_name'])
else:
packages[package]['systemdservice'].append(packages[package]['process_name'])
restartable = []
nonrestartable = []
restartinitcommands = []
restartservicecommands = []
for package in packages:
_check_timeout(start_time, timeout)
if packages[package]['initscripts']:
restartable.append(package)
restartinitcommands.extend(['service ' + s + ' restart' for s in packages[package]['initscripts']])
elif packages[package]['systemdservice']:
restartable.append(package)
restartservicecommands.extend(['systemctl restart ' + s for s in packages[package]['systemdservice']])
else:
nonrestartable.append(package)
if packages[package]['process_name'] in restart_services:
restart_services.remove(packages[package]['process_name'])
for restart_service in restart_services:
_check_timeout(start_time, timeout)
restartservicecommands.extend(['systemctl restart ' + restart_service])
ret = _format_output(kernel_restart, packages, verbose, restartable, nonrestartable,
restartservicecommands, restartinitcommands)
return ret
|
saltstack/salt
|
salt/modules/restartcheck.py
|
_deleted_files
|
python
|
def _deleted_files():
'''
Iterates over /proc/PID/maps and /proc/PID/fd links and returns list of desired deleted files.
Returns:
List of deleted files to analyze, False on failure.
'''
deleted_files = []
for proc in psutil.process_iter(): # pylint: disable=too-many-nested-blocks
try:
pinfo = proc.as_dict(attrs=['pid', 'name'])
try:
with salt.utils.files.fopen('/proc/{0}/maps'.format(pinfo['pid'])) as maps: # pylint: disable=resource-leakage
dirpath = '/proc/' + six.text_type(pinfo['pid']) + '/fd/'
listdir = os.listdir(dirpath)
maplines = maps.readlines()
except (OSError, IOError):
yield False
# /proc/PID/maps
mapline = re.compile(r'^[\da-f]+-[\da-f]+ [r-][w-][x-][sp-] '
r'[\da-f]+ [\da-f]{2}:[\da-f]{2} (\d+) *(.+)( \(deleted\))?\n$')
for line in maplines:
line = salt.utils.stringutils.to_unicode(line)
matched = mapline.match(line)
if not matched:
continue
path = matched.group(2)
if not path:
continue
valid = _valid_deleted_file(path)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], path[0:-10])
if val not in deleted_files:
deleted_files.append(val)
yield val
# /proc/PID/fd
try:
for link in listdir:
path = dirpath + link
readlink = os.readlink(path)
filenames = []
if os.path.isfile(readlink):
filenames.append(readlink)
elif os.path.isdir(readlink) and readlink != '/':
for root, dummy_dirs, files in salt.utils.path.os_walk(readlink, followlinks=True):
for name in files:
filenames.append(os.path.join(root, name))
for filename in filenames:
valid = _valid_deleted_file(filename)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], filename)
if val not in deleted_files:
deleted_files.append(val)
yield val
except OSError:
pass
except psutil.NoSuchProcess:
pass
|
Iterates over /proc/PID/maps and /proc/PID/fd links and returns list of desired deleted files.
Returns:
List of deleted files to analyze, False on failure.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/restartcheck.py#L115-L182
| null |
# -*- coding: utf-8 -*-
'''
checkrestart functionality for Debian and Red Hat Based systems
Identifies services (processes) that are linked against deleted files (for example after downloading an updated
binary of a shared library).
Based on checkrestart script from debian-goodies (written by Matt Zimmerman for the Debian GNU/Linux distribution,
https://packages.debian.org/debian-goodies) and psdel by Sam Morris.
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import subprocess
import sys
import time
# Import salt libs
import salt.exceptions
import salt.utils.args
import salt.utils.files
import salt.utils.path
# Import 3rd partylibs
from salt.ext import six
NILRT_FAMILY_NAME = 'NILinuxRT'
HAS_PSUTIL = False
try:
import psutil
HAS_PSUTIL = True
except ImportError:
pass
LIST_DIRS = [
# We don't care about log files
'^/var/log/',
'^/var/local/log/',
# Or about files under temporary locations
'^/var/run/',
'^/var/local/run/',
# Or about files under /tmp
'^/tmp/',
# Or about files under /dev/shm
'^/dev/shm/',
# Or about files under /run
'^/run/',
# Or about files under /drm
'^/drm',
# Or about files under /var/tmp and /var/local/tmp
'^/var/tmp/',
'^/var/local/tmp/',
# Or /dev/zero
'^/dev/zero',
# Or /dev/pts (used by gpm)
'^/dev/pts/',
# Or /usr/lib/locale
'^/usr/lib/locale/',
# Skip files from the user's home directories
# many processes hold temporafy files there
'^/home/',
# Skip automatically generated files
'^.*icon-theme.cache',
# Skip font files
'^/var/cache/fontconfig/',
# Skip Nagios Spool
'^/var/lib/nagios3/spool/',
# Skip nagios spool files
'^/var/lib/nagios3/spool/checkresults/',
# Skip Postgresql files
'^/var/lib/postgresql/',
# Skip VDR lib files
'^/var/lib/vdr/',
# Skip Aio files found in MySQL servers
'^/[aio]',
# ignore files under /SYSV
'^/SYSV'
]
def __virtual__():
'''
Only run this module if the psutil python module is installed (package python-psutil).
'''
return HAS_PSUTIL
def _valid_deleted_file(path):
'''
Filters file path against unwanted directories and decides whether file is marked as deleted.
Returns:
True if file is desired deleted file, else False.
Args:
path: A string - path to file
'''
ret = False
if path.endswith(' (deleted)'):
ret = True
if re.compile(r"\(path inode=[0-9]+\)$").search(path):
ret = True
regex = re.compile("|".join(LIST_DIRS))
if regex.match(path):
ret = False
return ret
def _format_output(kernel_restart, packages, verbose, restartable, nonrestartable, restartservicecommands,
restartinitcommands):
'''
Formats the output of the restartcheck module.
Returns:
String - formatted output.
Args:
kernel_restart: indicates that newer kernel is instaled
packages: list of packages that should be restarted
verbose: enables extensive output
restartable: list of restartable packages
nonrestartable: list of non-restartable packages
restartservicecommands: list of commands to restart services
restartinitcommands: list of commands to restart init.d scripts
'''
if not verbose:
packages = restartable + nonrestartable
if kernel_restart:
packages.append('System restart required.')
return packages
else:
ret = ''
if kernel_restart:
ret = 'System restart required.\n\n'
if packages:
ret += "Found {0} processes using old versions of upgraded files.\n".format(len(packages))
ret += "These are the packages:\n"
if restartable:
ret += "Of these, {0} seem to contain systemd service definitions or init scripts " \
"which can be used to restart them:\n".format(len(restartable))
for package in restartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
if restartservicecommands:
ret += "\n\nThese are the systemd services:\n"
ret += '\n'.join(restartservicecommands)
if restartinitcommands:
ret += "\n\nThese are the initd scripts:\n"
ret += '\n'.join(restartinitcommands)
if nonrestartable:
ret += "\n\nThese processes {0} do not seem to have an associated init script " \
"to restart them:\n".format(len(nonrestartable))
for package in nonrestartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
return ret
def _kernel_versions_debian():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kernel_get_selections = __salt__['cmd.run']('dpkg --get-selections linux-image-*')
kernels = []
kernel_versions = []
for line in kernel_get_selections.splitlines():
kernels.append(line)
try:
kernel = kernels[-2]
except IndexError:
kernel = kernels[0]
kernel = kernel.rstrip('\t\tinstall')
kernel_get_version = __salt__['cmd.run']('apt-cache policy ' + kernel)
for line in kernel_get_version.splitlines():
if line.startswith(' Installed: '):
kernel_v = line.strip(' Installed: ')
kernel_versions.append(kernel_v)
break
if __grains__['os'] == 'Ubuntu':
kernel_v = kernel_versions[0].rsplit('.', 1)
kernel_ubuntu_generic = kernel_v[0] + '-generic #' + kernel_v[1]
kernel_ubuntu_lowlatency = kernel_v[0] + '-lowlatency #' + kernel_v[1]
kernel_versions.extend([kernel_ubuntu_generic, kernel_ubuntu_lowlatency])
return kernel_versions
def _kernel_versions_redhat():
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
kernel_get_last = __salt__['cmd.run']('rpm -q --last kernel')
kernels = []
kernel_versions = []
for line in kernel_get_last.splitlines():
if 'kernel-' in line:
kernels.append(line)
kernel = kernels[0].split(' ', 1)[0]
kernel = kernel.strip('kernel-')
kernel_versions.append(kernel)
return kernel_versions
def _kernel_versions_nilrt():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kver = None
def _get_kver_from_bin(kbin):
'''
Get kernel version from a binary image or None if detection fails
'''
kvregex = r'[0-9]+\.[0-9]+\.[0-9]+-rt\S+'
kernel_strings = __salt__['cmd.run']('strings {0}'.format(kbin))
re_result = re.search(kvregex, kernel_strings)
return None if re_result is None else re_result.group(0)
if __grains__.get('lsb_distrib_id') == 'nilrt':
if 'arm' in __grains__.get('cpuarch'):
# the kernel is inside a uboot created itb (FIT) image alongside the
# device tree, ramdisk and a bootscript. There is no package management
# or any other kind of versioning info, so we need to extract the itb.
itb_path = '/boot/linux_runmode.itb'
compressed_kernel = '/var/volatile/tmp/uImage.gz'
uncompressed_kernel = '/var/volatile/tmp/uImage'
__salt__['cmd.run']('dumpimage -i {0} -T flat_dt -p0 kernel -o {1}'
.format(itb_path, compressed_kernel))
__salt__['cmd.run']('gunzip -f {0}'.format(compressed_kernel))
kver = _get_kver_from_bin(uncompressed_kernel)
else:
# the kernel bzImage is copied to rootfs without package management or
# other versioning info.
kver = _get_kver_from_bin('/boot/runmode/bzImage')
else:
# kernels in newer NILRT's are installed via package management and
# have the version appended to the kernel image filename
if 'arm' in __grains__.get('cpuarch'):
kver = os.path.basename(os.readlink('/boot/uImage')).strip('uImage-')
else:
kver = os.path.basename(os.readlink('/boot/bzImage')).strip('bzImage-')
return [] if kver is None else [kver]
def _check_timeout(start_time, timeout):
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
timeout_milisec = timeout * 60000
if timeout_milisec < (int(round(time.time() * 1000)) - start_time):
raise salt.exceptions.TimeoutError('Timeout expired.')
def _file_changed_nilrt(full_filepath):
'''
Detect whether a file changed in an NILinuxRT system using md5sum and timestamp
files from a state directory.
Returns:
- False if md5sum/timestamp state files don't exist
- True/False depending if ``base_filename`` got modified/touched
'''
rs_state_dir = "/var/lib/salt/restartcheck_state"
base_filename = os.path.basename(full_filepath)
timestamp_file = os.path.join(rs_state_dir, '{0}.timestamp'.format(base_filename))
md5sum_file = os.path.join(rs_state_dir, '{0}.md5sum'.format(base_filename))
if not os.path.exists(timestamp_file) or not os.path.exists(md5sum_file):
return True
prev_timestamp = __salt__['file.read'](timestamp_file).rstrip()
# Need timestamp in seconds so floor it using int()
cur_timestamp = str(int(os.path.getmtime(full_filepath)))
if prev_timestamp != cur_timestamp:
return True
return bool(__salt__['cmd.retcode']('md5sum -cs {0}'.format(md5sum_file), output_loglevel="quiet"))
def _kernel_modules_changed_nilrt(kernelversion):
'''
Once a NILRT kernel module is inserted, it can't be rmmod so systems need
rebooting (some modules explicitly ask for reboots even on first install),
hence this functionality of determining if the module state got modified by
testing if depmod was run.
Returns:
- True/False depending if modules.dep got modified/touched
'''
if kernelversion is not None:
return _file_changed_nilrt('/lib/modules/{0}/modules.dep'.format(kernelversion))
return False
def _sysapi_changed_nilrt():
'''
Besides the normal Linux kernel driver interfaces, NILinuxRT-supported hardware features an
extensible, plugin-based device enumeration and configuration interface named "System API".
When an installed package is extending the API it is very hard to know all repercurssions and
actions to be taken, so reboot making sure all drivers are reloaded, hardware reinitialized,
daemons restarted, etc.
Returns:
- True/False depending if nisysapi .ini files got modified/touched
- False if no nisysapi .ini files exist
'''
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path) and _file_changed_nilrt(nisysapi_path):
return True
restartcheck_state_dir = '/var/lib/salt/restartcheck_state'
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
rs_count_file = '{0}/sysapi.conf.d.count'.format(restartcheck_state_dir)
if not os.path.exists(rs_count_file):
return True
with salt.utils.files.fopen(rs_count_file, 'r') as fcount:
current_nb_files = len(os.listdir(nisysapi_conf_d_path))
rs_stored_nb_files = int(fcount.read())
if current_nb_files != rs_stored_nb_files:
return True
for fexpert in os.listdir(nisysapi_conf_d_path):
if _file_changed_nilrt('{0}/{1}'.format(nisysapi_conf_d_path, fexpert)):
return True
return False
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def restartcheck(ignorelist=None, blacklist=None, excludepid=None, **kwargs):
'''
Analyzes files openeded by running processes and seeks for packages which need to be restarted.
Args:
ignorelist: string or list of packages to be ignored
blacklist: string or list of file paths to be ignored
excludepid: string or list of process IDs to be ignored
verbose: boolean, enables extensive output
timeout: int, timeout in minute
Returns:
Dict on error: { 'result': False, 'comment': '<reason>' }
String with checkrestart output if some package seems to need to be restarted or
if no packages need restarting.
.. versionadded:: 2015.8.3
CLI Example:
.. code-block:: bash
salt '*' restartcheck.restartcheck
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
start_time = int(round(time.time() * 1000))
kernel_restart = True
verbose = kwargs.pop('verbose', True)
timeout = kwargs.pop('timeout', 5)
if __grains__.get('os_family') == 'Debian':
cmd_pkg_query = 'dpkg-query --listfiles '
systemd_folder = '/lib/systemd/system/'
systemd = '/bin/systemd'
kernel_versions = _kernel_versions_debian()
elif __grains__.get('os_family') == 'RedHat':
cmd_pkg_query = 'repoquery -l '
systemd_folder = '/usr/lib/systemd/system/'
systemd = '/usr/bin/systemctl'
kernel_versions = _kernel_versions_redhat()
elif __grains__.get('os_family') == NILRT_FAMILY_NAME:
cmd_pkg_query = 'opkg files '
systemd = ''
kernel_versions = _kernel_versions_nilrt()
else:
return {'result': False, 'comment': 'Only available on Debian, Red Hat and NI Linux Real-Time based systems.'}
# Check kernel versions
kernel_current = __salt__['cmd.run']('uname -a')
for kernel in kernel_versions:
_check_timeout(start_time, timeout)
if kernel in kernel_current:
if __grains__.get('os_family') == 'NILinuxRT':
# Check kernel modules and hardware API's for version changes
# If a restartcheck=True event was previously witnessed, propagate it
if not _kernel_modules_changed_nilrt(kernel) and \
not _sysapi_changed_nilrt() and \
not __salt__['system.get_reboot_required_witnessed']():
kernel_restart = False
break
else:
kernel_restart = False
break
packages = {}
running_services = {}
restart_services = []
if ignorelist:
if not isinstance(ignorelist, list):
ignorelist = [ignorelist]
else:
ignorelist = ['screen', 'systemd']
if blacklist:
if not isinstance(blacklist, list):
blacklist = [blacklist]
else:
blacklist = []
if excludepid:
if not isinstance(excludepid, list):
excludepid = [excludepid]
else:
excludepid = []
for service in __salt__['service.get_running']():
_check_timeout(start_time, timeout)
service_show = __salt__['service.show'](service)
if 'ExecMainPID' in service_show:
running_services[service] = int(service_show['ExecMainPID'])
owners_cache = {}
for deleted_file in _deleted_files():
if deleted_file is False:
return {'result': False, 'comment': 'Could not get list of processes.'
' (Do you have root access?)'}
_check_timeout(start_time, timeout)
name, pid, path = deleted_file[0], deleted_file[1], deleted_file[2]
if path in blacklist or pid in excludepid:
continue
try:
readlink = os.readlink('/proc/{0}/exe'.format(pid))
except OSError:
excludepid.append(pid)
continue
try:
packagename = owners_cache[readlink]
except KeyError:
packagename = __salt__['pkg.owner'](readlink)
if not packagename:
packagename = name
owners_cache[readlink] = packagename
for running_service in running_services:
_check_timeout(start_time, timeout)
if running_service not in restart_services and pid == running_services[running_service]:
if packagename and packagename not in ignorelist:
restart_services.append(running_service)
name = running_service
if packagename and packagename not in ignorelist:
program = '\t' + six.text_type(pid) + ' ' + readlink + ' (file: ' + six.text_type(path) + ')'
if packagename not in packages:
packages[packagename] = {'initscripts': [], 'systemdservice': [], 'processes': [program],
'process_name': name}
else:
if program not in packages[packagename]['processes']:
packages[packagename]['processes'].append(program)
if not packages and not kernel_restart:
return 'No packages seem to need to be restarted.'
for package in packages:
_check_timeout(start_time, timeout)
cmd = cmd_pkg_query + package
paths = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
while True:
_check_timeout(start_time, timeout)
line = salt.utils.stringutils.to_unicode(paths.stdout.readline())
if not line:
break
pth = line[:-1]
if pth.startswith('/etc/init.d/') and not pth.endswith('.sh'):
packages[package]['initscripts'].append(pth[12:])
if os.path.exists(systemd) and pth.startswith(systemd_folder) and pth.endswith('.service') and \
pth.find('.wants') == -1:
is_oneshot = False
try:
servicefile = salt.utils.files.fopen(pth) # pylint: disable=resource-leakage
except IOError:
continue
sysfold_len = len(systemd_folder)
for line in servicefile.readlines():
line = salt.utils.stringutils.to_unicode(line)
if line.find('Type=oneshot') > 0:
# scripts that does a single job and then exit
is_oneshot = True
continue
servicefile.close()
if not is_oneshot:
packages[package]['systemdservice'].append(pth[sysfold_len:])
sys.stdout.flush()
paths.stdout.close()
# Alternatively, find init.d script or service that match the process name
for package in packages:
_check_timeout(start_time, timeout)
if not packages[package]['systemdservice'] and not packages[package]['initscripts']:
service = __salt__['service.available'](packages[package]['process_name'])
if service:
if os.path.exists('/etc/init.d/' + packages[package]['process_name']):
packages[package]['initscripts'].append(packages[package]['process_name'])
else:
packages[package]['systemdservice'].append(packages[package]['process_name'])
restartable = []
nonrestartable = []
restartinitcommands = []
restartservicecommands = []
for package in packages:
_check_timeout(start_time, timeout)
if packages[package]['initscripts']:
restartable.append(package)
restartinitcommands.extend(['service ' + s + ' restart' for s in packages[package]['initscripts']])
elif packages[package]['systemdservice']:
restartable.append(package)
restartservicecommands.extend(['systemctl restart ' + s for s in packages[package]['systemdservice']])
else:
nonrestartable.append(package)
if packages[package]['process_name'] in restart_services:
restart_services.remove(packages[package]['process_name'])
for restart_service in restart_services:
_check_timeout(start_time, timeout)
restartservicecommands.extend(['systemctl restart ' + restart_service])
ret = _format_output(kernel_restart, packages, verbose, restartable, nonrestartable,
restartservicecommands, restartinitcommands)
return ret
|
saltstack/salt
|
salt/modules/restartcheck.py
|
_format_output
|
python
|
def _format_output(kernel_restart, packages, verbose, restartable, nonrestartable, restartservicecommands,
restartinitcommands):
'''
Formats the output of the restartcheck module.
Returns:
String - formatted output.
Args:
kernel_restart: indicates that newer kernel is instaled
packages: list of packages that should be restarted
verbose: enables extensive output
restartable: list of restartable packages
nonrestartable: list of non-restartable packages
restartservicecommands: list of commands to restart services
restartinitcommands: list of commands to restart init.d scripts
'''
if not verbose:
packages = restartable + nonrestartable
if kernel_restart:
packages.append('System restart required.')
return packages
else:
ret = ''
if kernel_restart:
ret = 'System restart required.\n\n'
if packages:
ret += "Found {0} processes using old versions of upgraded files.\n".format(len(packages))
ret += "These are the packages:\n"
if restartable:
ret += "Of these, {0} seem to contain systemd service definitions or init scripts " \
"which can be used to restart them:\n".format(len(restartable))
for package in restartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
if restartservicecommands:
ret += "\n\nThese are the systemd services:\n"
ret += '\n'.join(restartservicecommands)
if restartinitcommands:
ret += "\n\nThese are the initd scripts:\n"
ret += '\n'.join(restartinitcommands)
if nonrestartable:
ret += "\n\nThese processes {0} do not seem to have an associated init script " \
"to restart them:\n".format(len(nonrestartable))
for package in nonrestartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
return ret
|
Formats the output of the restartcheck module.
Returns:
String - formatted output.
Args:
kernel_restart: indicates that newer kernel is instaled
packages: list of packages that should be restarted
verbose: enables extensive output
restartable: list of restartable packages
nonrestartable: list of non-restartable packages
restartservicecommands: list of commands to restart services
restartinitcommands: list of commands to restart init.d scripts
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/restartcheck.py#L185-L240
| null |
# -*- coding: utf-8 -*-
'''
checkrestart functionality for Debian and Red Hat Based systems
Identifies services (processes) that are linked against deleted files (for example after downloading an updated
binary of a shared library).
Based on checkrestart script from debian-goodies (written by Matt Zimmerman for the Debian GNU/Linux distribution,
https://packages.debian.org/debian-goodies) and psdel by Sam Morris.
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import subprocess
import sys
import time
# Import salt libs
import salt.exceptions
import salt.utils.args
import salt.utils.files
import salt.utils.path
# Import 3rd partylibs
from salt.ext import six
NILRT_FAMILY_NAME = 'NILinuxRT'
HAS_PSUTIL = False
try:
import psutil
HAS_PSUTIL = True
except ImportError:
pass
LIST_DIRS = [
# We don't care about log files
'^/var/log/',
'^/var/local/log/',
# Or about files under temporary locations
'^/var/run/',
'^/var/local/run/',
# Or about files under /tmp
'^/tmp/',
# Or about files under /dev/shm
'^/dev/shm/',
# Or about files under /run
'^/run/',
# Or about files under /drm
'^/drm',
# Or about files under /var/tmp and /var/local/tmp
'^/var/tmp/',
'^/var/local/tmp/',
# Or /dev/zero
'^/dev/zero',
# Or /dev/pts (used by gpm)
'^/dev/pts/',
# Or /usr/lib/locale
'^/usr/lib/locale/',
# Skip files from the user's home directories
# many processes hold temporafy files there
'^/home/',
# Skip automatically generated files
'^.*icon-theme.cache',
# Skip font files
'^/var/cache/fontconfig/',
# Skip Nagios Spool
'^/var/lib/nagios3/spool/',
# Skip nagios spool files
'^/var/lib/nagios3/spool/checkresults/',
# Skip Postgresql files
'^/var/lib/postgresql/',
# Skip VDR lib files
'^/var/lib/vdr/',
# Skip Aio files found in MySQL servers
'^/[aio]',
# ignore files under /SYSV
'^/SYSV'
]
def __virtual__():
'''
Only run this module if the psutil python module is installed (package python-psutil).
'''
return HAS_PSUTIL
def _valid_deleted_file(path):
'''
Filters file path against unwanted directories and decides whether file is marked as deleted.
Returns:
True if file is desired deleted file, else False.
Args:
path: A string - path to file
'''
ret = False
if path.endswith(' (deleted)'):
ret = True
if re.compile(r"\(path inode=[0-9]+\)$").search(path):
ret = True
regex = re.compile("|".join(LIST_DIRS))
if regex.match(path):
ret = False
return ret
def _deleted_files():
'''
Iterates over /proc/PID/maps and /proc/PID/fd links and returns list of desired deleted files.
Returns:
List of deleted files to analyze, False on failure.
'''
deleted_files = []
for proc in psutil.process_iter(): # pylint: disable=too-many-nested-blocks
try:
pinfo = proc.as_dict(attrs=['pid', 'name'])
try:
with salt.utils.files.fopen('/proc/{0}/maps'.format(pinfo['pid'])) as maps: # pylint: disable=resource-leakage
dirpath = '/proc/' + six.text_type(pinfo['pid']) + '/fd/'
listdir = os.listdir(dirpath)
maplines = maps.readlines()
except (OSError, IOError):
yield False
# /proc/PID/maps
mapline = re.compile(r'^[\da-f]+-[\da-f]+ [r-][w-][x-][sp-] '
r'[\da-f]+ [\da-f]{2}:[\da-f]{2} (\d+) *(.+)( \(deleted\))?\n$')
for line in maplines:
line = salt.utils.stringutils.to_unicode(line)
matched = mapline.match(line)
if not matched:
continue
path = matched.group(2)
if not path:
continue
valid = _valid_deleted_file(path)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], path[0:-10])
if val not in deleted_files:
deleted_files.append(val)
yield val
# /proc/PID/fd
try:
for link in listdir:
path = dirpath + link
readlink = os.readlink(path)
filenames = []
if os.path.isfile(readlink):
filenames.append(readlink)
elif os.path.isdir(readlink) and readlink != '/':
for root, dummy_dirs, files in salt.utils.path.os_walk(readlink, followlinks=True):
for name in files:
filenames.append(os.path.join(root, name))
for filename in filenames:
valid = _valid_deleted_file(filename)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], filename)
if val not in deleted_files:
deleted_files.append(val)
yield val
except OSError:
pass
except psutil.NoSuchProcess:
pass
def _kernel_versions_debian():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kernel_get_selections = __salt__['cmd.run']('dpkg --get-selections linux-image-*')
kernels = []
kernel_versions = []
for line in kernel_get_selections.splitlines():
kernels.append(line)
try:
kernel = kernels[-2]
except IndexError:
kernel = kernels[0]
kernel = kernel.rstrip('\t\tinstall')
kernel_get_version = __salt__['cmd.run']('apt-cache policy ' + kernel)
for line in kernel_get_version.splitlines():
if line.startswith(' Installed: '):
kernel_v = line.strip(' Installed: ')
kernel_versions.append(kernel_v)
break
if __grains__['os'] == 'Ubuntu':
kernel_v = kernel_versions[0].rsplit('.', 1)
kernel_ubuntu_generic = kernel_v[0] + '-generic #' + kernel_v[1]
kernel_ubuntu_lowlatency = kernel_v[0] + '-lowlatency #' + kernel_v[1]
kernel_versions.extend([kernel_ubuntu_generic, kernel_ubuntu_lowlatency])
return kernel_versions
def _kernel_versions_redhat():
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
kernel_get_last = __salt__['cmd.run']('rpm -q --last kernel')
kernels = []
kernel_versions = []
for line in kernel_get_last.splitlines():
if 'kernel-' in line:
kernels.append(line)
kernel = kernels[0].split(' ', 1)[0]
kernel = kernel.strip('kernel-')
kernel_versions.append(kernel)
return kernel_versions
def _kernel_versions_nilrt():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kver = None
def _get_kver_from_bin(kbin):
'''
Get kernel version from a binary image or None if detection fails
'''
kvregex = r'[0-9]+\.[0-9]+\.[0-9]+-rt\S+'
kernel_strings = __salt__['cmd.run']('strings {0}'.format(kbin))
re_result = re.search(kvregex, kernel_strings)
return None if re_result is None else re_result.group(0)
if __grains__.get('lsb_distrib_id') == 'nilrt':
if 'arm' in __grains__.get('cpuarch'):
# the kernel is inside a uboot created itb (FIT) image alongside the
# device tree, ramdisk and a bootscript. There is no package management
# or any other kind of versioning info, so we need to extract the itb.
itb_path = '/boot/linux_runmode.itb'
compressed_kernel = '/var/volatile/tmp/uImage.gz'
uncompressed_kernel = '/var/volatile/tmp/uImage'
__salt__['cmd.run']('dumpimage -i {0} -T flat_dt -p0 kernel -o {1}'
.format(itb_path, compressed_kernel))
__salt__['cmd.run']('gunzip -f {0}'.format(compressed_kernel))
kver = _get_kver_from_bin(uncompressed_kernel)
else:
# the kernel bzImage is copied to rootfs without package management or
# other versioning info.
kver = _get_kver_from_bin('/boot/runmode/bzImage')
else:
# kernels in newer NILRT's are installed via package management and
# have the version appended to the kernel image filename
if 'arm' in __grains__.get('cpuarch'):
kver = os.path.basename(os.readlink('/boot/uImage')).strip('uImage-')
else:
kver = os.path.basename(os.readlink('/boot/bzImage')).strip('bzImage-')
return [] if kver is None else [kver]
def _check_timeout(start_time, timeout):
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
timeout_milisec = timeout * 60000
if timeout_milisec < (int(round(time.time() * 1000)) - start_time):
raise salt.exceptions.TimeoutError('Timeout expired.')
def _file_changed_nilrt(full_filepath):
'''
Detect whether a file changed in an NILinuxRT system using md5sum and timestamp
files from a state directory.
Returns:
- False if md5sum/timestamp state files don't exist
- True/False depending if ``base_filename`` got modified/touched
'''
rs_state_dir = "/var/lib/salt/restartcheck_state"
base_filename = os.path.basename(full_filepath)
timestamp_file = os.path.join(rs_state_dir, '{0}.timestamp'.format(base_filename))
md5sum_file = os.path.join(rs_state_dir, '{0}.md5sum'.format(base_filename))
if not os.path.exists(timestamp_file) or not os.path.exists(md5sum_file):
return True
prev_timestamp = __salt__['file.read'](timestamp_file).rstrip()
# Need timestamp in seconds so floor it using int()
cur_timestamp = str(int(os.path.getmtime(full_filepath)))
if prev_timestamp != cur_timestamp:
return True
return bool(__salt__['cmd.retcode']('md5sum -cs {0}'.format(md5sum_file), output_loglevel="quiet"))
def _kernel_modules_changed_nilrt(kernelversion):
'''
Once a NILRT kernel module is inserted, it can't be rmmod so systems need
rebooting (some modules explicitly ask for reboots even on first install),
hence this functionality of determining if the module state got modified by
testing if depmod was run.
Returns:
- True/False depending if modules.dep got modified/touched
'''
if kernelversion is not None:
return _file_changed_nilrt('/lib/modules/{0}/modules.dep'.format(kernelversion))
return False
def _sysapi_changed_nilrt():
'''
Besides the normal Linux kernel driver interfaces, NILinuxRT-supported hardware features an
extensible, plugin-based device enumeration and configuration interface named "System API".
When an installed package is extending the API it is very hard to know all repercurssions and
actions to be taken, so reboot making sure all drivers are reloaded, hardware reinitialized,
daemons restarted, etc.
Returns:
- True/False depending if nisysapi .ini files got modified/touched
- False if no nisysapi .ini files exist
'''
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path) and _file_changed_nilrt(nisysapi_path):
return True
restartcheck_state_dir = '/var/lib/salt/restartcheck_state'
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
rs_count_file = '{0}/sysapi.conf.d.count'.format(restartcheck_state_dir)
if not os.path.exists(rs_count_file):
return True
with salt.utils.files.fopen(rs_count_file, 'r') as fcount:
current_nb_files = len(os.listdir(nisysapi_conf_d_path))
rs_stored_nb_files = int(fcount.read())
if current_nb_files != rs_stored_nb_files:
return True
for fexpert in os.listdir(nisysapi_conf_d_path):
if _file_changed_nilrt('{0}/{1}'.format(nisysapi_conf_d_path, fexpert)):
return True
return False
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def restartcheck(ignorelist=None, blacklist=None, excludepid=None, **kwargs):
'''
Analyzes files openeded by running processes and seeks for packages which need to be restarted.
Args:
ignorelist: string or list of packages to be ignored
blacklist: string or list of file paths to be ignored
excludepid: string or list of process IDs to be ignored
verbose: boolean, enables extensive output
timeout: int, timeout in minute
Returns:
Dict on error: { 'result': False, 'comment': '<reason>' }
String with checkrestart output if some package seems to need to be restarted or
if no packages need restarting.
.. versionadded:: 2015.8.3
CLI Example:
.. code-block:: bash
salt '*' restartcheck.restartcheck
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
start_time = int(round(time.time() * 1000))
kernel_restart = True
verbose = kwargs.pop('verbose', True)
timeout = kwargs.pop('timeout', 5)
if __grains__.get('os_family') == 'Debian':
cmd_pkg_query = 'dpkg-query --listfiles '
systemd_folder = '/lib/systemd/system/'
systemd = '/bin/systemd'
kernel_versions = _kernel_versions_debian()
elif __grains__.get('os_family') == 'RedHat':
cmd_pkg_query = 'repoquery -l '
systemd_folder = '/usr/lib/systemd/system/'
systemd = '/usr/bin/systemctl'
kernel_versions = _kernel_versions_redhat()
elif __grains__.get('os_family') == NILRT_FAMILY_NAME:
cmd_pkg_query = 'opkg files '
systemd = ''
kernel_versions = _kernel_versions_nilrt()
else:
return {'result': False, 'comment': 'Only available on Debian, Red Hat and NI Linux Real-Time based systems.'}
# Check kernel versions
kernel_current = __salt__['cmd.run']('uname -a')
for kernel in kernel_versions:
_check_timeout(start_time, timeout)
if kernel in kernel_current:
if __grains__.get('os_family') == 'NILinuxRT':
# Check kernel modules and hardware API's for version changes
# If a restartcheck=True event was previously witnessed, propagate it
if not _kernel_modules_changed_nilrt(kernel) and \
not _sysapi_changed_nilrt() and \
not __salt__['system.get_reboot_required_witnessed']():
kernel_restart = False
break
else:
kernel_restart = False
break
packages = {}
running_services = {}
restart_services = []
if ignorelist:
if not isinstance(ignorelist, list):
ignorelist = [ignorelist]
else:
ignorelist = ['screen', 'systemd']
if blacklist:
if not isinstance(blacklist, list):
blacklist = [blacklist]
else:
blacklist = []
if excludepid:
if not isinstance(excludepid, list):
excludepid = [excludepid]
else:
excludepid = []
for service in __salt__['service.get_running']():
_check_timeout(start_time, timeout)
service_show = __salt__['service.show'](service)
if 'ExecMainPID' in service_show:
running_services[service] = int(service_show['ExecMainPID'])
owners_cache = {}
for deleted_file in _deleted_files():
if deleted_file is False:
return {'result': False, 'comment': 'Could not get list of processes.'
' (Do you have root access?)'}
_check_timeout(start_time, timeout)
name, pid, path = deleted_file[0], deleted_file[1], deleted_file[2]
if path in blacklist or pid in excludepid:
continue
try:
readlink = os.readlink('/proc/{0}/exe'.format(pid))
except OSError:
excludepid.append(pid)
continue
try:
packagename = owners_cache[readlink]
except KeyError:
packagename = __salt__['pkg.owner'](readlink)
if not packagename:
packagename = name
owners_cache[readlink] = packagename
for running_service in running_services:
_check_timeout(start_time, timeout)
if running_service not in restart_services and pid == running_services[running_service]:
if packagename and packagename not in ignorelist:
restart_services.append(running_service)
name = running_service
if packagename and packagename not in ignorelist:
program = '\t' + six.text_type(pid) + ' ' + readlink + ' (file: ' + six.text_type(path) + ')'
if packagename not in packages:
packages[packagename] = {'initscripts': [], 'systemdservice': [], 'processes': [program],
'process_name': name}
else:
if program not in packages[packagename]['processes']:
packages[packagename]['processes'].append(program)
if not packages and not kernel_restart:
return 'No packages seem to need to be restarted.'
for package in packages:
_check_timeout(start_time, timeout)
cmd = cmd_pkg_query + package
paths = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
while True:
_check_timeout(start_time, timeout)
line = salt.utils.stringutils.to_unicode(paths.stdout.readline())
if not line:
break
pth = line[:-1]
if pth.startswith('/etc/init.d/') and not pth.endswith('.sh'):
packages[package]['initscripts'].append(pth[12:])
if os.path.exists(systemd) and pth.startswith(systemd_folder) and pth.endswith('.service') and \
pth.find('.wants') == -1:
is_oneshot = False
try:
servicefile = salt.utils.files.fopen(pth) # pylint: disable=resource-leakage
except IOError:
continue
sysfold_len = len(systemd_folder)
for line in servicefile.readlines():
line = salt.utils.stringutils.to_unicode(line)
if line.find('Type=oneshot') > 0:
# scripts that does a single job and then exit
is_oneshot = True
continue
servicefile.close()
if not is_oneshot:
packages[package]['systemdservice'].append(pth[sysfold_len:])
sys.stdout.flush()
paths.stdout.close()
# Alternatively, find init.d script or service that match the process name
for package in packages:
_check_timeout(start_time, timeout)
if not packages[package]['systemdservice'] and not packages[package]['initscripts']:
service = __salt__['service.available'](packages[package]['process_name'])
if service:
if os.path.exists('/etc/init.d/' + packages[package]['process_name']):
packages[package]['initscripts'].append(packages[package]['process_name'])
else:
packages[package]['systemdservice'].append(packages[package]['process_name'])
restartable = []
nonrestartable = []
restartinitcommands = []
restartservicecommands = []
for package in packages:
_check_timeout(start_time, timeout)
if packages[package]['initscripts']:
restartable.append(package)
restartinitcommands.extend(['service ' + s + ' restart' for s in packages[package]['initscripts']])
elif packages[package]['systemdservice']:
restartable.append(package)
restartservicecommands.extend(['systemctl restart ' + s for s in packages[package]['systemdservice']])
else:
nonrestartable.append(package)
if packages[package]['process_name'] in restart_services:
restart_services.remove(packages[package]['process_name'])
for restart_service in restart_services:
_check_timeout(start_time, timeout)
restartservicecommands.extend(['systemctl restart ' + restart_service])
ret = _format_output(kernel_restart, packages, verbose, restartable, nonrestartable,
restartservicecommands, restartinitcommands)
return ret
|
saltstack/salt
|
salt/modules/restartcheck.py
|
_kernel_versions_debian
|
python
|
def _kernel_versions_debian():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kernel_get_selections = __salt__['cmd.run']('dpkg --get-selections linux-image-*')
kernels = []
kernel_versions = []
for line in kernel_get_selections.splitlines():
kernels.append(line)
try:
kernel = kernels[-2]
except IndexError:
kernel = kernels[0]
kernel = kernel.rstrip('\t\tinstall')
kernel_get_version = __salt__['cmd.run']('apt-cache policy ' + kernel)
for line in kernel_get_version.splitlines():
if line.startswith(' Installed: '):
kernel_v = line.strip(' Installed: ')
kernel_versions.append(kernel_v)
break
if __grains__['os'] == 'Ubuntu':
kernel_v = kernel_versions[0].rsplit('.', 1)
kernel_ubuntu_generic = kernel_v[0] + '-generic #' + kernel_v[1]
kernel_ubuntu_lowlatency = kernel_v[0] + '-lowlatency #' + kernel_v[1]
kernel_versions.extend([kernel_ubuntu_generic, kernel_ubuntu_lowlatency])
return kernel_versions
|
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/restartcheck.py#L243-L278
| null |
# -*- coding: utf-8 -*-
'''
checkrestart functionality for Debian and Red Hat Based systems
Identifies services (processes) that are linked against deleted files (for example after downloading an updated
binary of a shared library).
Based on checkrestart script from debian-goodies (written by Matt Zimmerman for the Debian GNU/Linux distribution,
https://packages.debian.org/debian-goodies) and psdel by Sam Morris.
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import subprocess
import sys
import time
# Import salt libs
import salt.exceptions
import salt.utils.args
import salt.utils.files
import salt.utils.path
# Import 3rd partylibs
from salt.ext import six
NILRT_FAMILY_NAME = 'NILinuxRT'
HAS_PSUTIL = False
try:
import psutil
HAS_PSUTIL = True
except ImportError:
pass
LIST_DIRS = [
# We don't care about log files
'^/var/log/',
'^/var/local/log/',
# Or about files under temporary locations
'^/var/run/',
'^/var/local/run/',
# Or about files under /tmp
'^/tmp/',
# Or about files under /dev/shm
'^/dev/shm/',
# Or about files under /run
'^/run/',
# Or about files under /drm
'^/drm',
# Or about files under /var/tmp and /var/local/tmp
'^/var/tmp/',
'^/var/local/tmp/',
# Or /dev/zero
'^/dev/zero',
# Or /dev/pts (used by gpm)
'^/dev/pts/',
# Or /usr/lib/locale
'^/usr/lib/locale/',
# Skip files from the user's home directories
# many processes hold temporafy files there
'^/home/',
# Skip automatically generated files
'^.*icon-theme.cache',
# Skip font files
'^/var/cache/fontconfig/',
# Skip Nagios Spool
'^/var/lib/nagios3/spool/',
# Skip nagios spool files
'^/var/lib/nagios3/spool/checkresults/',
# Skip Postgresql files
'^/var/lib/postgresql/',
# Skip VDR lib files
'^/var/lib/vdr/',
# Skip Aio files found in MySQL servers
'^/[aio]',
# ignore files under /SYSV
'^/SYSV'
]
def __virtual__():
'''
Only run this module if the psutil python module is installed (package python-psutil).
'''
return HAS_PSUTIL
def _valid_deleted_file(path):
'''
Filters file path against unwanted directories and decides whether file is marked as deleted.
Returns:
True if file is desired deleted file, else False.
Args:
path: A string - path to file
'''
ret = False
if path.endswith(' (deleted)'):
ret = True
if re.compile(r"\(path inode=[0-9]+\)$").search(path):
ret = True
regex = re.compile("|".join(LIST_DIRS))
if regex.match(path):
ret = False
return ret
def _deleted_files():
'''
Iterates over /proc/PID/maps and /proc/PID/fd links and returns list of desired deleted files.
Returns:
List of deleted files to analyze, False on failure.
'''
deleted_files = []
for proc in psutil.process_iter(): # pylint: disable=too-many-nested-blocks
try:
pinfo = proc.as_dict(attrs=['pid', 'name'])
try:
with salt.utils.files.fopen('/proc/{0}/maps'.format(pinfo['pid'])) as maps: # pylint: disable=resource-leakage
dirpath = '/proc/' + six.text_type(pinfo['pid']) + '/fd/'
listdir = os.listdir(dirpath)
maplines = maps.readlines()
except (OSError, IOError):
yield False
# /proc/PID/maps
mapline = re.compile(r'^[\da-f]+-[\da-f]+ [r-][w-][x-][sp-] '
r'[\da-f]+ [\da-f]{2}:[\da-f]{2} (\d+) *(.+)( \(deleted\))?\n$')
for line in maplines:
line = salt.utils.stringutils.to_unicode(line)
matched = mapline.match(line)
if not matched:
continue
path = matched.group(2)
if not path:
continue
valid = _valid_deleted_file(path)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], path[0:-10])
if val not in deleted_files:
deleted_files.append(val)
yield val
# /proc/PID/fd
try:
for link in listdir:
path = dirpath + link
readlink = os.readlink(path)
filenames = []
if os.path.isfile(readlink):
filenames.append(readlink)
elif os.path.isdir(readlink) and readlink != '/':
for root, dummy_dirs, files in salt.utils.path.os_walk(readlink, followlinks=True):
for name in files:
filenames.append(os.path.join(root, name))
for filename in filenames:
valid = _valid_deleted_file(filename)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], filename)
if val not in deleted_files:
deleted_files.append(val)
yield val
except OSError:
pass
except psutil.NoSuchProcess:
pass
def _format_output(kernel_restart, packages, verbose, restartable, nonrestartable, restartservicecommands,
restartinitcommands):
'''
Formats the output of the restartcheck module.
Returns:
String - formatted output.
Args:
kernel_restart: indicates that newer kernel is instaled
packages: list of packages that should be restarted
verbose: enables extensive output
restartable: list of restartable packages
nonrestartable: list of non-restartable packages
restartservicecommands: list of commands to restart services
restartinitcommands: list of commands to restart init.d scripts
'''
if not verbose:
packages = restartable + nonrestartable
if kernel_restart:
packages.append('System restart required.')
return packages
else:
ret = ''
if kernel_restart:
ret = 'System restart required.\n\n'
if packages:
ret += "Found {0} processes using old versions of upgraded files.\n".format(len(packages))
ret += "These are the packages:\n"
if restartable:
ret += "Of these, {0} seem to contain systemd service definitions or init scripts " \
"which can be used to restart them:\n".format(len(restartable))
for package in restartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
if restartservicecommands:
ret += "\n\nThese are the systemd services:\n"
ret += '\n'.join(restartservicecommands)
if restartinitcommands:
ret += "\n\nThese are the initd scripts:\n"
ret += '\n'.join(restartinitcommands)
if nonrestartable:
ret += "\n\nThese processes {0} do not seem to have an associated init script " \
"to restart them:\n".format(len(nonrestartable))
for package in nonrestartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
return ret
def _kernel_versions_redhat():
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
kernel_get_last = __salt__['cmd.run']('rpm -q --last kernel')
kernels = []
kernel_versions = []
for line in kernel_get_last.splitlines():
if 'kernel-' in line:
kernels.append(line)
kernel = kernels[0].split(' ', 1)[0]
kernel = kernel.strip('kernel-')
kernel_versions.append(kernel)
return kernel_versions
def _kernel_versions_nilrt():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kver = None
def _get_kver_from_bin(kbin):
'''
Get kernel version from a binary image or None if detection fails
'''
kvregex = r'[0-9]+\.[0-9]+\.[0-9]+-rt\S+'
kernel_strings = __salt__['cmd.run']('strings {0}'.format(kbin))
re_result = re.search(kvregex, kernel_strings)
return None if re_result is None else re_result.group(0)
if __grains__.get('lsb_distrib_id') == 'nilrt':
if 'arm' in __grains__.get('cpuarch'):
# the kernel is inside a uboot created itb (FIT) image alongside the
# device tree, ramdisk and a bootscript. There is no package management
# or any other kind of versioning info, so we need to extract the itb.
itb_path = '/boot/linux_runmode.itb'
compressed_kernel = '/var/volatile/tmp/uImage.gz'
uncompressed_kernel = '/var/volatile/tmp/uImage'
__salt__['cmd.run']('dumpimage -i {0} -T flat_dt -p0 kernel -o {1}'
.format(itb_path, compressed_kernel))
__salt__['cmd.run']('gunzip -f {0}'.format(compressed_kernel))
kver = _get_kver_from_bin(uncompressed_kernel)
else:
# the kernel bzImage is copied to rootfs without package management or
# other versioning info.
kver = _get_kver_from_bin('/boot/runmode/bzImage')
else:
# kernels in newer NILRT's are installed via package management and
# have the version appended to the kernel image filename
if 'arm' in __grains__.get('cpuarch'):
kver = os.path.basename(os.readlink('/boot/uImage')).strip('uImage-')
else:
kver = os.path.basename(os.readlink('/boot/bzImage')).strip('bzImage-')
return [] if kver is None else [kver]
def _check_timeout(start_time, timeout):
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
timeout_milisec = timeout * 60000
if timeout_milisec < (int(round(time.time() * 1000)) - start_time):
raise salt.exceptions.TimeoutError('Timeout expired.')
def _file_changed_nilrt(full_filepath):
'''
Detect whether a file changed in an NILinuxRT system using md5sum and timestamp
files from a state directory.
Returns:
- False if md5sum/timestamp state files don't exist
- True/False depending if ``base_filename`` got modified/touched
'''
rs_state_dir = "/var/lib/salt/restartcheck_state"
base_filename = os.path.basename(full_filepath)
timestamp_file = os.path.join(rs_state_dir, '{0}.timestamp'.format(base_filename))
md5sum_file = os.path.join(rs_state_dir, '{0}.md5sum'.format(base_filename))
if not os.path.exists(timestamp_file) or not os.path.exists(md5sum_file):
return True
prev_timestamp = __salt__['file.read'](timestamp_file).rstrip()
# Need timestamp in seconds so floor it using int()
cur_timestamp = str(int(os.path.getmtime(full_filepath)))
if prev_timestamp != cur_timestamp:
return True
return bool(__salt__['cmd.retcode']('md5sum -cs {0}'.format(md5sum_file), output_loglevel="quiet"))
def _kernel_modules_changed_nilrt(kernelversion):
'''
Once a NILRT kernel module is inserted, it can't be rmmod so systems need
rebooting (some modules explicitly ask for reboots even on first install),
hence this functionality of determining if the module state got modified by
testing if depmod was run.
Returns:
- True/False depending if modules.dep got modified/touched
'''
if kernelversion is not None:
return _file_changed_nilrt('/lib/modules/{0}/modules.dep'.format(kernelversion))
return False
def _sysapi_changed_nilrt():
'''
Besides the normal Linux kernel driver interfaces, NILinuxRT-supported hardware features an
extensible, plugin-based device enumeration and configuration interface named "System API".
When an installed package is extending the API it is very hard to know all repercurssions and
actions to be taken, so reboot making sure all drivers are reloaded, hardware reinitialized,
daemons restarted, etc.
Returns:
- True/False depending if nisysapi .ini files got modified/touched
- False if no nisysapi .ini files exist
'''
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path) and _file_changed_nilrt(nisysapi_path):
return True
restartcheck_state_dir = '/var/lib/salt/restartcheck_state'
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
rs_count_file = '{0}/sysapi.conf.d.count'.format(restartcheck_state_dir)
if not os.path.exists(rs_count_file):
return True
with salt.utils.files.fopen(rs_count_file, 'r') as fcount:
current_nb_files = len(os.listdir(nisysapi_conf_d_path))
rs_stored_nb_files = int(fcount.read())
if current_nb_files != rs_stored_nb_files:
return True
for fexpert in os.listdir(nisysapi_conf_d_path):
if _file_changed_nilrt('{0}/{1}'.format(nisysapi_conf_d_path, fexpert)):
return True
return False
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def restartcheck(ignorelist=None, blacklist=None, excludepid=None, **kwargs):
'''
Analyzes files openeded by running processes and seeks for packages which need to be restarted.
Args:
ignorelist: string or list of packages to be ignored
blacklist: string or list of file paths to be ignored
excludepid: string or list of process IDs to be ignored
verbose: boolean, enables extensive output
timeout: int, timeout in minute
Returns:
Dict on error: { 'result': False, 'comment': '<reason>' }
String with checkrestart output if some package seems to need to be restarted or
if no packages need restarting.
.. versionadded:: 2015.8.3
CLI Example:
.. code-block:: bash
salt '*' restartcheck.restartcheck
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
start_time = int(round(time.time() * 1000))
kernel_restart = True
verbose = kwargs.pop('verbose', True)
timeout = kwargs.pop('timeout', 5)
if __grains__.get('os_family') == 'Debian':
cmd_pkg_query = 'dpkg-query --listfiles '
systemd_folder = '/lib/systemd/system/'
systemd = '/bin/systemd'
kernel_versions = _kernel_versions_debian()
elif __grains__.get('os_family') == 'RedHat':
cmd_pkg_query = 'repoquery -l '
systemd_folder = '/usr/lib/systemd/system/'
systemd = '/usr/bin/systemctl'
kernel_versions = _kernel_versions_redhat()
elif __grains__.get('os_family') == NILRT_FAMILY_NAME:
cmd_pkg_query = 'opkg files '
systemd = ''
kernel_versions = _kernel_versions_nilrt()
else:
return {'result': False, 'comment': 'Only available on Debian, Red Hat and NI Linux Real-Time based systems.'}
# Check kernel versions
kernel_current = __salt__['cmd.run']('uname -a')
for kernel in kernel_versions:
_check_timeout(start_time, timeout)
if kernel in kernel_current:
if __grains__.get('os_family') == 'NILinuxRT':
# Check kernel modules and hardware API's for version changes
# If a restartcheck=True event was previously witnessed, propagate it
if not _kernel_modules_changed_nilrt(kernel) and \
not _sysapi_changed_nilrt() and \
not __salt__['system.get_reboot_required_witnessed']():
kernel_restart = False
break
else:
kernel_restart = False
break
packages = {}
running_services = {}
restart_services = []
if ignorelist:
if not isinstance(ignorelist, list):
ignorelist = [ignorelist]
else:
ignorelist = ['screen', 'systemd']
if blacklist:
if not isinstance(blacklist, list):
blacklist = [blacklist]
else:
blacklist = []
if excludepid:
if not isinstance(excludepid, list):
excludepid = [excludepid]
else:
excludepid = []
for service in __salt__['service.get_running']():
_check_timeout(start_time, timeout)
service_show = __salt__['service.show'](service)
if 'ExecMainPID' in service_show:
running_services[service] = int(service_show['ExecMainPID'])
owners_cache = {}
for deleted_file in _deleted_files():
if deleted_file is False:
return {'result': False, 'comment': 'Could not get list of processes.'
' (Do you have root access?)'}
_check_timeout(start_time, timeout)
name, pid, path = deleted_file[0], deleted_file[1], deleted_file[2]
if path in blacklist or pid in excludepid:
continue
try:
readlink = os.readlink('/proc/{0}/exe'.format(pid))
except OSError:
excludepid.append(pid)
continue
try:
packagename = owners_cache[readlink]
except KeyError:
packagename = __salt__['pkg.owner'](readlink)
if not packagename:
packagename = name
owners_cache[readlink] = packagename
for running_service in running_services:
_check_timeout(start_time, timeout)
if running_service not in restart_services and pid == running_services[running_service]:
if packagename and packagename not in ignorelist:
restart_services.append(running_service)
name = running_service
if packagename and packagename not in ignorelist:
program = '\t' + six.text_type(pid) + ' ' + readlink + ' (file: ' + six.text_type(path) + ')'
if packagename not in packages:
packages[packagename] = {'initscripts': [], 'systemdservice': [], 'processes': [program],
'process_name': name}
else:
if program not in packages[packagename]['processes']:
packages[packagename]['processes'].append(program)
if not packages and not kernel_restart:
return 'No packages seem to need to be restarted.'
for package in packages:
_check_timeout(start_time, timeout)
cmd = cmd_pkg_query + package
paths = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
while True:
_check_timeout(start_time, timeout)
line = salt.utils.stringutils.to_unicode(paths.stdout.readline())
if not line:
break
pth = line[:-1]
if pth.startswith('/etc/init.d/') and not pth.endswith('.sh'):
packages[package]['initscripts'].append(pth[12:])
if os.path.exists(systemd) and pth.startswith(systemd_folder) and pth.endswith('.service') and \
pth.find('.wants') == -1:
is_oneshot = False
try:
servicefile = salt.utils.files.fopen(pth) # pylint: disable=resource-leakage
except IOError:
continue
sysfold_len = len(systemd_folder)
for line in servicefile.readlines():
line = salt.utils.stringutils.to_unicode(line)
if line.find('Type=oneshot') > 0:
# scripts that does a single job and then exit
is_oneshot = True
continue
servicefile.close()
if not is_oneshot:
packages[package]['systemdservice'].append(pth[sysfold_len:])
sys.stdout.flush()
paths.stdout.close()
# Alternatively, find init.d script or service that match the process name
for package in packages:
_check_timeout(start_time, timeout)
if not packages[package]['systemdservice'] and not packages[package]['initscripts']:
service = __salt__['service.available'](packages[package]['process_name'])
if service:
if os.path.exists('/etc/init.d/' + packages[package]['process_name']):
packages[package]['initscripts'].append(packages[package]['process_name'])
else:
packages[package]['systemdservice'].append(packages[package]['process_name'])
restartable = []
nonrestartable = []
restartinitcommands = []
restartservicecommands = []
for package in packages:
_check_timeout(start_time, timeout)
if packages[package]['initscripts']:
restartable.append(package)
restartinitcommands.extend(['service ' + s + ' restart' for s in packages[package]['initscripts']])
elif packages[package]['systemdservice']:
restartable.append(package)
restartservicecommands.extend(['systemctl restart ' + s for s in packages[package]['systemdservice']])
else:
nonrestartable.append(package)
if packages[package]['process_name'] in restart_services:
restart_services.remove(packages[package]['process_name'])
for restart_service in restart_services:
_check_timeout(start_time, timeout)
restartservicecommands.extend(['systemctl restart ' + restart_service])
ret = _format_output(kernel_restart, packages, verbose, restartable, nonrestartable,
restartservicecommands, restartinitcommands)
return ret
|
saltstack/salt
|
salt/modules/restartcheck.py
|
_kernel_versions_redhat
|
python
|
def _kernel_versions_redhat():
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
kernel_get_last = __salt__['cmd.run']('rpm -q --last kernel')
kernels = []
kernel_versions = []
for line in kernel_get_last.splitlines():
if 'kernel-' in line:
kernels.append(line)
kernel = kernels[0].split(' ', 1)[0]
kernel = kernel.strip('kernel-')
kernel_versions.append(kernel)
return kernel_versions
|
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/restartcheck.py#L281-L299
| null |
# -*- coding: utf-8 -*-
'''
checkrestart functionality for Debian and Red Hat Based systems
Identifies services (processes) that are linked against deleted files (for example after downloading an updated
binary of a shared library).
Based on checkrestart script from debian-goodies (written by Matt Zimmerman for the Debian GNU/Linux distribution,
https://packages.debian.org/debian-goodies) and psdel by Sam Morris.
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import subprocess
import sys
import time
# Import salt libs
import salt.exceptions
import salt.utils.args
import salt.utils.files
import salt.utils.path
# Import 3rd partylibs
from salt.ext import six
NILRT_FAMILY_NAME = 'NILinuxRT'
HAS_PSUTIL = False
try:
import psutil
HAS_PSUTIL = True
except ImportError:
pass
LIST_DIRS = [
# We don't care about log files
'^/var/log/',
'^/var/local/log/',
# Or about files under temporary locations
'^/var/run/',
'^/var/local/run/',
# Or about files under /tmp
'^/tmp/',
# Or about files under /dev/shm
'^/dev/shm/',
# Or about files under /run
'^/run/',
# Or about files under /drm
'^/drm',
# Or about files under /var/tmp and /var/local/tmp
'^/var/tmp/',
'^/var/local/tmp/',
# Or /dev/zero
'^/dev/zero',
# Or /dev/pts (used by gpm)
'^/dev/pts/',
# Or /usr/lib/locale
'^/usr/lib/locale/',
# Skip files from the user's home directories
# many processes hold temporafy files there
'^/home/',
# Skip automatically generated files
'^.*icon-theme.cache',
# Skip font files
'^/var/cache/fontconfig/',
# Skip Nagios Spool
'^/var/lib/nagios3/spool/',
# Skip nagios spool files
'^/var/lib/nagios3/spool/checkresults/',
# Skip Postgresql files
'^/var/lib/postgresql/',
# Skip VDR lib files
'^/var/lib/vdr/',
# Skip Aio files found in MySQL servers
'^/[aio]',
# ignore files under /SYSV
'^/SYSV'
]
def __virtual__():
'''
Only run this module if the psutil python module is installed (package python-psutil).
'''
return HAS_PSUTIL
def _valid_deleted_file(path):
'''
Filters file path against unwanted directories and decides whether file is marked as deleted.
Returns:
True if file is desired deleted file, else False.
Args:
path: A string - path to file
'''
ret = False
if path.endswith(' (deleted)'):
ret = True
if re.compile(r"\(path inode=[0-9]+\)$").search(path):
ret = True
regex = re.compile("|".join(LIST_DIRS))
if regex.match(path):
ret = False
return ret
def _deleted_files():
'''
Iterates over /proc/PID/maps and /proc/PID/fd links and returns list of desired deleted files.
Returns:
List of deleted files to analyze, False on failure.
'''
deleted_files = []
for proc in psutil.process_iter(): # pylint: disable=too-many-nested-blocks
try:
pinfo = proc.as_dict(attrs=['pid', 'name'])
try:
with salt.utils.files.fopen('/proc/{0}/maps'.format(pinfo['pid'])) as maps: # pylint: disable=resource-leakage
dirpath = '/proc/' + six.text_type(pinfo['pid']) + '/fd/'
listdir = os.listdir(dirpath)
maplines = maps.readlines()
except (OSError, IOError):
yield False
# /proc/PID/maps
mapline = re.compile(r'^[\da-f]+-[\da-f]+ [r-][w-][x-][sp-] '
r'[\da-f]+ [\da-f]{2}:[\da-f]{2} (\d+) *(.+)( \(deleted\))?\n$')
for line in maplines:
line = salt.utils.stringutils.to_unicode(line)
matched = mapline.match(line)
if not matched:
continue
path = matched.group(2)
if not path:
continue
valid = _valid_deleted_file(path)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], path[0:-10])
if val not in deleted_files:
deleted_files.append(val)
yield val
# /proc/PID/fd
try:
for link in listdir:
path = dirpath + link
readlink = os.readlink(path)
filenames = []
if os.path.isfile(readlink):
filenames.append(readlink)
elif os.path.isdir(readlink) and readlink != '/':
for root, dummy_dirs, files in salt.utils.path.os_walk(readlink, followlinks=True):
for name in files:
filenames.append(os.path.join(root, name))
for filename in filenames:
valid = _valid_deleted_file(filename)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], filename)
if val not in deleted_files:
deleted_files.append(val)
yield val
except OSError:
pass
except psutil.NoSuchProcess:
pass
def _format_output(kernel_restart, packages, verbose, restartable, nonrestartable, restartservicecommands,
restartinitcommands):
'''
Formats the output of the restartcheck module.
Returns:
String - formatted output.
Args:
kernel_restart: indicates that newer kernel is instaled
packages: list of packages that should be restarted
verbose: enables extensive output
restartable: list of restartable packages
nonrestartable: list of non-restartable packages
restartservicecommands: list of commands to restart services
restartinitcommands: list of commands to restart init.d scripts
'''
if not verbose:
packages = restartable + nonrestartable
if kernel_restart:
packages.append('System restart required.')
return packages
else:
ret = ''
if kernel_restart:
ret = 'System restart required.\n\n'
if packages:
ret += "Found {0} processes using old versions of upgraded files.\n".format(len(packages))
ret += "These are the packages:\n"
if restartable:
ret += "Of these, {0} seem to contain systemd service definitions or init scripts " \
"which can be used to restart them:\n".format(len(restartable))
for package in restartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
if restartservicecommands:
ret += "\n\nThese are the systemd services:\n"
ret += '\n'.join(restartservicecommands)
if restartinitcommands:
ret += "\n\nThese are the initd scripts:\n"
ret += '\n'.join(restartinitcommands)
if nonrestartable:
ret += "\n\nThese processes {0} do not seem to have an associated init script " \
"to restart them:\n".format(len(nonrestartable))
for package in nonrestartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
return ret
def _kernel_versions_debian():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kernel_get_selections = __salt__['cmd.run']('dpkg --get-selections linux-image-*')
kernels = []
kernel_versions = []
for line in kernel_get_selections.splitlines():
kernels.append(line)
try:
kernel = kernels[-2]
except IndexError:
kernel = kernels[0]
kernel = kernel.rstrip('\t\tinstall')
kernel_get_version = __salt__['cmd.run']('apt-cache policy ' + kernel)
for line in kernel_get_version.splitlines():
if line.startswith(' Installed: '):
kernel_v = line.strip(' Installed: ')
kernel_versions.append(kernel_v)
break
if __grains__['os'] == 'Ubuntu':
kernel_v = kernel_versions[0].rsplit('.', 1)
kernel_ubuntu_generic = kernel_v[0] + '-generic #' + kernel_v[1]
kernel_ubuntu_lowlatency = kernel_v[0] + '-lowlatency #' + kernel_v[1]
kernel_versions.extend([kernel_ubuntu_generic, kernel_ubuntu_lowlatency])
return kernel_versions
def _kernel_versions_nilrt():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kver = None
def _get_kver_from_bin(kbin):
'''
Get kernel version from a binary image or None if detection fails
'''
kvregex = r'[0-9]+\.[0-9]+\.[0-9]+-rt\S+'
kernel_strings = __salt__['cmd.run']('strings {0}'.format(kbin))
re_result = re.search(kvregex, kernel_strings)
return None if re_result is None else re_result.group(0)
if __grains__.get('lsb_distrib_id') == 'nilrt':
if 'arm' in __grains__.get('cpuarch'):
# the kernel is inside a uboot created itb (FIT) image alongside the
# device tree, ramdisk and a bootscript. There is no package management
# or any other kind of versioning info, so we need to extract the itb.
itb_path = '/boot/linux_runmode.itb'
compressed_kernel = '/var/volatile/tmp/uImage.gz'
uncompressed_kernel = '/var/volatile/tmp/uImage'
__salt__['cmd.run']('dumpimage -i {0} -T flat_dt -p0 kernel -o {1}'
.format(itb_path, compressed_kernel))
__salt__['cmd.run']('gunzip -f {0}'.format(compressed_kernel))
kver = _get_kver_from_bin(uncompressed_kernel)
else:
# the kernel bzImage is copied to rootfs without package management or
# other versioning info.
kver = _get_kver_from_bin('/boot/runmode/bzImage')
else:
# kernels in newer NILRT's are installed via package management and
# have the version appended to the kernel image filename
if 'arm' in __grains__.get('cpuarch'):
kver = os.path.basename(os.readlink('/boot/uImage')).strip('uImage-')
else:
kver = os.path.basename(os.readlink('/boot/bzImage')).strip('bzImage-')
return [] if kver is None else [kver]
def _check_timeout(start_time, timeout):
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
timeout_milisec = timeout * 60000
if timeout_milisec < (int(round(time.time() * 1000)) - start_time):
raise salt.exceptions.TimeoutError('Timeout expired.')
def _file_changed_nilrt(full_filepath):
'''
Detect whether a file changed in an NILinuxRT system using md5sum and timestamp
files from a state directory.
Returns:
- False if md5sum/timestamp state files don't exist
- True/False depending if ``base_filename`` got modified/touched
'''
rs_state_dir = "/var/lib/salt/restartcheck_state"
base_filename = os.path.basename(full_filepath)
timestamp_file = os.path.join(rs_state_dir, '{0}.timestamp'.format(base_filename))
md5sum_file = os.path.join(rs_state_dir, '{0}.md5sum'.format(base_filename))
if not os.path.exists(timestamp_file) or not os.path.exists(md5sum_file):
return True
prev_timestamp = __salt__['file.read'](timestamp_file).rstrip()
# Need timestamp in seconds so floor it using int()
cur_timestamp = str(int(os.path.getmtime(full_filepath)))
if prev_timestamp != cur_timestamp:
return True
return bool(__salt__['cmd.retcode']('md5sum -cs {0}'.format(md5sum_file), output_loglevel="quiet"))
def _kernel_modules_changed_nilrt(kernelversion):
'''
Once a NILRT kernel module is inserted, it can't be rmmod so systems need
rebooting (some modules explicitly ask for reboots even on first install),
hence this functionality of determining if the module state got modified by
testing if depmod was run.
Returns:
- True/False depending if modules.dep got modified/touched
'''
if kernelversion is not None:
return _file_changed_nilrt('/lib/modules/{0}/modules.dep'.format(kernelversion))
return False
def _sysapi_changed_nilrt():
'''
Besides the normal Linux kernel driver interfaces, NILinuxRT-supported hardware features an
extensible, plugin-based device enumeration and configuration interface named "System API".
When an installed package is extending the API it is very hard to know all repercurssions and
actions to be taken, so reboot making sure all drivers are reloaded, hardware reinitialized,
daemons restarted, etc.
Returns:
- True/False depending if nisysapi .ini files got modified/touched
- False if no nisysapi .ini files exist
'''
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path) and _file_changed_nilrt(nisysapi_path):
return True
restartcheck_state_dir = '/var/lib/salt/restartcheck_state'
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
rs_count_file = '{0}/sysapi.conf.d.count'.format(restartcheck_state_dir)
if not os.path.exists(rs_count_file):
return True
with salt.utils.files.fopen(rs_count_file, 'r') as fcount:
current_nb_files = len(os.listdir(nisysapi_conf_d_path))
rs_stored_nb_files = int(fcount.read())
if current_nb_files != rs_stored_nb_files:
return True
for fexpert in os.listdir(nisysapi_conf_d_path):
if _file_changed_nilrt('{0}/{1}'.format(nisysapi_conf_d_path, fexpert)):
return True
return False
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def restartcheck(ignorelist=None, blacklist=None, excludepid=None, **kwargs):
'''
Analyzes files openeded by running processes and seeks for packages which need to be restarted.
Args:
ignorelist: string or list of packages to be ignored
blacklist: string or list of file paths to be ignored
excludepid: string or list of process IDs to be ignored
verbose: boolean, enables extensive output
timeout: int, timeout in minute
Returns:
Dict on error: { 'result': False, 'comment': '<reason>' }
String with checkrestart output if some package seems to need to be restarted or
if no packages need restarting.
.. versionadded:: 2015.8.3
CLI Example:
.. code-block:: bash
salt '*' restartcheck.restartcheck
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
start_time = int(round(time.time() * 1000))
kernel_restart = True
verbose = kwargs.pop('verbose', True)
timeout = kwargs.pop('timeout', 5)
if __grains__.get('os_family') == 'Debian':
cmd_pkg_query = 'dpkg-query --listfiles '
systemd_folder = '/lib/systemd/system/'
systemd = '/bin/systemd'
kernel_versions = _kernel_versions_debian()
elif __grains__.get('os_family') == 'RedHat':
cmd_pkg_query = 'repoquery -l '
systemd_folder = '/usr/lib/systemd/system/'
systemd = '/usr/bin/systemctl'
kernel_versions = _kernel_versions_redhat()
elif __grains__.get('os_family') == NILRT_FAMILY_NAME:
cmd_pkg_query = 'opkg files '
systemd = ''
kernel_versions = _kernel_versions_nilrt()
else:
return {'result': False, 'comment': 'Only available on Debian, Red Hat and NI Linux Real-Time based systems.'}
# Check kernel versions
kernel_current = __salt__['cmd.run']('uname -a')
for kernel in kernel_versions:
_check_timeout(start_time, timeout)
if kernel in kernel_current:
if __grains__.get('os_family') == 'NILinuxRT':
# Check kernel modules and hardware API's for version changes
# If a restartcheck=True event was previously witnessed, propagate it
if not _kernel_modules_changed_nilrt(kernel) and \
not _sysapi_changed_nilrt() and \
not __salt__['system.get_reboot_required_witnessed']():
kernel_restart = False
break
else:
kernel_restart = False
break
packages = {}
running_services = {}
restart_services = []
if ignorelist:
if not isinstance(ignorelist, list):
ignorelist = [ignorelist]
else:
ignorelist = ['screen', 'systemd']
if blacklist:
if not isinstance(blacklist, list):
blacklist = [blacklist]
else:
blacklist = []
if excludepid:
if not isinstance(excludepid, list):
excludepid = [excludepid]
else:
excludepid = []
for service in __salt__['service.get_running']():
_check_timeout(start_time, timeout)
service_show = __salt__['service.show'](service)
if 'ExecMainPID' in service_show:
running_services[service] = int(service_show['ExecMainPID'])
owners_cache = {}
for deleted_file in _deleted_files():
if deleted_file is False:
return {'result': False, 'comment': 'Could not get list of processes.'
' (Do you have root access?)'}
_check_timeout(start_time, timeout)
name, pid, path = deleted_file[0], deleted_file[1], deleted_file[2]
if path in blacklist or pid in excludepid:
continue
try:
readlink = os.readlink('/proc/{0}/exe'.format(pid))
except OSError:
excludepid.append(pid)
continue
try:
packagename = owners_cache[readlink]
except KeyError:
packagename = __salt__['pkg.owner'](readlink)
if not packagename:
packagename = name
owners_cache[readlink] = packagename
for running_service in running_services:
_check_timeout(start_time, timeout)
if running_service not in restart_services and pid == running_services[running_service]:
if packagename and packagename not in ignorelist:
restart_services.append(running_service)
name = running_service
if packagename and packagename not in ignorelist:
program = '\t' + six.text_type(pid) + ' ' + readlink + ' (file: ' + six.text_type(path) + ')'
if packagename not in packages:
packages[packagename] = {'initscripts': [], 'systemdservice': [], 'processes': [program],
'process_name': name}
else:
if program not in packages[packagename]['processes']:
packages[packagename]['processes'].append(program)
if not packages and not kernel_restart:
return 'No packages seem to need to be restarted.'
for package in packages:
_check_timeout(start_time, timeout)
cmd = cmd_pkg_query + package
paths = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
while True:
_check_timeout(start_time, timeout)
line = salt.utils.stringutils.to_unicode(paths.stdout.readline())
if not line:
break
pth = line[:-1]
if pth.startswith('/etc/init.d/') and not pth.endswith('.sh'):
packages[package]['initscripts'].append(pth[12:])
if os.path.exists(systemd) and pth.startswith(systemd_folder) and pth.endswith('.service') and \
pth.find('.wants') == -1:
is_oneshot = False
try:
servicefile = salt.utils.files.fopen(pth) # pylint: disable=resource-leakage
except IOError:
continue
sysfold_len = len(systemd_folder)
for line in servicefile.readlines():
line = salt.utils.stringutils.to_unicode(line)
if line.find('Type=oneshot') > 0:
# scripts that does a single job and then exit
is_oneshot = True
continue
servicefile.close()
if not is_oneshot:
packages[package]['systemdservice'].append(pth[sysfold_len:])
sys.stdout.flush()
paths.stdout.close()
# Alternatively, find init.d script or service that match the process name
for package in packages:
_check_timeout(start_time, timeout)
if not packages[package]['systemdservice'] and not packages[package]['initscripts']:
service = __salt__['service.available'](packages[package]['process_name'])
if service:
if os.path.exists('/etc/init.d/' + packages[package]['process_name']):
packages[package]['initscripts'].append(packages[package]['process_name'])
else:
packages[package]['systemdservice'].append(packages[package]['process_name'])
restartable = []
nonrestartable = []
restartinitcommands = []
restartservicecommands = []
for package in packages:
_check_timeout(start_time, timeout)
if packages[package]['initscripts']:
restartable.append(package)
restartinitcommands.extend(['service ' + s + ' restart' for s in packages[package]['initscripts']])
elif packages[package]['systemdservice']:
restartable.append(package)
restartservicecommands.extend(['systemctl restart ' + s for s in packages[package]['systemdservice']])
else:
nonrestartable.append(package)
if packages[package]['process_name'] in restart_services:
restart_services.remove(packages[package]['process_name'])
for restart_service in restart_services:
_check_timeout(start_time, timeout)
restartservicecommands.extend(['systemctl restart ' + restart_service])
ret = _format_output(kernel_restart, packages, verbose, restartable, nonrestartable,
restartservicecommands, restartinitcommands)
return ret
|
saltstack/salt
|
salt/modules/restartcheck.py
|
_kernel_versions_nilrt
|
python
|
def _kernel_versions_nilrt():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kver = None
def _get_kver_from_bin(kbin):
'''
Get kernel version from a binary image or None if detection fails
'''
kvregex = r'[0-9]+\.[0-9]+\.[0-9]+-rt\S+'
kernel_strings = __salt__['cmd.run']('strings {0}'.format(kbin))
re_result = re.search(kvregex, kernel_strings)
return None if re_result is None else re_result.group(0)
if __grains__.get('lsb_distrib_id') == 'nilrt':
if 'arm' in __grains__.get('cpuarch'):
# the kernel is inside a uboot created itb (FIT) image alongside the
# device tree, ramdisk and a bootscript. There is no package management
# or any other kind of versioning info, so we need to extract the itb.
itb_path = '/boot/linux_runmode.itb'
compressed_kernel = '/var/volatile/tmp/uImage.gz'
uncompressed_kernel = '/var/volatile/tmp/uImage'
__salt__['cmd.run']('dumpimage -i {0} -T flat_dt -p0 kernel -o {1}'
.format(itb_path, compressed_kernel))
__salt__['cmd.run']('gunzip -f {0}'.format(compressed_kernel))
kver = _get_kver_from_bin(uncompressed_kernel)
else:
# the kernel bzImage is copied to rootfs without package management or
# other versioning info.
kver = _get_kver_from_bin('/boot/runmode/bzImage')
else:
# kernels in newer NILRT's are installed via package management and
# have the version appended to the kernel image filename
if 'arm' in __grains__.get('cpuarch'):
kver = os.path.basename(os.readlink('/boot/uImage')).strip('uImage-')
else:
kver = os.path.basename(os.readlink('/boot/bzImage')).strip('bzImage-')
return [] if kver is None else [kver]
|
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/restartcheck.py#L302-L345
| null |
# -*- coding: utf-8 -*-
'''
checkrestart functionality for Debian and Red Hat Based systems
Identifies services (processes) that are linked against deleted files (for example after downloading an updated
binary of a shared library).
Based on checkrestart script from debian-goodies (written by Matt Zimmerman for the Debian GNU/Linux distribution,
https://packages.debian.org/debian-goodies) and psdel by Sam Morris.
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import subprocess
import sys
import time
# Import salt libs
import salt.exceptions
import salt.utils.args
import salt.utils.files
import salt.utils.path
# Import 3rd partylibs
from salt.ext import six
NILRT_FAMILY_NAME = 'NILinuxRT'
HAS_PSUTIL = False
try:
import psutil
HAS_PSUTIL = True
except ImportError:
pass
LIST_DIRS = [
# We don't care about log files
'^/var/log/',
'^/var/local/log/',
# Or about files under temporary locations
'^/var/run/',
'^/var/local/run/',
# Or about files under /tmp
'^/tmp/',
# Or about files under /dev/shm
'^/dev/shm/',
# Or about files under /run
'^/run/',
# Or about files under /drm
'^/drm',
# Or about files under /var/tmp and /var/local/tmp
'^/var/tmp/',
'^/var/local/tmp/',
# Or /dev/zero
'^/dev/zero',
# Or /dev/pts (used by gpm)
'^/dev/pts/',
# Or /usr/lib/locale
'^/usr/lib/locale/',
# Skip files from the user's home directories
# many processes hold temporafy files there
'^/home/',
# Skip automatically generated files
'^.*icon-theme.cache',
# Skip font files
'^/var/cache/fontconfig/',
# Skip Nagios Spool
'^/var/lib/nagios3/spool/',
# Skip nagios spool files
'^/var/lib/nagios3/spool/checkresults/',
# Skip Postgresql files
'^/var/lib/postgresql/',
# Skip VDR lib files
'^/var/lib/vdr/',
# Skip Aio files found in MySQL servers
'^/[aio]',
# ignore files under /SYSV
'^/SYSV'
]
def __virtual__():
'''
Only run this module if the psutil python module is installed (package python-psutil).
'''
return HAS_PSUTIL
def _valid_deleted_file(path):
'''
Filters file path against unwanted directories and decides whether file is marked as deleted.
Returns:
True if file is desired deleted file, else False.
Args:
path: A string - path to file
'''
ret = False
if path.endswith(' (deleted)'):
ret = True
if re.compile(r"\(path inode=[0-9]+\)$").search(path):
ret = True
regex = re.compile("|".join(LIST_DIRS))
if regex.match(path):
ret = False
return ret
def _deleted_files():
'''
Iterates over /proc/PID/maps and /proc/PID/fd links and returns list of desired deleted files.
Returns:
List of deleted files to analyze, False on failure.
'''
deleted_files = []
for proc in psutil.process_iter(): # pylint: disable=too-many-nested-blocks
try:
pinfo = proc.as_dict(attrs=['pid', 'name'])
try:
with salt.utils.files.fopen('/proc/{0}/maps'.format(pinfo['pid'])) as maps: # pylint: disable=resource-leakage
dirpath = '/proc/' + six.text_type(pinfo['pid']) + '/fd/'
listdir = os.listdir(dirpath)
maplines = maps.readlines()
except (OSError, IOError):
yield False
# /proc/PID/maps
mapline = re.compile(r'^[\da-f]+-[\da-f]+ [r-][w-][x-][sp-] '
r'[\da-f]+ [\da-f]{2}:[\da-f]{2} (\d+) *(.+)( \(deleted\))?\n$')
for line in maplines:
line = salt.utils.stringutils.to_unicode(line)
matched = mapline.match(line)
if not matched:
continue
path = matched.group(2)
if not path:
continue
valid = _valid_deleted_file(path)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], path[0:-10])
if val not in deleted_files:
deleted_files.append(val)
yield val
# /proc/PID/fd
try:
for link in listdir:
path = dirpath + link
readlink = os.readlink(path)
filenames = []
if os.path.isfile(readlink):
filenames.append(readlink)
elif os.path.isdir(readlink) and readlink != '/':
for root, dummy_dirs, files in salt.utils.path.os_walk(readlink, followlinks=True):
for name in files:
filenames.append(os.path.join(root, name))
for filename in filenames:
valid = _valid_deleted_file(filename)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], filename)
if val not in deleted_files:
deleted_files.append(val)
yield val
except OSError:
pass
except psutil.NoSuchProcess:
pass
def _format_output(kernel_restart, packages, verbose, restartable, nonrestartable, restartservicecommands,
restartinitcommands):
'''
Formats the output of the restartcheck module.
Returns:
String - formatted output.
Args:
kernel_restart: indicates that newer kernel is instaled
packages: list of packages that should be restarted
verbose: enables extensive output
restartable: list of restartable packages
nonrestartable: list of non-restartable packages
restartservicecommands: list of commands to restart services
restartinitcommands: list of commands to restart init.d scripts
'''
if not verbose:
packages = restartable + nonrestartable
if kernel_restart:
packages.append('System restart required.')
return packages
else:
ret = ''
if kernel_restart:
ret = 'System restart required.\n\n'
if packages:
ret += "Found {0} processes using old versions of upgraded files.\n".format(len(packages))
ret += "These are the packages:\n"
if restartable:
ret += "Of these, {0} seem to contain systemd service definitions or init scripts " \
"which can be used to restart them:\n".format(len(restartable))
for package in restartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
if restartservicecommands:
ret += "\n\nThese are the systemd services:\n"
ret += '\n'.join(restartservicecommands)
if restartinitcommands:
ret += "\n\nThese are the initd scripts:\n"
ret += '\n'.join(restartinitcommands)
if nonrestartable:
ret += "\n\nThese processes {0} do not seem to have an associated init script " \
"to restart them:\n".format(len(nonrestartable))
for package in nonrestartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
return ret
def _kernel_versions_debian():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kernel_get_selections = __salt__['cmd.run']('dpkg --get-selections linux-image-*')
kernels = []
kernel_versions = []
for line in kernel_get_selections.splitlines():
kernels.append(line)
try:
kernel = kernels[-2]
except IndexError:
kernel = kernels[0]
kernel = kernel.rstrip('\t\tinstall')
kernel_get_version = __salt__['cmd.run']('apt-cache policy ' + kernel)
for line in kernel_get_version.splitlines():
if line.startswith(' Installed: '):
kernel_v = line.strip(' Installed: ')
kernel_versions.append(kernel_v)
break
if __grains__['os'] == 'Ubuntu':
kernel_v = kernel_versions[0].rsplit('.', 1)
kernel_ubuntu_generic = kernel_v[0] + '-generic #' + kernel_v[1]
kernel_ubuntu_lowlatency = kernel_v[0] + '-lowlatency #' + kernel_v[1]
kernel_versions.extend([kernel_ubuntu_generic, kernel_ubuntu_lowlatency])
return kernel_versions
def _kernel_versions_redhat():
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
kernel_get_last = __salt__['cmd.run']('rpm -q --last kernel')
kernels = []
kernel_versions = []
for line in kernel_get_last.splitlines():
if 'kernel-' in line:
kernels.append(line)
kernel = kernels[0].split(' ', 1)[0]
kernel = kernel.strip('kernel-')
kernel_versions.append(kernel)
return kernel_versions
def _check_timeout(start_time, timeout):
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
timeout_milisec = timeout * 60000
if timeout_milisec < (int(round(time.time() * 1000)) - start_time):
raise salt.exceptions.TimeoutError('Timeout expired.')
def _file_changed_nilrt(full_filepath):
'''
Detect whether a file changed in an NILinuxRT system using md5sum and timestamp
files from a state directory.
Returns:
- False if md5sum/timestamp state files don't exist
- True/False depending if ``base_filename`` got modified/touched
'''
rs_state_dir = "/var/lib/salt/restartcheck_state"
base_filename = os.path.basename(full_filepath)
timestamp_file = os.path.join(rs_state_dir, '{0}.timestamp'.format(base_filename))
md5sum_file = os.path.join(rs_state_dir, '{0}.md5sum'.format(base_filename))
if not os.path.exists(timestamp_file) or not os.path.exists(md5sum_file):
return True
prev_timestamp = __salt__['file.read'](timestamp_file).rstrip()
# Need timestamp in seconds so floor it using int()
cur_timestamp = str(int(os.path.getmtime(full_filepath)))
if prev_timestamp != cur_timestamp:
return True
return bool(__salt__['cmd.retcode']('md5sum -cs {0}'.format(md5sum_file), output_loglevel="quiet"))
def _kernel_modules_changed_nilrt(kernelversion):
'''
Once a NILRT kernel module is inserted, it can't be rmmod so systems need
rebooting (some modules explicitly ask for reboots even on first install),
hence this functionality of determining if the module state got modified by
testing if depmod was run.
Returns:
- True/False depending if modules.dep got modified/touched
'''
if kernelversion is not None:
return _file_changed_nilrt('/lib/modules/{0}/modules.dep'.format(kernelversion))
return False
def _sysapi_changed_nilrt():
'''
Besides the normal Linux kernel driver interfaces, NILinuxRT-supported hardware features an
extensible, plugin-based device enumeration and configuration interface named "System API".
When an installed package is extending the API it is very hard to know all repercurssions and
actions to be taken, so reboot making sure all drivers are reloaded, hardware reinitialized,
daemons restarted, etc.
Returns:
- True/False depending if nisysapi .ini files got modified/touched
- False if no nisysapi .ini files exist
'''
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path) and _file_changed_nilrt(nisysapi_path):
return True
restartcheck_state_dir = '/var/lib/salt/restartcheck_state'
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
rs_count_file = '{0}/sysapi.conf.d.count'.format(restartcheck_state_dir)
if not os.path.exists(rs_count_file):
return True
with salt.utils.files.fopen(rs_count_file, 'r') as fcount:
current_nb_files = len(os.listdir(nisysapi_conf_d_path))
rs_stored_nb_files = int(fcount.read())
if current_nb_files != rs_stored_nb_files:
return True
for fexpert in os.listdir(nisysapi_conf_d_path):
if _file_changed_nilrt('{0}/{1}'.format(nisysapi_conf_d_path, fexpert)):
return True
return False
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def restartcheck(ignorelist=None, blacklist=None, excludepid=None, **kwargs):
'''
Analyzes files openeded by running processes and seeks for packages which need to be restarted.
Args:
ignorelist: string or list of packages to be ignored
blacklist: string or list of file paths to be ignored
excludepid: string or list of process IDs to be ignored
verbose: boolean, enables extensive output
timeout: int, timeout in minute
Returns:
Dict on error: { 'result': False, 'comment': '<reason>' }
String with checkrestart output if some package seems to need to be restarted or
if no packages need restarting.
.. versionadded:: 2015.8.3
CLI Example:
.. code-block:: bash
salt '*' restartcheck.restartcheck
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
start_time = int(round(time.time() * 1000))
kernel_restart = True
verbose = kwargs.pop('verbose', True)
timeout = kwargs.pop('timeout', 5)
if __grains__.get('os_family') == 'Debian':
cmd_pkg_query = 'dpkg-query --listfiles '
systemd_folder = '/lib/systemd/system/'
systemd = '/bin/systemd'
kernel_versions = _kernel_versions_debian()
elif __grains__.get('os_family') == 'RedHat':
cmd_pkg_query = 'repoquery -l '
systemd_folder = '/usr/lib/systemd/system/'
systemd = '/usr/bin/systemctl'
kernel_versions = _kernel_versions_redhat()
elif __grains__.get('os_family') == NILRT_FAMILY_NAME:
cmd_pkg_query = 'opkg files '
systemd = ''
kernel_versions = _kernel_versions_nilrt()
else:
return {'result': False, 'comment': 'Only available on Debian, Red Hat and NI Linux Real-Time based systems.'}
# Check kernel versions
kernel_current = __salt__['cmd.run']('uname -a')
for kernel in kernel_versions:
_check_timeout(start_time, timeout)
if kernel in kernel_current:
if __grains__.get('os_family') == 'NILinuxRT':
# Check kernel modules and hardware API's for version changes
# If a restartcheck=True event was previously witnessed, propagate it
if not _kernel_modules_changed_nilrt(kernel) and \
not _sysapi_changed_nilrt() and \
not __salt__['system.get_reboot_required_witnessed']():
kernel_restart = False
break
else:
kernel_restart = False
break
packages = {}
running_services = {}
restart_services = []
if ignorelist:
if not isinstance(ignorelist, list):
ignorelist = [ignorelist]
else:
ignorelist = ['screen', 'systemd']
if blacklist:
if not isinstance(blacklist, list):
blacklist = [blacklist]
else:
blacklist = []
if excludepid:
if not isinstance(excludepid, list):
excludepid = [excludepid]
else:
excludepid = []
for service in __salt__['service.get_running']():
_check_timeout(start_time, timeout)
service_show = __salt__['service.show'](service)
if 'ExecMainPID' in service_show:
running_services[service] = int(service_show['ExecMainPID'])
owners_cache = {}
for deleted_file in _deleted_files():
if deleted_file is False:
return {'result': False, 'comment': 'Could not get list of processes.'
' (Do you have root access?)'}
_check_timeout(start_time, timeout)
name, pid, path = deleted_file[0], deleted_file[1], deleted_file[2]
if path in blacklist or pid in excludepid:
continue
try:
readlink = os.readlink('/proc/{0}/exe'.format(pid))
except OSError:
excludepid.append(pid)
continue
try:
packagename = owners_cache[readlink]
except KeyError:
packagename = __salt__['pkg.owner'](readlink)
if not packagename:
packagename = name
owners_cache[readlink] = packagename
for running_service in running_services:
_check_timeout(start_time, timeout)
if running_service not in restart_services and pid == running_services[running_service]:
if packagename and packagename not in ignorelist:
restart_services.append(running_service)
name = running_service
if packagename and packagename not in ignorelist:
program = '\t' + six.text_type(pid) + ' ' + readlink + ' (file: ' + six.text_type(path) + ')'
if packagename not in packages:
packages[packagename] = {'initscripts': [], 'systemdservice': [], 'processes': [program],
'process_name': name}
else:
if program not in packages[packagename]['processes']:
packages[packagename]['processes'].append(program)
if not packages and not kernel_restart:
return 'No packages seem to need to be restarted.'
for package in packages:
_check_timeout(start_time, timeout)
cmd = cmd_pkg_query + package
paths = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
while True:
_check_timeout(start_time, timeout)
line = salt.utils.stringutils.to_unicode(paths.stdout.readline())
if not line:
break
pth = line[:-1]
if pth.startswith('/etc/init.d/') and not pth.endswith('.sh'):
packages[package]['initscripts'].append(pth[12:])
if os.path.exists(systemd) and pth.startswith(systemd_folder) and pth.endswith('.service') and \
pth.find('.wants') == -1:
is_oneshot = False
try:
servicefile = salt.utils.files.fopen(pth) # pylint: disable=resource-leakage
except IOError:
continue
sysfold_len = len(systemd_folder)
for line in servicefile.readlines():
line = salt.utils.stringutils.to_unicode(line)
if line.find('Type=oneshot') > 0:
# scripts that does a single job and then exit
is_oneshot = True
continue
servicefile.close()
if not is_oneshot:
packages[package]['systemdservice'].append(pth[sysfold_len:])
sys.stdout.flush()
paths.stdout.close()
# Alternatively, find init.d script or service that match the process name
for package in packages:
_check_timeout(start_time, timeout)
if not packages[package]['systemdservice'] and not packages[package]['initscripts']:
service = __salt__['service.available'](packages[package]['process_name'])
if service:
if os.path.exists('/etc/init.d/' + packages[package]['process_name']):
packages[package]['initscripts'].append(packages[package]['process_name'])
else:
packages[package]['systemdservice'].append(packages[package]['process_name'])
restartable = []
nonrestartable = []
restartinitcommands = []
restartservicecommands = []
for package in packages:
_check_timeout(start_time, timeout)
if packages[package]['initscripts']:
restartable.append(package)
restartinitcommands.extend(['service ' + s + ' restart' for s in packages[package]['initscripts']])
elif packages[package]['systemdservice']:
restartable.append(package)
restartservicecommands.extend(['systemctl restart ' + s for s in packages[package]['systemdservice']])
else:
nonrestartable.append(package)
if packages[package]['process_name'] in restart_services:
restart_services.remove(packages[package]['process_name'])
for restart_service in restart_services:
_check_timeout(start_time, timeout)
restartservicecommands.extend(['systemctl restart ' + restart_service])
ret = _format_output(kernel_restart, packages, verbose, restartable, nonrestartable,
restartservicecommands, restartinitcommands)
return ret
|
saltstack/salt
|
salt/modules/restartcheck.py
|
_check_timeout
|
python
|
def _check_timeout(start_time, timeout):
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
timeout_milisec = timeout * 60000
if timeout_milisec < (int(round(time.time() * 1000)) - start_time):
raise salt.exceptions.TimeoutError('Timeout expired.')
|
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/restartcheck.py#L348-L357
| null |
# -*- coding: utf-8 -*-
'''
checkrestart functionality for Debian and Red Hat Based systems
Identifies services (processes) that are linked against deleted files (for example after downloading an updated
binary of a shared library).
Based on checkrestart script from debian-goodies (written by Matt Zimmerman for the Debian GNU/Linux distribution,
https://packages.debian.org/debian-goodies) and psdel by Sam Morris.
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import subprocess
import sys
import time
# Import salt libs
import salt.exceptions
import salt.utils.args
import salt.utils.files
import salt.utils.path
# Import 3rd partylibs
from salt.ext import six
NILRT_FAMILY_NAME = 'NILinuxRT'
HAS_PSUTIL = False
try:
import psutil
HAS_PSUTIL = True
except ImportError:
pass
LIST_DIRS = [
# We don't care about log files
'^/var/log/',
'^/var/local/log/',
# Or about files under temporary locations
'^/var/run/',
'^/var/local/run/',
# Or about files under /tmp
'^/tmp/',
# Or about files under /dev/shm
'^/dev/shm/',
# Or about files under /run
'^/run/',
# Or about files under /drm
'^/drm',
# Or about files under /var/tmp and /var/local/tmp
'^/var/tmp/',
'^/var/local/tmp/',
# Or /dev/zero
'^/dev/zero',
# Or /dev/pts (used by gpm)
'^/dev/pts/',
# Or /usr/lib/locale
'^/usr/lib/locale/',
# Skip files from the user's home directories
# many processes hold temporafy files there
'^/home/',
# Skip automatically generated files
'^.*icon-theme.cache',
# Skip font files
'^/var/cache/fontconfig/',
# Skip Nagios Spool
'^/var/lib/nagios3/spool/',
# Skip nagios spool files
'^/var/lib/nagios3/spool/checkresults/',
# Skip Postgresql files
'^/var/lib/postgresql/',
# Skip VDR lib files
'^/var/lib/vdr/',
# Skip Aio files found in MySQL servers
'^/[aio]',
# ignore files under /SYSV
'^/SYSV'
]
def __virtual__():
'''
Only run this module if the psutil python module is installed (package python-psutil).
'''
return HAS_PSUTIL
def _valid_deleted_file(path):
'''
Filters file path against unwanted directories and decides whether file is marked as deleted.
Returns:
True if file is desired deleted file, else False.
Args:
path: A string - path to file
'''
ret = False
if path.endswith(' (deleted)'):
ret = True
if re.compile(r"\(path inode=[0-9]+\)$").search(path):
ret = True
regex = re.compile("|".join(LIST_DIRS))
if regex.match(path):
ret = False
return ret
def _deleted_files():
'''
Iterates over /proc/PID/maps and /proc/PID/fd links and returns list of desired deleted files.
Returns:
List of deleted files to analyze, False on failure.
'''
deleted_files = []
for proc in psutil.process_iter(): # pylint: disable=too-many-nested-blocks
try:
pinfo = proc.as_dict(attrs=['pid', 'name'])
try:
with salt.utils.files.fopen('/proc/{0}/maps'.format(pinfo['pid'])) as maps: # pylint: disable=resource-leakage
dirpath = '/proc/' + six.text_type(pinfo['pid']) + '/fd/'
listdir = os.listdir(dirpath)
maplines = maps.readlines()
except (OSError, IOError):
yield False
# /proc/PID/maps
mapline = re.compile(r'^[\da-f]+-[\da-f]+ [r-][w-][x-][sp-] '
r'[\da-f]+ [\da-f]{2}:[\da-f]{2} (\d+) *(.+)( \(deleted\))?\n$')
for line in maplines:
line = salt.utils.stringutils.to_unicode(line)
matched = mapline.match(line)
if not matched:
continue
path = matched.group(2)
if not path:
continue
valid = _valid_deleted_file(path)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], path[0:-10])
if val not in deleted_files:
deleted_files.append(val)
yield val
# /proc/PID/fd
try:
for link in listdir:
path = dirpath + link
readlink = os.readlink(path)
filenames = []
if os.path.isfile(readlink):
filenames.append(readlink)
elif os.path.isdir(readlink) and readlink != '/':
for root, dummy_dirs, files in salt.utils.path.os_walk(readlink, followlinks=True):
for name in files:
filenames.append(os.path.join(root, name))
for filename in filenames:
valid = _valid_deleted_file(filename)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], filename)
if val not in deleted_files:
deleted_files.append(val)
yield val
except OSError:
pass
except psutil.NoSuchProcess:
pass
def _format_output(kernel_restart, packages, verbose, restartable, nonrestartable, restartservicecommands,
restartinitcommands):
'''
Formats the output of the restartcheck module.
Returns:
String - formatted output.
Args:
kernel_restart: indicates that newer kernel is instaled
packages: list of packages that should be restarted
verbose: enables extensive output
restartable: list of restartable packages
nonrestartable: list of non-restartable packages
restartservicecommands: list of commands to restart services
restartinitcommands: list of commands to restart init.d scripts
'''
if not verbose:
packages = restartable + nonrestartable
if kernel_restart:
packages.append('System restart required.')
return packages
else:
ret = ''
if kernel_restart:
ret = 'System restart required.\n\n'
if packages:
ret += "Found {0} processes using old versions of upgraded files.\n".format(len(packages))
ret += "These are the packages:\n"
if restartable:
ret += "Of these, {0} seem to contain systemd service definitions or init scripts " \
"which can be used to restart them:\n".format(len(restartable))
for package in restartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
if restartservicecommands:
ret += "\n\nThese are the systemd services:\n"
ret += '\n'.join(restartservicecommands)
if restartinitcommands:
ret += "\n\nThese are the initd scripts:\n"
ret += '\n'.join(restartinitcommands)
if nonrestartable:
ret += "\n\nThese processes {0} do not seem to have an associated init script " \
"to restart them:\n".format(len(nonrestartable))
for package in nonrestartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
return ret
def _kernel_versions_debian():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kernel_get_selections = __salt__['cmd.run']('dpkg --get-selections linux-image-*')
kernels = []
kernel_versions = []
for line in kernel_get_selections.splitlines():
kernels.append(line)
try:
kernel = kernels[-2]
except IndexError:
kernel = kernels[0]
kernel = kernel.rstrip('\t\tinstall')
kernel_get_version = __salt__['cmd.run']('apt-cache policy ' + kernel)
for line in kernel_get_version.splitlines():
if line.startswith(' Installed: '):
kernel_v = line.strip(' Installed: ')
kernel_versions.append(kernel_v)
break
if __grains__['os'] == 'Ubuntu':
kernel_v = kernel_versions[0].rsplit('.', 1)
kernel_ubuntu_generic = kernel_v[0] + '-generic #' + kernel_v[1]
kernel_ubuntu_lowlatency = kernel_v[0] + '-lowlatency #' + kernel_v[1]
kernel_versions.extend([kernel_ubuntu_generic, kernel_ubuntu_lowlatency])
return kernel_versions
def _kernel_versions_redhat():
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
kernel_get_last = __salt__['cmd.run']('rpm -q --last kernel')
kernels = []
kernel_versions = []
for line in kernel_get_last.splitlines():
if 'kernel-' in line:
kernels.append(line)
kernel = kernels[0].split(' ', 1)[0]
kernel = kernel.strip('kernel-')
kernel_versions.append(kernel)
return kernel_versions
def _kernel_versions_nilrt():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kver = None
def _get_kver_from_bin(kbin):
'''
Get kernel version from a binary image or None if detection fails
'''
kvregex = r'[0-9]+\.[0-9]+\.[0-9]+-rt\S+'
kernel_strings = __salt__['cmd.run']('strings {0}'.format(kbin))
re_result = re.search(kvregex, kernel_strings)
return None if re_result is None else re_result.group(0)
if __grains__.get('lsb_distrib_id') == 'nilrt':
if 'arm' in __grains__.get('cpuarch'):
# the kernel is inside a uboot created itb (FIT) image alongside the
# device tree, ramdisk and a bootscript. There is no package management
# or any other kind of versioning info, so we need to extract the itb.
itb_path = '/boot/linux_runmode.itb'
compressed_kernel = '/var/volatile/tmp/uImage.gz'
uncompressed_kernel = '/var/volatile/tmp/uImage'
__salt__['cmd.run']('dumpimage -i {0} -T flat_dt -p0 kernel -o {1}'
.format(itb_path, compressed_kernel))
__salt__['cmd.run']('gunzip -f {0}'.format(compressed_kernel))
kver = _get_kver_from_bin(uncompressed_kernel)
else:
# the kernel bzImage is copied to rootfs without package management or
# other versioning info.
kver = _get_kver_from_bin('/boot/runmode/bzImage')
else:
# kernels in newer NILRT's are installed via package management and
# have the version appended to the kernel image filename
if 'arm' in __grains__.get('cpuarch'):
kver = os.path.basename(os.readlink('/boot/uImage')).strip('uImage-')
else:
kver = os.path.basename(os.readlink('/boot/bzImage')).strip('bzImage-')
return [] if kver is None else [kver]
def _file_changed_nilrt(full_filepath):
'''
Detect whether a file changed in an NILinuxRT system using md5sum and timestamp
files from a state directory.
Returns:
- False if md5sum/timestamp state files don't exist
- True/False depending if ``base_filename`` got modified/touched
'''
rs_state_dir = "/var/lib/salt/restartcheck_state"
base_filename = os.path.basename(full_filepath)
timestamp_file = os.path.join(rs_state_dir, '{0}.timestamp'.format(base_filename))
md5sum_file = os.path.join(rs_state_dir, '{0}.md5sum'.format(base_filename))
if not os.path.exists(timestamp_file) or not os.path.exists(md5sum_file):
return True
prev_timestamp = __salt__['file.read'](timestamp_file).rstrip()
# Need timestamp in seconds so floor it using int()
cur_timestamp = str(int(os.path.getmtime(full_filepath)))
if prev_timestamp != cur_timestamp:
return True
return bool(__salt__['cmd.retcode']('md5sum -cs {0}'.format(md5sum_file), output_loglevel="quiet"))
def _kernel_modules_changed_nilrt(kernelversion):
'''
Once a NILRT kernel module is inserted, it can't be rmmod so systems need
rebooting (some modules explicitly ask for reboots even on first install),
hence this functionality of determining if the module state got modified by
testing if depmod was run.
Returns:
- True/False depending if modules.dep got modified/touched
'''
if kernelversion is not None:
return _file_changed_nilrt('/lib/modules/{0}/modules.dep'.format(kernelversion))
return False
def _sysapi_changed_nilrt():
'''
Besides the normal Linux kernel driver interfaces, NILinuxRT-supported hardware features an
extensible, plugin-based device enumeration and configuration interface named "System API".
When an installed package is extending the API it is very hard to know all repercurssions and
actions to be taken, so reboot making sure all drivers are reloaded, hardware reinitialized,
daemons restarted, etc.
Returns:
- True/False depending if nisysapi .ini files got modified/touched
- False if no nisysapi .ini files exist
'''
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path) and _file_changed_nilrt(nisysapi_path):
return True
restartcheck_state_dir = '/var/lib/salt/restartcheck_state'
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
rs_count_file = '{0}/sysapi.conf.d.count'.format(restartcheck_state_dir)
if not os.path.exists(rs_count_file):
return True
with salt.utils.files.fopen(rs_count_file, 'r') as fcount:
current_nb_files = len(os.listdir(nisysapi_conf_d_path))
rs_stored_nb_files = int(fcount.read())
if current_nb_files != rs_stored_nb_files:
return True
for fexpert in os.listdir(nisysapi_conf_d_path):
if _file_changed_nilrt('{0}/{1}'.format(nisysapi_conf_d_path, fexpert)):
return True
return False
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def restartcheck(ignorelist=None, blacklist=None, excludepid=None, **kwargs):
'''
Analyzes files openeded by running processes and seeks for packages which need to be restarted.
Args:
ignorelist: string or list of packages to be ignored
blacklist: string or list of file paths to be ignored
excludepid: string or list of process IDs to be ignored
verbose: boolean, enables extensive output
timeout: int, timeout in minute
Returns:
Dict on error: { 'result': False, 'comment': '<reason>' }
String with checkrestart output if some package seems to need to be restarted or
if no packages need restarting.
.. versionadded:: 2015.8.3
CLI Example:
.. code-block:: bash
salt '*' restartcheck.restartcheck
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
start_time = int(round(time.time() * 1000))
kernel_restart = True
verbose = kwargs.pop('verbose', True)
timeout = kwargs.pop('timeout', 5)
if __grains__.get('os_family') == 'Debian':
cmd_pkg_query = 'dpkg-query --listfiles '
systemd_folder = '/lib/systemd/system/'
systemd = '/bin/systemd'
kernel_versions = _kernel_versions_debian()
elif __grains__.get('os_family') == 'RedHat':
cmd_pkg_query = 'repoquery -l '
systemd_folder = '/usr/lib/systemd/system/'
systemd = '/usr/bin/systemctl'
kernel_versions = _kernel_versions_redhat()
elif __grains__.get('os_family') == NILRT_FAMILY_NAME:
cmd_pkg_query = 'opkg files '
systemd = ''
kernel_versions = _kernel_versions_nilrt()
else:
return {'result': False, 'comment': 'Only available on Debian, Red Hat and NI Linux Real-Time based systems.'}
# Check kernel versions
kernel_current = __salt__['cmd.run']('uname -a')
for kernel in kernel_versions:
_check_timeout(start_time, timeout)
if kernel in kernel_current:
if __grains__.get('os_family') == 'NILinuxRT':
# Check kernel modules and hardware API's for version changes
# If a restartcheck=True event was previously witnessed, propagate it
if not _kernel_modules_changed_nilrt(kernel) and \
not _sysapi_changed_nilrt() and \
not __salt__['system.get_reboot_required_witnessed']():
kernel_restart = False
break
else:
kernel_restart = False
break
packages = {}
running_services = {}
restart_services = []
if ignorelist:
if not isinstance(ignorelist, list):
ignorelist = [ignorelist]
else:
ignorelist = ['screen', 'systemd']
if blacklist:
if not isinstance(blacklist, list):
blacklist = [blacklist]
else:
blacklist = []
if excludepid:
if not isinstance(excludepid, list):
excludepid = [excludepid]
else:
excludepid = []
for service in __salt__['service.get_running']():
_check_timeout(start_time, timeout)
service_show = __salt__['service.show'](service)
if 'ExecMainPID' in service_show:
running_services[service] = int(service_show['ExecMainPID'])
owners_cache = {}
for deleted_file in _deleted_files():
if deleted_file is False:
return {'result': False, 'comment': 'Could not get list of processes.'
' (Do you have root access?)'}
_check_timeout(start_time, timeout)
name, pid, path = deleted_file[0], deleted_file[1], deleted_file[2]
if path in blacklist or pid in excludepid:
continue
try:
readlink = os.readlink('/proc/{0}/exe'.format(pid))
except OSError:
excludepid.append(pid)
continue
try:
packagename = owners_cache[readlink]
except KeyError:
packagename = __salt__['pkg.owner'](readlink)
if not packagename:
packagename = name
owners_cache[readlink] = packagename
for running_service in running_services:
_check_timeout(start_time, timeout)
if running_service not in restart_services and pid == running_services[running_service]:
if packagename and packagename not in ignorelist:
restart_services.append(running_service)
name = running_service
if packagename and packagename not in ignorelist:
program = '\t' + six.text_type(pid) + ' ' + readlink + ' (file: ' + six.text_type(path) + ')'
if packagename not in packages:
packages[packagename] = {'initscripts': [], 'systemdservice': [], 'processes': [program],
'process_name': name}
else:
if program not in packages[packagename]['processes']:
packages[packagename]['processes'].append(program)
if not packages and not kernel_restart:
return 'No packages seem to need to be restarted.'
for package in packages:
_check_timeout(start_time, timeout)
cmd = cmd_pkg_query + package
paths = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
while True:
_check_timeout(start_time, timeout)
line = salt.utils.stringutils.to_unicode(paths.stdout.readline())
if not line:
break
pth = line[:-1]
if pth.startswith('/etc/init.d/') and not pth.endswith('.sh'):
packages[package]['initscripts'].append(pth[12:])
if os.path.exists(systemd) and pth.startswith(systemd_folder) and pth.endswith('.service') and \
pth.find('.wants') == -1:
is_oneshot = False
try:
servicefile = salt.utils.files.fopen(pth) # pylint: disable=resource-leakage
except IOError:
continue
sysfold_len = len(systemd_folder)
for line in servicefile.readlines():
line = salt.utils.stringutils.to_unicode(line)
if line.find('Type=oneshot') > 0:
# scripts that does a single job and then exit
is_oneshot = True
continue
servicefile.close()
if not is_oneshot:
packages[package]['systemdservice'].append(pth[sysfold_len:])
sys.stdout.flush()
paths.stdout.close()
# Alternatively, find init.d script or service that match the process name
for package in packages:
_check_timeout(start_time, timeout)
if not packages[package]['systemdservice'] and not packages[package]['initscripts']:
service = __salt__['service.available'](packages[package]['process_name'])
if service:
if os.path.exists('/etc/init.d/' + packages[package]['process_name']):
packages[package]['initscripts'].append(packages[package]['process_name'])
else:
packages[package]['systemdservice'].append(packages[package]['process_name'])
restartable = []
nonrestartable = []
restartinitcommands = []
restartservicecommands = []
for package in packages:
_check_timeout(start_time, timeout)
if packages[package]['initscripts']:
restartable.append(package)
restartinitcommands.extend(['service ' + s + ' restart' for s in packages[package]['initscripts']])
elif packages[package]['systemdservice']:
restartable.append(package)
restartservicecommands.extend(['systemctl restart ' + s for s in packages[package]['systemdservice']])
else:
nonrestartable.append(package)
if packages[package]['process_name'] in restart_services:
restart_services.remove(packages[package]['process_name'])
for restart_service in restart_services:
_check_timeout(start_time, timeout)
restartservicecommands.extend(['systemctl restart ' + restart_service])
ret = _format_output(kernel_restart, packages, verbose, restartable, nonrestartable,
restartservicecommands, restartinitcommands)
return ret
|
saltstack/salt
|
salt/modules/restartcheck.py
|
_file_changed_nilrt
|
python
|
def _file_changed_nilrt(full_filepath):
'''
Detect whether a file changed in an NILinuxRT system using md5sum and timestamp
files from a state directory.
Returns:
- False if md5sum/timestamp state files don't exist
- True/False depending if ``base_filename`` got modified/touched
'''
rs_state_dir = "/var/lib/salt/restartcheck_state"
base_filename = os.path.basename(full_filepath)
timestamp_file = os.path.join(rs_state_dir, '{0}.timestamp'.format(base_filename))
md5sum_file = os.path.join(rs_state_dir, '{0}.md5sum'.format(base_filename))
if not os.path.exists(timestamp_file) or not os.path.exists(md5sum_file):
return True
prev_timestamp = __salt__['file.read'](timestamp_file).rstrip()
# Need timestamp in seconds so floor it using int()
cur_timestamp = str(int(os.path.getmtime(full_filepath)))
if prev_timestamp != cur_timestamp:
return True
return bool(__salt__['cmd.retcode']('md5sum -cs {0}'.format(md5sum_file), output_loglevel="quiet"))
|
Detect whether a file changed in an NILinuxRT system using md5sum and timestamp
files from a state directory.
Returns:
- False if md5sum/timestamp state files don't exist
- True/False depending if ``base_filename`` got modified/touched
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/restartcheck.py#L360-L384
| null |
# -*- coding: utf-8 -*-
'''
checkrestart functionality for Debian and Red Hat Based systems
Identifies services (processes) that are linked against deleted files (for example after downloading an updated
binary of a shared library).
Based on checkrestart script from debian-goodies (written by Matt Zimmerman for the Debian GNU/Linux distribution,
https://packages.debian.org/debian-goodies) and psdel by Sam Morris.
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import subprocess
import sys
import time
# Import salt libs
import salt.exceptions
import salt.utils.args
import salt.utils.files
import salt.utils.path
# Import 3rd partylibs
from salt.ext import six
NILRT_FAMILY_NAME = 'NILinuxRT'
HAS_PSUTIL = False
try:
import psutil
HAS_PSUTIL = True
except ImportError:
pass
LIST_DIRS = [
# We don't care about log files
'^/var/log/',
'^/var/local/log/',
# Or about files under temporary locations
'^/var/run/',
'^/var/local/run/',
# Or about files under /tmp
'^/tmp/',
# Or about files under /dev/shm
'^/dev/shm/',
# Or about files under /run
'^/run/',
# Or about files under /drm
'^/drm',
# Or about files under /var/tmp and /var/local/tmp
'^/var/tmp/',
'^/var/local/tmp/',
# Or /dev/zero
'^/dev/zero',
# Or /dev/pts (used by gpm)
'^/dev/pts/',
# Or /usr/lib/locale
'^/usr/lib/locale/',
# Skip files from the user's home directories
# many processes hold temporafy files there
'^/home/',
# Skip automatically generated files
'^.*icon-theme.cache',
# Skip font files
'^/var/cache/fontconfig/',
# Skip Nagios Spool
'^/var/lib/nagios3/spool/',
# Skip nagios spool files
'^/var/lib/nagios3/spool/checkresults/',
# Skip Postgresql files
'^/var/lib/postgresql/',
# Skip VDR lib files
'^/var/lib/vdr/',
# Skip Aio files found in MySQL servers
'^/[aio]',
# ignore files under /SYSV
'^/SYSV'
]
def __virtual__():
'''
Only run this module if the psutil python module is installed (package python-psutil).
'''
return HAS_PSUTIL
def _valid_deleted_file(path):
'''
Filters file path against unwanted directories and decides whether file is marked as deleted.
Returns:
True if file is desired deleted file, else False.
Args:
path: A string - path to file
'''
ret = False
if path.endswith(' (deleted)'):
ret = True
if re.compile(r"\(path inode=[0-9]+\)$").search(path):
ret = True
regex = re.compile("|".join(LIST_DIRS))
if regex.match(path):
ret = False
return ret
def _deleted_files():
'''
Iterates over /proc/PID/maps and /proc/PID/fd links and returns list of desired deleted files.
Returns:
List of deleted files to analyze, False on failure.
'''
deleted_files = []
for proc in psutil.process_iter(): # pylint: disable=too-many-nested-blocks
try:
pinfo = proc.as_dict(attrs=['pid', 'name'])
try:
with salt.utils.files.fopen('/proc/{0}/maps'.format(pinfo['pid'])) as maps: # pylint: disable=resource-leakage
dirpath = '/proc/' + six.text_type(pinfo['pid']) + '/fd/'
listdir = os.listdir(dirpath)
maplines = maps.readlines()
except (OSError, IOError):
yield False
# /proc/PID/maps
mapline = re.compile(r'^[\da-f]+-[\da-f]+ [r-][w-][x-][sp-] '
r'[\da-f]+ [\da-f]{2}:[\da-f]{2} (\d+) *(.+)( \(deleted\))?\n$')
for line in maplines:
line = salt.utils.stringutils.to_unicode(line)
matched = mapline.match(line)
if not matched:
continue
path = matched.group(2)
if not path:
continue
valid = _valid_deleted_file(path)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], path[0:-10])
if val not in deleted_files:
deleted_files.append(val)
yield val
# /proc/PID/fd
try:
for link in listdir:
path = dirpath + link
readlink = os.readlink(path)
filenames = []
if os.path.isfile(readlink):
filenames.append(readlink)
elif os.path.isdir(readlink) and readlink != '/':
for root, dummy_dirs, files in salt.utils.path.os_walk(readlink, followlinks=True):
for name in files:
filenames.append(os.path.join(root, name))
for filename in filenames:
valid = _valid_deleted_file(filename)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], filename)
if val not in deleted_files:
deleted_files.append(val)
yield val
except OSError:
pass
except psutil.NoSuchProcess:
pass
def _format_output(kernel_restart, packages, verbose, restartable, nonrestartable, restartservicecommands,
restartinitcommands):
'''
Formats the output of the restartcheck module.
Returns:
String - formatted output.
Args:
kernel_restart: indicates that newer kernel is instaled
packages: list of packages that should be restarted
verbose: enables extensive output
restartable: list of restartable packages
nonrestartable: list of non-restartable packages
restartservicecommands: list of commands to restart services
restartinitcommands: list of commands to restart init.d scripts
'''
if not verbose:
packages = restartable + nonrestartable
if kernel_restart:
packages.append('System restart required.')
return packages
else:
ret = ''
if kernel_restart:
ret = 'System restart required.\n\n'
if packages:
ret += "Found {0} processes using old versions of upgraded files.\n".format(len(packages))
ret += "These are the packages:\n"
if restartable:
ret += "Of these, {0} seem to contain systemd service definitions or init scripts " \
"which can be used to restart them:\n".format(len(restartable))
for package in restartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
if restartservicecommands:
ret += "\n\nThese are the systemd services:\n"
ret += '\n'.join(restartservicecommands)
if restartinitcommands:
ret += "\n\nThese are the initd scripts:\n"
ret += '\n'.join(restartinitcommands)
if nonrestartable:
ret += "\n\nThese processes {0} do not seem to have an associated init script " \
"to restart them:\n".format(len(nonrestartable))
for package in nonrestartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
return ret
def _kernel_versions_debian():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kernel_get_selections = __salt__['cmd.run']('dpkg --get-selections linux-image-*')
kernels = []
kernel_versions = []
for line in kernel_get_selections.splitlines():
kernels.append(line)
try:
kernel = kernels[-2]
except IndexError:
kernel = kernels[0]
kernel = kernel.rstrip('\t\tinstall')
kernel_get_version = __salt__['cmd.run']('apt-cache policy ' + kernel)
for line in kernel_get_version.splitlines():
if line.startswith(' Installed: '):
kernel_v = line.strip(' Installed: ')
kernel_versions.append(kernel_v)
break
if __grains__['os'] == 'Ubuntu':
kernel_v = kernel_versions[0].rsplit('.', 1)
kernel_ubuntu_generic = kernel_v[0] + '-generic #' + kernel_v[1]
kernel_ubuntu_lowlatency = kernel_v[0] + '-lowlatency #' + kernel_v[1]
kernel_versions.extend([kernel_ubuntu_generic, kernel_ubuntu_lowlatency])
return kernel_versions
def _kernel_versions_redhat():
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
kernel_get_last = __salt__['cmd.run']('rpm -q --last kernel')
kernels = []
kernel_versions = []
for line in kernel_get_last.splitlines():
if 'kernel-' in line:
kernels.append(line)
kernel = kernels[0].split(' ', 1)[0]
kernel = kernel.strip('kernel-')
kernel_versions.append(kernel)
return kernel_versions
def _kernel_versions_nilrt():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kver = None
def _get_kver_from_bin(kbin):
'''
Get kernel version from a binary image or None if detection fails
'''
kvregex = r'[0-9]+\.[0-9]+\.[0-9]+-rt\S+'
kernel_strings = __salt__['cmd.run']('strings {0}'.format(kbin))
re_result = re.search(kvregex, kernel_strings)
return None if re_result is None else re_result.group(0)
if __grains__.get('lsb_distrib_id') == 'nilrt':
if 'arm' in __grains__.get('cpuarch'):
# the kernel is inside a uboot created itb (FIT) image alongside the
# device tree, ramdisk and a bootscript. There is no package management
# or any other kind of versioning info, so we need to extract the itb.
itb_path = '/boot/linux_runmode.itb'
compressed_kernel = '/var/volatile/tmp/uImage.gz'
uncompressed_kernel = '/var/volatile/tmp/uImage'
__salt__['cmd.run']('dumpimage -i {0} -T flat_dt -p0 kernel -o {1}'
.format(itb_path, compressed_kernel))
__salt__['cmd.run']('gunzip -f {0}'.format(compressed_kernel))
kver = _get_kver_from_bin(uncompressed_kernel)
else:
# the kernel bzImage is copied to rootfs without package management or
# other versioning info.
kver = _get_kver_from_bin('/boot/runmode/bzImage')
else:
# kernels in newer NILRT's are installed via package management and
# have the version appended to the kernel image filename
if 'arm' in __grains__.get('cpuarch'):
kver = os.path.basename(os.readlink('/boot/uImage')).strip('uImage-')
else:
kver = os.path.basename(os.readlink('/boot/bzImage')).strip('bzImage-')
return [] if kver is None else [kver]
def _check_timeout(start_time, timeout):
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
timeout_milisec = timeout * 60000
if timeout_milisec < (int(round(time.time() * 1000)) - start_time):
raise salt.exceptions.TimeoutError('Timeout expired.')
def _kernel_modules_changed_nilrt(kernelversion):
'''
Once a NILRT kernel module is inserted, it can't be rmmod so systems need
rebooting (some modules explicitly ask for reboots even on first install),
hence this functionality of determining if the module state got modified by
testing if depmod was run.
Returns:
- True/False depending if modules.dep got modified/touched
'''
if kernelversion is not None:
return _file_changed_nilrt('/lib/modules/{0}/modules.dep'.format(kernelversion))
return False
def _sysapi_changed_nilrt():
'''
Besides the normal Linux kernel driver interfaces, NILinuxRT-supported hardware features an
extensible, plugin-based device enumeration and configuration interface named "System API".
When an installed package is extending the API it is very hard to know all repercurssions and
actions to be taken, so reboot making sure all drivers are reloaded, hardware reinitialized,
daemons restarted, etc.
Returns:
- True/False depending if nisysapi .ini files got modified/touched
- False if no nisysapi .ini files exist
'''
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path) and _file_changed_nilrt(nisysapi_path):
return True
restartcheck_state_dir = '/var/lib/salt/restartcheck_state'
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
rs_count_file = '{0}/sysapi.conf.d.count'.format(restartcheck_state_dir)
if not os.path.exists(rs_count_file):
return True
with salt.utils.files.fopen(rs_count_file, 'r') as fcount:
current_nb_files = len(os.listdir(nisysapi_conf_d_path))
rs_stored_nb_files = int(fcount.read())
if current_nb_files != rs_stored_nb_files:
return True
for fexpert in os.listdir(nisysapi_conf_d_path):
if _file_changed_nilrt('{0}/{1}'.format(nisysapi_conf_d_path, fexpert)):
return True
return False
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def restartcheck(ignorelist=None, blacklist=None, excludepid=None, **kwargs):
'''
Analyzes files openeded by running processes and seeks for packages which need to be restarted.
Args:
ignorelist: string or list of packages to be ignored
blacklist: string or list of file paths to be ignored
excludepid: string or list of process IDs to be ignored
verbose: boolean, enables extensive output
timeout: int, timeout in minute
Returns:
Dict on error: { 'result': False, 'comment': '<reason>' }
String with checkrestart output if some package seems to need to be restarted or
if no packages need restarting.
.. versionadded:: 2015.8.3
CLI Example:
.. code-block:: bash
salt '*' restartcheck.restartcheck
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
start_time = int(round(time.time() * 1000))
kernel_restart = True
verbose = kwargs.pop('verbose', True)
timeout = kwargs.pop('timeout', 5)
if __grains__.get('os_family') == 'Debian':
cmd_pkg_query = 'dpkg-query --listfiles '
systemd_folder = '/lib/systemd/system/'
systemd = '/bin/systemd'
kernel_versions = _kernel_versions_debian()
elif __grains__.get('os_family') == 'RedHat':
cmd_pkg_query = 'repoquery -l '
systemd_folder = '/usr/lib/systemd/system/'
systemd = '/usr/bin/systemctl'
kernel_versions = _kernel_versions_redhat()
elif __grains__.get('os_family') == NILRT_FAMILY_NAME:
cmd_pkg_query = 'opkg files '
systemd = ''
kernel_versions = _kernel_versions_nilrt()
else:
return {'result': False, 'comment': 'Only available on Debian, Red Hat and NI Linux Real-Time based systems.'}
# Check kernel versions
kernel_current = __salt__['cmd.run']('uname -a')
for kernel in kernel_versions:
_check_timeout(start_time, timeout)
if kernel in kernel_current:
if __grains__.get('os_family') == 'NILinuxRT':
# Check kernel modules and hardware API's for version changes
# If a restartcheck=True event was previously witnessed, propagate it
if not _kernel_modules_changed_nilrt(kernel) and \
not _sysapi_changed_nilrt() and \
not __salt__['system.get_reboot_required_witnessed']():
kernel_restart = False
break
else:
kernel_restart = False
break
packages = {}
running_services = {}
restart_services = []
if ignorelist:
if not isinstance(ignorelist, list):
ignorelist = [ignorelist]
else:
ignorelist = ['screen', 'systemd']
if blacklist:
if not isinstance(blacklist, list):
blacklist = [blacklist]
else:
blacklist = []
if excludepid:
if not isinstance(excludepid, list):
excludepid = [excludepid]
else:
excludepid = []
for service in __salt__['service.get_running']():
_check_timeout(start_time, timeout)
service_show = __salt__['service.show'](service)
if 'ExecMainPID' in service_show:
running_services[service] = int(service_show['ExecMainPID'])
owners_cache = {}
for deleted_file in _deleted_files():
if deleted_file is False:
return {'result': False, 'comment': 'Could not get list of processes.'
' (Do you have root access?)'}
_check_timeout(start_time, timeout)
name, pid, path = deleted_file[0], deleted_file[1], deleted_file[2]
if path in blacklist or pid in excludepid:
continue
try:
readlink = os.readlink('/proc/{0}/exe'.format(pid))
except OSError:
excludepid.append(pid)
continue
try:
packagename = owners_cache[readlink]
except KeyError:
packagename = __salt__['pkg.owner'](readlink)
if not packagename:
packagename = name
owners_cache[readlink] = packagename
for running_service in running_services:
_check_timeout(start_time, timeout)
if running_service not in restart_services and pid == running_services[running_service]:
if packagename and packagename not in ignorelist:
restart_services.append(running_service)
name = running_service
if packagename and packagename not in ignorelist:
program = '\t' + six.text_type(pid) + ' ' + readlink + ' (file: ' + six.text_type(path) + ')'
if packagename not in packages:
packages[packagename] = {'initscripts': [], 'systemdservice': [], 'processes': [program],
'process_name': name}
else:
if program not in packages[packagename]['processes']:
packages[packagename]['processes'].append(program)
if not packages and not kernel_restart:
return 'No packages seem to need to be restarted.'
for package in packages:
_check_timeout(start_time, timeout)
cmd = cmd_pkg_query + package
paths = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
while True:
_check_timeout(start_time, timeout)
line = salt.utils.stringutils.to_unicode(paths.stdout.readline())
if not line:
break
pth = line[:-1]
if pth.startswith('/etc/init.d/') and not pth.endswith('.sh'):
packages[package]['initscripts'].append(pth[12:])
if os.path.exists(systemd) and pth.startswith(systemd_folder) and pth.endswith('.service') and \
pth.find('.wants') == -1:
is_oneshot = False
try:
servicefile = salt.utils.files.fopen(pth) # pylint: disable=resource-leakage
except IOError:
continue
sysfold_len = len(systemd_folder)
for line in servicefile.readlines():
line = salt.utils.stringutils.to_unicode(line)
if line.find('Type=oneshot') > 0:
# scripts that does a single job and then exit
is_oneshot = True
continue
servicefile.close()
if not is_oneshot:
packages[package]['systemdservice'].append(pth[sysfold_len:])
sys.stdout.flush()
paths.stdout.close()
# Alternatively, find init.d script or service that match the process name
for package in packages:
_check_timeout(start_time, timeout)
if not packages[package]['systemdservice'] and not packages[package]['initscripts']:
service = __salt__['service.available'](packages[package]['process_name'])
if service:
if os.path.exists('/etc/init.d/' + packages[package]['process_name']):
packages[package]['initscripts'].append(packages[package]['process_name'])
else:
packages[package]['systemdservice'].append(packages[package]['process_name'])
restartable = []
nonrestartable = []
restartinitcommands = []
restartservicecommands = []
for package in packages:
_check_timeout(start_time, timeout)
if packages[package]['initscripts']:
restartable.append(package)
restartinitcommands.extend(['service ' + s + ' restart' for s in packages[package]['initscripts']])
elif packages[package]['systemdservice']:
restartable.append(package)
restartservicecommands.extend(['systemctl restart ' + s for s in packages[package]['systemdservice']])
else:
nonrestartable.append(package)
if packages[package]['process_name'] in restart_services:
restart_services.remove(packages[package]['process_name'])
for restart_service in restart_services:
_check_timeout(start_time, timeout)
restartservicecommands.extend(['systemctl restart ' + restart_service])
ret = _format_output(kernel_restart, packages, verbose, restartable, nonrestartable,
restartservicecommands, restartinitcommands)
return ret
|
saltstack/salt
|
salt/modules/restartcheck.py
|
_sysapi_changed_nilrt
|
python
|
def _sysapi_changed_nilrt():
'''
Besides the normal Linux kernel driver interfaces, NILinuxRT-supported hardware features an
extensible, plugin-based device enumeration and configuration interface named "System API".
When an installed package is extending the API it is very hard to know all repercurssions and
actions to be taken, so reboot making sure all drivers are reloaded, hardware reinitialized,
daemons restarted, etc.
Returns:
- True/False depending if nisysapi .ini files got modified/touched
- False if no nisysapi .ini files exist
'''
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path) and _file_changed_nilrt(nisysapi_path):
return True
restartcheck_state_dir = '/var/lib/salt/restartcheck_state'
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
rs_count_file = '{0}/sysapi.conf.d.count'.format(restartcheck_state_dir)
if not os.path.exists(rs_count_file):
return True
with salt.utils.files.fopen(rs_count_file, 'r') as fcount:
current_nb_files = len(os.listdir(nisysapi_conf_d_path))
rs_stored_nb_files = int(fcount.read())
if current_nb_files != rs_stored_nb_files:
return True
for fexpert in os.listdir(nisysapi_conf_d_path):
if _file_changed_nilrt('{0}/{1}'.format(nisysapi_conf_d_path, fexpert)):
return True
return False
|
Besides the normal Linux kernel driver interfaces, NILinuxRT-supported hardware features an
extensible, plugin-based device enumeration and configuration interface named "System API".
When an installed package is extending the API it is very hard to know all repercurssions and
actions to be taken, so reboot making sure all drivers are reloaded, hardware reinitialized,
daemons restarted, etc.
Returns:
- True/False depending if nisysapi .ini files got modified/touched
- False if no nisysapi .ini files exist
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/restartcheck.py#L402-L438
| null |
# -*- coding: utf-8 -*-
'''
checkrestart functionality for Debian and Red Hat Based systems
Identifies services (processes) that are linked against deleted files (for example after downloading an updated
binary of a shared library).
Based on checkrestart script from debian-goodies (written by Matt Zimmerman for the Debian GNU/Linux distribution,
https://packages.debian.org/debian-goodies) and psdel by Sam Morris.
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import subprocess
import sys
import time
# Import salt libs
import salt.exceptions
import salt.utils.args
import salt.utils.files
import salt.utils.path
# Import 3rd partylibs
from salt.ext import six
NILRT_FAMILY_NAME = 'NILinuxRT'
HAS_PSUTIL = False
try:
import psutil
HAS_PSUTIL = True
except ImportError:
pass
LIST_DIRS = [
# We don't care about log files
'^/var/log/',
'^/var/local/log/',
# Or about files under temporary locations
'^/var/run/',
'^/var/local/run/',
# Or about files under /tmp
'^/tmp/',
# Or about files under /dev/shm
'^/dev/shm/',
# Or about files under /run
'^/run/',
# Or about files under /drm
'^/drm',
# Or about files under /var/tmp and /var/local/tmp
'^/var/tmp/',
'^/var/local/tmp/',
# Or /dev/zero
'^/dev/zero',
# Or /dev/pts (used by gpm)
'^/dev/pts/',
# Or /usr/lib/locale
'^/usr/lib/locale/',
# Skip files from the user's home directories
# many processes hold temporafy files there
'^/home/',
# Skip automatically generated files
'^.*icon-theme.cache',
# Skip font files
'^/var/cache/fontconfig/',
# Skip Nagios Spool
'^/var/lib/nagios3/spool/',
# Skip nagios spool files
'^/var/lib/nagios3/spool/checkresults/',
# Skip Postgresql files
'^/var/lib/postgresql/',
# Skip VDR lib files
'^/var/lib/vdr/',
# Skip Aio files found in MySQL servers
'^/[aio]',
# ignore files under /SYSV
'^/SYSV'
]
def __virtual__():
'''
Only run this module if the psutil python module is installed (package python-psutil).
'''
return HAS_PSUTIL
def _valid_deleted_file(path):
'''
Filters file path against unwanted directories and decides whether file is marked as deleted.
Returns:
True if file is desired deleted file, else False.
Args:
path: A string - path to file
'''
ret = False
if path.endswith(' (deleted)'):
ret = True
if re.compile(r"\(path inode=[0-9]+\)$").search(path):
ret = True
regex = re.compile("|".join(LIST_DIRS))
if regex.match(path):
ret = False
return ret
def _deleted_files():
'''
Iterates over /proc/PID/maps and /proc/PID/fd links and returns list of desired deleted files.
Returns:
List of deleted files to analyze, False on failure.
'''
deleted_files = []
for proc in psutil.process_iter(): # pylint: disable=too-many-nested-blocks
try:
pinfo = proc.as_dict(attrs=['pid', 'name'])
try:
with salt.utils.files.fopen('/proc/{0}/maps'.format(pinfo['pid'])) as maps: # pylint: disable=resource-leakage
dirpath = '/proc/' + six.text_type(pinfo['pid']) + '/fd/'
listdir = os.listdir(dirpath)
maplines = maps.readlines()
except (OSError, IOError):
yield False
# /proc/PID/maps
mapline = re.compile(r'^[\da-f]+-[\da-f]+ [r-][w-][x-][sp-] '
r'[\da-f]+ [\da-f]{2}:[\da-f]{2} (\d+) *(.+)( \(deleted\))?\n$')
for line in maplines:
line = salt.utils.stringutils.to_unicode(line)
matched = mapline.match(line)
if not matched:
continue
path = matched.group(2)
if not path:
continue
valid = _valid_deleted_file(path)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], path[0:-10])
if val not in deleted_files:
deleted_files.append(val)
yield val
# /proc/PID/fd
try:
for link in listdir:
path = dirpath + link
readlink = os.readlink(path)
filenames = []
if os.path.isfile(readlink):
filenames.append(readlink)
elif os.path.isdir(readlink) and readlink != '/':
for root, dummy_dirs, files in salt.utils.path.os_walk(readlink, followlinks=True):
for name in files:
filenames.append(os.path.join(root, name))
for filename in filenames:
valid = _valid_deleted_file(filename)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], filename)
if val not in deleted_files:
deleted_files.append(val)
yield val
except OSError:
pass
except psutil.NoSuchProcess:
pass
def _format_output(kernel_restart, packages, verbose, restartable, nonrestartable, restartservicecommands,
restartinitcommands):
'''
Formats the output of the restartcheck module.
Returns:
String - formatted output.
Args:
kernel_restart: indicates that newer kernel is instaled
packages: list of packages that should be restarted
verbose: enables extensive output
restartable: list of restartable packages
nonrestartable: list of non-restartable packages
restartservicecommands: list of commands to restart services
restartinitcommands: list of commands to restart init.d scripts
'''
if not verbose:
packages = restartable + nonrestartable
if kernel_restart:
packages.append('System restart required.')
return packages
else:
ret = ''
if kernel_restart:
ret = 'System restart required.\n\n'
if packages:
ret += "Found {0} processes using old versions of upgraded files.\n".format(len(packages))
ret += "These are the packages:\n"
if restartable:
ret += "Of these, {0} seem to contain systemd service definitions or init scripts " \
"which can be used to restart them:\n".format(len(restartable))
for package in restartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
if restartservicecommands:
ret += "\n\nThese are the systemd services:\n"
ret += '\n'.join(restartservicecommands)
if restartinitcommands:
ret += "\n\nThese are the initd scripts:\n"
ret += '\n'.join(restartinitcommands)
if nonrestartable:
ret += "\n\nThese processes {0} do not seem to have an associated init script " \
"to restart them:\n".format(len(nonrestartable))
for package in nonrestartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
return ret
def _kernel_versions_debian():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kernel_get_selections = __salt__['cmd.run']('dpkg --get-selections linux-image-*')
kernels = []
kernel_versions = []
for line in kernel_get_selections.splitlines():
kernels.append(line)
try:
kernel = kernels[-2]
except IndexError:
kernel = kernels[0]
kernel = kernel.rstrip('\t\tinstall')
kernel_get_version = __salt__['cmd.run']('apt-cache policy ' + kernel)
for line in kernel_get_version.splitlines():
if line.startswith(' Installed: '):
kernel_v = line.strip(' Installed: ')
kernel_versions.append(kernel_v)
break
if __grains__['os'] == 'Ubuntu':
kernel_v = kernel_versions[0].rsplit('.', 1)
kernel_ubuntu_generic = kernel_v[0] + '-generic #' + kernel_v[1]
kernel_ubuntu_lowlatency = kernel_v[0] + '-lowlatency #' + kernel_v[1]
kernel_versions.extend([kernel_ubuntu_generic, kernel_ubuntu_lowlatency])
return kernel_versions
def _kernel_versions_redhat():
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
kernel_get_last = __salt__['cmd.run']('rpm -q --last kernel')
kernels = []
kernel_versions = []
for line in kernel_get_last.splitlines():
if 'kernel-' in line:
kernels.append(line)
kernel = kernels[0].split(' ', 1)[0]
kernel = kernel.strip('kernel-')
kernel_versions.append(kernel)
return kernel_versions
def _kernel_versions_nilrt():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kver = None
def _get_kver_from_bin(kbin):
'''
Get kernel version from a binary image or None if detection fails
'''
kvregex = r'[0-9]+\.[0-9]+\.[0-9]+-rt\S+'
kernel_strings = __salt__['cmd.run']('strings {0}'.format(kbin))
re_result = re.search(kvregex, kernel_strings)
return None if re_result is None else re_result.group(0)
if __grains__.get('lsb_distrib_id') == 'nilrt':
if 'arm' in __grains__.get('cpuarch'):
# the kernel is inside a uboot created itb (FIT) image alongside the
# device tree, ramdisk and a bootscript. There is no package management
# or any other kind of versioning info, so we need to extract the itb.
itb_path = '/boot/linux_runmode.itb'
compressed_kernel = '/var/volatile/tmp/uImage.gz'
uncompressed_kernel = '/var/volatile/tmp/uImage'
__salt__['cmd.run']('dumpimage -i {0} -T flat_dt -p0 kernel -o {1}'
.format(itb_path, compressed_kernel))
__salt__['cmd.run']('gunzip -f {0}'.format(compressed_kernel))
kver = _get_kver_from_bin(uncompressed_kernel)
else:
# the kernel bzImage is copied to rootfs without package management or
# other versioning info.
kver = _get_kver_from_bin('/boot/runmode/bzImage')
else:
# kernels in newer NILRT's are installed via package management and
# have the version appended to the kernel image filename
if 'arm' in __grains__.get('cpuarch'):
kver = os.path.basename(os.readlink('/boot/uImage')).strip('uImage-')
else:
kver = os.path.basename(os.readlink('/boot/bzImage')).strip('bzImage-')
return [] if kver is None else [kver]
def _check_timeout(start_time, timeout):
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
timeout_milisec = timeout * 60000
if timeout_milisec < (int(round(time.time() * 1000)) - start_time):
raise salt.exceptions.TimeoutError('Timeout expired.')
def _file_changed_nilrt(full_filepath):
'''
Detect whether a file changed in an NILinuxRT system using md5sum and timestamp
files from a state directory.
Returns:
- False if md5sum/timestamp state files don't exist
- True/False depending if ``base_filename`` got modified/touched
'''
rs_state_dir = "/var/lib/salt/restartcheck_state"
base_filename = os.path.basename(full_filepath)
timestamp_file = os.path.join(rs_state_dir, '{0}.timestamp'.format(base_filename))
md5sum_file = os.path.join(rs_state_dir, '{0}.md5sum'.format(base_filename))
if not os.path.exists(timestamp_file) or not os.path.exists(md5sum_file):
return True
prev_timestamp = __salt__['file.read'](timestamp_file).rstrip()
# Need timestamp in seconds so floor it using int()
cur_timestamp = str(int(os.path.getmtime(full_filepath)))
if prev_timestamp != cur_timestamp:
return True
return bool(__salt__['cmd.retcode']('md5sum -cs {0}'.format(md5sum_file), output_loglevel="quiet"))
def _kernel_modules_changed_nilrt(kernelversion):
'''
Once a NILRT kernel module is inserted, it can't be rmmod so systems need
rebooting (some modules explicitly ask for reboots even on first install),
hence this functionality of determining if the module state got modified by
testing if depmod was run.
Returns:
- True/False depending if modules.dep got modified/touched
'''
if kernelversion is not None:
return _file_changed_nilrt('/lib/modules/{0}/modules.dep'.format(kernelversion))
return False
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
def restartcheck(ignorelist=None, blacklist=None, excludepid=None, **kwargs):
'''
Analyzes files openeded by running processes and seeks for packages which need to be restarted.
Args:
ignorelist: string or list of packages to be ignored
blacklist: string or list of file paths to be ignored
excludepid: string or list of process IDs to be ignored
verbose: boolean, enables extensive output
timeout: int, timeout in minute
Returns:
Dict on error: { 'result': False, 'comment': '<reason>' }
String with checkrestart output if some package seems to need to be restarted or
if no packages need restarting.
.. versionadded:: 2015.8.3
CLI Example:
.. code-block:: bash
salt '*' restartcheck.restartcheck
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
start_time = int(round(time.time() * 1000))
kernel_restart = True
verbose = kwargs.pop('verbose', True)
timeout = kwargs.pop('timeout', 5)
if __grains__.get('os_family') == 'Debian':
cmd_pkg_query = 'dpkg-query --listfiles '
systemd_folder = '/lib/systemd/system/'
systemd = '/bin/systemd'
kernel_versions = _kernel_versions_debian()
elif __grains__.get('os_family') == 'RedHat':
cmd_pkg_query = 'repoquery -l '
systemd_folder = '/usr/lib/systemd/system/'
systemd = '/usr/bin/systemctl'
kernel_versions = _kernel_versions_redhat()
elif __grains__.get('os_family') == NILRT_FAMILY_NAME:
cmd_pkg_query = 'opkg files '
systemd = ''
kernel_versions = _kernel_versions_nilrt()
else:
return {'result': False, 'comment': 'Only available on Debian, Red Hat and NI Linux Real-Time based systems.'}
# Check kernel versions
kernel_current = __salt__['cmd.run']('uname -a')
for kernel in kernel_versions:
_check_timeout(start_time, timeout)
if kernel in kernel_current:
if __grains__.get('os_family') == 'NILinuxRT':
# Check kernel modules and hardware API's for version changes
# If a restartcheck=True event was previously witnessed, propagate it
if not _kernel_modules_changed_nilrt(kernel) and \
not _sysapi_changed_nilrt() and \
not __salt__['system.get_reboot_required_witnessed']():
kernel_restart = False
break
else:
kernel_restart = False
break
packages = {}
running_services = {}
restart_services = []
if ignorelist:
if not isinstance(ignorelist, list):
ignorelist = [ignorelist]
else:
ignorelist = ['screen', 'systemd']
if blacklist:
if not isinstance(blacklist, list):
blacklist = [blacklist]
else:
blacklist = []
if excludepid:
if not isinstance(excludepid, list):
excludepid = [excludepid]
else:
excludepid = []
for service in __salt__['service.get_running']():
_check_timeout(start_time, timeout)
service_show = __salt__['service.show'](service)
if 'ExecMainPID' in service_show:
running_services[service] = int(service_show['ExecMainPID'])
owners_cache = {}
for deleted_file in _deleted_files():
if deleted_file is False:
return {'result': False, 'comment': 'Could not get list of processes.'
' (Do you have root access?)'}
_check_timeout(start_time, timeout)
name, pid, path = deleted_file[0], deleted_file[1], deleted_file[2]
if path in blacklist or pid in excludepid:
continue
try:
readlink = os.readlink('/proc/{0}/exe'.format(pid))
except OSError:
excludepid.append(pid)
continue
try:
packagename = owners_cache[readlink]
except KeyError:
packagename = __salt__['pkg.owner'](readlink)
if not packagename:
packagename = name
owners_cache[readlink] = packagename
for running_service in running_services:
_check_timeout(start_time, timeout)
if running_service not in restart_services and pid == running_services[running_service]:
if packagename and packagename not in ignorelist:
restart_services.append(running_service)
name = running_service
if packagename and packagename not in ignorelist:
program = '\t' + six.text_type(pid) + ' ' + readlink + ' (file: ' + six.text_type(path) + ')'
if packagename not in packages:
packages[packagename] = {'initscripts': [], 'systemdservice': [], 'processes': [program],
'process_name': name}
else:
if program not in packages[packagename]['processes']:
packages[packagename]['processes'].append(program)
if not packages and not kernel_restart:
return 'No packages seem to need to be restarted.'
for package in packages:
_check_timeout(start_time, timeout)
cmd = cmd_pkg_query + package
paths = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
while True:
_check_timeout(start_time, timeout)
line = salt.utils.stringutils.to_unicode(paths.stdout.readline())
if not line:
break
pth = line[:-1]
if pth.startswith('/etc/init.d/') and not pth.endswith('.sh'):
packages[package]['initscripts'].append(pth[12:])
if os.path.exists(systemd) and pth.startswith(systemd_folder) and pth.endswith('.service') and \
pth.find('.wants') == -1:
is_oneshot = False
try:
servicefile = salt.utils.files.fopen(pth) # pylint: disable=resource-leakage
except IOError:
continue
sysfold_len = len(systemd_folder)
for line in servicefile.readlines():
line = salt.utils.stringutils.to_unicode(line)
if line.find('Type=oneshot') > 0:
# scripts that does a single job and then exit
is_oneshot = True
continue
servicefile.close()
if not is_oneshot:
packages[package]['systemdservice'].append(pth[sysfold_len:])
sys.stdout.flush()
paths.stdout.close()
# Alternatively, find init.d script or service that match the process name
for package in packages:
_check_timeout(start_time, timeout)
if not packages[package]['systemdservice'] and not packages[package]['initscripts']:
service = __salt__['service.available'](packages[package]['process_name'])
if service:
if os.path.exists('/etc/init.d/' + packages[package]['process_name']):
packages[package]['initscripts'].append(packages[package]['process_name'])
else:
packages[package]['systemdservice'].append(packages[package]['process_name'])
restartable = []
nonrestartable = []
restartinitcommands = []
restartservicecommands = []
for package in packages:
_check_timeout(start_time, timeout)
if packages[package]['initscripts']:
restartable.append(package)
restartinitcommands.extend(['service ' + s + ' restart' for s in packages[package]['initscripts']])
elif packages[package]['systemdservice']:
restartable.append(package)
restartservicecommands.extend(['systemctl restart ' + s for s in packages[package]['systemdservice']])
else:
nonrestartable.append(package)
if packages[package]['process_name'] in restart_services:
restart_services.remove(packages[package]['process_name'])
for restart_service in restart_services:
_check_timeout(start_time, timeout)
restartservicecommands.extend(['systemctl restart ' + restart_service])
ret = _format_output(kernel_restart, packages, verbose, restartable, nonrestartable,
restartservicecommands, restartinitcommands)
return ret
|
saltstack/salt
|
salt/modules/restartcheck.py
|
restartcheck
|
python
|
def restartcheck(ignorelist=None, blacklist=None, excludepid=None, **kwargs):
'''
Analyzes files openeded by running processes and seeks for packages which need to be restarted.
Args:
ignorelist: string or list of packages to be ignored
blacklist: string or list of file paths to be ignored
excludepid: string or list of process IDs to be ignored
verbose: boolean, enables extensive output
timeout: int, timeout in minute
Returns:
Dict on error: { 'result': False, 'comment': '<reason>' }
String with checkrestart output if some package seems to need to be restarted or
if no packages need restarting.
.. versionadded:: 2015.8.3
CLI Example:
.. code-block:: bash
salt '*' restartcheck.restartcheck
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
start_time = int(round(time.time() * 1000))
kernel_restart = True
verbose = kwargs.pop('verbose', True)
timeout = kwargs.pop('timeout', 5)
if __grains__.get('os_family') == 'Debian':
cmd_pkg_query = 'dpkg-query --listfiles '
systemd_folder = '/lib/systemd/system/'
systemd = '/bin/systemd'
kernel_versions = _kernel_versions_debian()
elif __grains__.get('os_family') == 'RedHat':
cmd_pkg_query = 'repoquery -l '
systemd_folder = '/usr/lib/systemd/system/'
systemd = '/usr/bin/systemctl'
kernel_versions = _kernel_versions_redhat()
elif __grains__.get('os_family') == NILRT_FAMILY_NAME:
cmd_pkg_query = 'opkg files '
systemd = ''
kernel_versions = _kernel_versions_nilrt()
else:
return {'result': False, 'comment': 'Only available on Debian, Red Hat and NI Linux Real-Time based systems.'}
# Check kernel versions
kernel_current = __salt__['cmd.run']('uname -a')
for kernel in kernel_versions:
_check_timeout(start_time, timeout)
if kernel in kernel_current:
if __grains__.get('os_family') == 'NILinuxRT':
# Check kernel modules and hardware API's for version changes
# If a restartcheck=True event was previously witnessed, propagate it
if not _kernel_modules_changed_nilrt(kernel) and \
not _sysapi_changed_nilrt() and \
not __salt__['system.get_reboot_required_witnessed']():
kernel_restart = False
break
else:
kernel_restart = False
break
packages = {}
running_services = {}
restart_services = []
if ignorelist:
if not isinstance(ignorelist, list):
ignorelist = [ignorelist]
else:
ignorelist = ['screen', 'systemd']
if blacklist:
if not isinstance(blacklist, list):
blacklist = [blacklist]
else:
blacklist = []
if excludepid:
if not isinstance(excludepid, list):
excludepid = [excludepid]
else:
excludepid = []
for service in __salt__['service.get_running']():
_check_timeout(start_time, timeout)
service_show = __salt__['service.show'](service)
if 'ExecMainPID' in service_show:
running_services[service] = int(service_show['ExecMainPID'])
owners_cache = {}
for deleted_file in _deleted_files():
if deleted_file is False:
return {'result': False, 'comment': 'Could not get list of processes.'
' (Do you have root access?)'}
_check_timeout(start_time, timeout)
name, pid, path = deleted_file[0], deleted_file[1], deleted_file[2]
if path in blacklist or pid in excludepid:
continue
try:
readlink = os.readlink('/proc/{0}/exe'.format(pid))
except OSError:
excludepid.append(pid)
continue
try:
packagename = owners_cache[readlink]
except KeyError:
packagename = __salt__['pkg.owner'](readlink)
if not packagename:
packagename = name
owners_cache[readlink] = packagename
for running_service in running_services:
_check_timeout(start_time, timeout)
if running_service not in restart_services and pid == running_services[running_service]:
if packagename and packagename not in ignorelist:
restart_services.append(running_service)
name = running_service
if packagename and packagename not in ignorelist:
program = '\t' + six.text_type(pid) + ' ' + readlink + ' (file: ' + six.text_type(path) + ')'
if packagename not in packages:
packages[packagename] = {'initscripts': [], 'systemdservice': [], 'processes': [program],
'process_name': name}
else:
if program not in packages[packagename]['processes']:
packages[packagename]['processes'].append(program)
if not packages and not kernel_restart:
return 'No packages seem to need to be restarted.'
for package in packages:
_check_timeout(start_time, timeout)
cmd = cmd_pkg_query + package
paths = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
while True:
_check_timeout(start_time, timeout)
line = salt.utils.stringutils.to_unicode(paths.stdout.readline())
if not line:
break
pth = line[:-1]
if pth.startswith('/etc/init.d/') and not pth.endswith('.sh'):
packages[package]['initscripts'].append(pth[12:])
if os.path.exists(systemd) and pth.startswith(systemd_folder) and pth.endswith('.service') and \
pth.find('.wants') == -1:
is_oneshot = False
try:
servicefile = salt.utils.files.fopen(pth) # pylint: disable=resource-leakage
except IOError:
continue
sysfold_len = len(systemd_folder)
for line in servicefile.readlines():
line = salt.utils.stringutils.to_unicode(line)
if line.find('Type=oneshot') > 0:
# scripts that does a single job and then exit
is_oneshot = True
continue
servicefile.close()
if not is_oneshot:
packages[package]['systemdservice'].append(pth[sysfold_len:])
sys.stdout.flush()
paths.stdout.close()
# Alternatively, find init.d script or service that match the process name
for package in packages:
_check_timeout(start_time, timeout)
if not packages[package]['systemdservice'] and not packages[package]['initscripts']:
service = __salt__['service.available'](packages[package]['process_name'])
if service:
if os.path.exists('/etc/init.d/' + packages[package]['process_name']):
packages[package]['initscripts'].append(packages[package]['process_name'])
else:
packages[package]['systemdservice'].append(packages[package]['process_name'])
restartable = []
nonrestartable = []
restartinitcommands = []
restartservicecommands = []
for package in packages:
_check_timeout(start_time, timeout)
if packages[package]['initscripts']:
restartable.append(package)
restartinitcommands.extend(['service ' + s + ' restart' for s in packages[package]['initscripts']])
elif packages[package]['systemdservice']:
restartable.append(package)
restartservicecommands.extend(['systemctl restart ' + s for s in packages[package]['systemdservice']])
else:
nonrestartable.append(package)
if packages[package]['process_name'] in restart_services:
restart_services.remove(packages[package]['process_name'])
for restart_service in restart_services:
_check_timeout(start_time, timeout)
restartservicecommands.extend(['systemctl restart ' + restart_service])
ret = _format_output(kernel_restart, packages, verbose, restartable, nonrestartable,
restartservicecommands, restartinitcommands)
return ret
|
Analyzes files openeded by running processes and seeks for packages which need to be restarted.
Args:
ignorelist: string or list of packages to be ignored
blacklist: string or list of file paths to be ignored
excludepid: string or list of process IDs to be ignored
verbose: boolean, enables extensive output
timeout: int, timeout in minute
Returns:
Dict on error: { 'result': False, 'comment': '<reason>' }
String with checkrestart output if some package seems to need to be restarted or
if no packages need restarting.
.. versionadded:: 2015.8.3
CLI Example:
.. code-block:: bash
salt '*' restartcheck.restartcheck
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/restartcheck.py#L442-L645
|
[
"def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n",
"def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n",
"def _check_timeout(start_time, timeout):\n '''\n Name of the last installed kernel, for Red Hat based systems.\n\n Returns:\n List with name of last installed kernel as it is interpreted in output of `uname -a` command.\n '''\n timeout_milisec = timeout * 60000\n if timeout_milisec < (int(round(time.time() * 1000)) - start_time):\n raise salt.exceptions.TimeoutError('Timeout expired.')\n",
"def _deleted_files():\n '''\n Iterates over /proc/PID/maps and /proc/PID/fd links and returns list of desired deleted files.\n\n Returns:\n List of deleted files to analyze, False on failure.\n\n '''\n deleted_files = []\n\n for proc in psutil.process_iter(): # pylint: disable=too-many-nested-blocks\n try:\n pinfo = proc.as_dict(attrs=['pid', 'name'])\n try:\n with salt.utils.files.fopen('/proc/{0}/maps'.format(pinfo['pid'])) as maps: # pylint: disable=resource-leakage\n dirpath = '/proc/' + six.text_type(pinfo['pid']) + '/fd/'\n listdir = os.listdir(dirpath)\n maplines = maps.readlines()\n except (OSError, IOError):\n yield False\n\n # /proc/PID/maps\n mapline = re.compile(r'^[\\da-f]+-[\\da-f]+ [r-][w-][x-][sp-] '\n r'[\\da-f]+ [\\da-f]{2}:[\\da-f]{2} (\\d+) *(.+)( \\(deleted\\))?\\n$')\n\n for line in maplines:\n line = salt.utils.stringutils.to_unicode(line)\n matched = mapline.match(line)\n if not matched:\n continue\n path = matched.group(2)\n if not path:\n continue\n valid = _valid_deleted_file(path)\n if not valid:\n continue\n val = (pinfo['name'], pinfo['pid'], path[0:-10])\n if val not in deleted_files:\n deleted_files.append(val)\n yield val\n\n # /proc/PID/fd\n try:\n for link in listdir:\n path = dirpath + link\n readlink = os.readlink(path)\n filenames = []\n\n if os.path.isfile(readlink):\n filenames.append(readlink)\n elif os.path.isdir(readlink) and readlink != '/':\n for root, dummy_dirs, files in salt.utils.path.os_walk(readlink, followlinks=True):\n for name in files:\n filenames.append(os.path.join(root, name))\n\n for filename in filenames:\n valid = _valid_deleted_file(filename)\n if not valid:\n continue\n val = (pinfo['name'], pinfo['pid'], filename)\n if val not in deleted_files:\n deleted_files.append(val)\n yield val\n except OSError:\n pass\n\n except psutil.NoSuchProcess:\n pass\n",
"def _format_output(kernel_restart, packages, verbose, restartable, nonrestartable, restartservicecommands,\n restartinitcommands):\n '''\n Formats the output of the restartcheck module.\n\n Returns:\n String - formatted output.\n\n Args:\n kernel_restart: indicates that newer kernel is instaled\n packages: list of packages that should be restarted\n verbose: enables extensive output\n restartable: list of restartable packages\n nonrestartable: list of non-restartable packages\n restartservicecommands: list of commands to restart services\n restartinitcommands: list of commands to restart init.d scripts\n\n '''\n if not verbose:\n packages = restartable + nonrestartable\n if kernel_restart:\n packages.append('System restart required.')\n return packages\n else:\n ret = ''\n if kernel_restart:\n ret = 'System restart required.\\n\\n'\n\n if packages:\n ret += \"Found {0} processes using old versions of upgraded files.\\n\".format(len(packages))\n ret += \"These are the packages:\\n\"\n\n if restartable:\n ret += \"Of these, {0} seem to contain systemd service definitions or init scripts \" \\\n \"which can be used to restart them:\\n\".format(len(restartable))\n for package in restartable:\n ret += package + ':\\n'\n for program in packages[package]['processes']:\n ret += program + '\\n'\n\n if restartservicecommands:\n ret += \"\\n\\nThese are the systemd services:\\n\"\n ret += '\\n'.join(restartservicecommands)\n\n if restartinitcommands:\n ret += \"\\n\\nThese are the initd scripts:\\n\"\n ret += '\\n'.join(restartinitcommands)\n\n if nonrestartable:\n ret += \"\\n\\nThese processes {0} do not seem to have an associated init script \" \\\n \"to restart them:\\n\".format(len(nonrestartable))\n for package in nonrestartable:\n ret += package + ':\\n'\n for program in packages[package]['processes']:\n ret += program + '\\n'\n return ret\n",
"def _kernel_versions_debian():\n '''\n Last installed kernel name, for Debian based systems.\n\n Returns:\n List with possible names of last installed kernel\n as they are probably interpreted in output of `uname -a` command.\n '''\n kernel_get_selections = __salt__['cmd.run']('dpkg --get-selections linux-image-*')\n kernels = []\n kernel_versions = []\n for line in kernel_get_selections.splitlines():\n kernels.append(line)\n\n try:\n kernel = kernels[-2]\n except IndexError:\n kernel = kernels[0]\n\n kernel = kernel.rstrip('\\t\\tinstall')\n\n kernel_get_version = __salt__['cmd.run']('apt-cache policy ' + kernel)\n\n for line in kernel_get_version.splitlines():\n if line.startswith(' Installed: '):\n kernel_v = line.strip(' Installed: ')\n kernel_versions.append(kernel_v)\n break\n\n if __grains__['os'] == 'Ubuntu':\n kernel_v = kernel_versions[0].rsplit('.', 1)\n kernel_ubuntu_generic = kernel_v[0] + '-generic #' + kernel_v[1]\n kernel_ubuntu_lowlatency = kernel_v[0] + '-lowlatency #' + kernel_v[1]\n kernel_versions.extend([kernel_ubuntu_generic, kernel_ubuntu_lowlatency])\n\n return kernel_versions\n",
"def _kernel_versions_redhat():\n '''\n Name of the last installed kernel, for Red Hat based systems.\n\n Returns:\n List with name of last installed kernel as it is interpreted in output of `uname -a` command.\n '''\n kernel_get_last = __salt__['cmd.run']('rpm -q --last kernel')\n kernels = []\n kernel_versions = []\n for line in kernel_get_last.splitlines():\n if 'kernel-' in line:\n kernels.append(line)\n\n kernel = kernels[0].split(' ', 1)[0]\n kernel = kernel.strip('kernel-')\n kernel_versions.append(kernel)\n\n return kernel_versions\n",
"def _kernel_versions_nilrt():\n '''\n Last installed kernel name, for Debian based systems.\n\n Returns:\n List with possible names of last installed kernel\n as they are probably interpreted in output of `uname -a` command.\n '''\n kver = None\n\n def _get_kver_from_bin(kbin):\n '''\n Get kernel version from a binary image or None if detection fails\n '''\n kvregex = r'[0-9]+\\.[0-9]+\\.[0-9]+-rt\\S+'\n kernel_strings = __salt__['cmd.run']('strings {0}'.format(kbin))\n re_result = re.search(kvregex, kernel_strings)\n return None if re_result is None else re_result.group(0)\n\n if __grains__.get('lsb_distrib_id') == 'nilrt':\n if 'arm' in __grains__.get('cpuarch'):\n # the kernel is inside a uboot created itb (FIT) image alongside the\n # device tree, ramdisk and a bootscript. There is no package management\n # or any other kind of versioning info, so we need to extract the itb.\n itb_path = '/boot/linux_runmode.itb'\n compressed_kernel = '/var/volatile/tmp/uImage.gz'\n uncompressed_kernel = '/var/volatile/tmp/uImage'\n __salt__['cmd.run']('dumpimage -i {0} -T flat_dt -p0 kernel -o {1}'\n .format(itb_path, compressed_kernel))\n __salt__['cmd.run']('gunzip -f {0}'.format(compressed_kernel))\n kver = _get_kver_from_bin(uncompressed_kernel)\n else:\n # the kernel bzImage is copied to rootfs without package management or\n # other versioning info.\n kver = _get_kver_from_bin('/boot/runmode/bzImage')\n else:\n # kernels in newer NILRT's are installed via package management and\n # have the version appended to the kernel image filename\n if 'arm' in __grains__.get('cpuarch'):\n kver = os.path.basename(os.readlink('/boot/uImage')).strip('uImage-')\n else:\n kver = os.path.basename(os.readlink('/boot/bzImage')).strip('bzImage-')\n\n return [] if kver is None else [kver]\n",
"def _kernel_modules_changed_nilrt(kernelversion):\n '''\n Once a NILRT kernel module is inserted, it can't be rmmod so systems need\n rebooting (some modules explicitly ask for reboots even on first install),\n hence this functionality of determining if the module state got modified by\n testing if depmod was run.\n\n Returns:\n - True/False depending if modules.dep got modified/touched\n '''\n if kernelversion is not None:\n return _file_changed_nilrt('/lib/modules/{0}/modules.dep'.format(kernelversion))\n return False\n",
"def _sysapi_changed_nilrt():\n '''\n Besides the normal Linux kernel driver interfaces, NILinuxRT-supported hardware features an\n extensible, plugin-based device enumeration and configuration interface named \"System API\".\n When an installed package is extending the API it is very hard to know all repercurssions and\n actions to be taken, so reboot making sure all drivers are reloaded, hardware reinitialized,\n daemons restarted, etc.\n\n Returns:\n - True/False depending if nisysapi .ini files got modified/touched\n - False if no nisysapi .ini files exist\n '''\n nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'\n if os.path.exists(nisysapi_path) and _file_changed_nilrt(nisysapi_path):\n return True\n\n restartcheck_state_dir = '/var/lib/salt/restartcheck_state'\n nisysapi_conf_d_path = \"/usr/lib/{0}/nisysapi/conf.d/experts/\".format(\n 'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'\n )\n\n if os.path.exists(nisysapi_conf_d_path):\n rs_count_file = '{0}/sysapi.conf.d.count'.format(restartcheck_state_dir)\n if not os.path.exists(rs_count_file):\n return True\n\n with salt.utils.files.fopen(rs_count_file, 'r') as fcount:\n current_nb_files = len(os.listdir(nisysapi_conf_d_path))\n rs_stored_nb_files = int(fcount.read())\n if current_nb_files != rs_stored_nb_files:\n return True\n\n for fexpert in os.listdir(nisysapi_conf_d_path):\n if _file_changed_nilrt('{0}/{1}'.format(nisysapi_conf_d_path, fexpert)):\n return True\n\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
checkrestart functionality for Debian and Red Hat Based systems
Identifies services (processes) that are linked against deleted files (for example after downloading an updated
binary of a shared library).
Based on checkrestart script from debian-goodies (written by Matt Zimmerman for the Debian GNU/Linux distribution,
https://packages.debian.org/debian-goodies) and psdel by Sam Morris.
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
import subprocess
import sys
import time
# Import salt libs
import salt.exceptions
import salt.utils.args
import salt.utils.files
import salt.utils.path
# Import 3rd partylibs
from salt.ext import six
NILRT_FAMILY_NAME = 'NILinuxRT'
HAS_PSUTIL = False
try:
import psutil
HAS_PSUTIL = True
except ImportError:
pass
LIST_DIRS = [
# We don't care about log files
'^/var/log/',
'^/var/local/log/',
# Or about files under temporary locations
'^/var/run/',
'^/var/local/run/',
# Or about files under /tmp
'^/tmp/',
# Or about files under /dev/shm
'^/dev/shm/',
# Or about files under /run
'^/run/',
# Or about files under /drm
'^/drm',
# Or about files under /var/tmp and /var/local/tmp
'^/var/tmp/',
'^/var/local/tmp/',
# Or /dev/zero
'^/dev/zero',
# Or /dev/pts (used by gpm)
'^/dev/pts/',
# Or /usr/lib/locale
'^/usr/lib/locale/',
# Skip files from the user's home directories
# many processes hold temporafy files there
'^/home/',
# Skip automatically generated files
'^.*icon-theme.cache',
# Skip font files
'^/var/cache/fontconfig/',
# Skip Nagios Spool
'^/var/lib/nagios3/spool/',
# Skip nagios spool files
'^/var/lib/nagios3/spool/checkresults/',
# Skip Postgresql files
'^/var/lib/postgresql/',
# Skip VDR lib files
'^/var/lib/vdr/',
# Skip Aio files found in MySQL servers
'^/[aio]',
# ignore files under /SYSV
'^/SYSV'
]
def __virtual__():
'''
Only run this module if the psutil python module is installed (package python-psutil).
'''
return HAS_PSUTIL
def _valid_deleted_file(path):
'''
Filters file path against unwanted directories and decides whether file is marked as deleted.
Returns:
True if file is desired deleted file, else False.
Args:
path: A string - path to file
'''
ret = False
if path.endswith(' (deleted)'):
ret = True
if re.compile(r"\(path inode=[0-9]+\)$").search(path):
ret = True
regex = re.compile("|".join(LIST_DIRS))
if regex.match(path):
ret = False
return ret
def _deleted_files():
'''
Iterates over /proc/PID/maps and /proc/PID/fd links and returns list of desired deleted files.
Returns:
List of deleted files to analyze, False on failure.
'''
deleted_files = []
for proc in psutil.process_iter(): # pylint: disable=too-many-nested-blocks
try:
pinfo = proc.as_dict(attrs=['pid', 'name'])
try:
with salt.utils.files.fopen('/proc/{0}/maps'.format(pinfo['pid'])) as maps: # pylint: disable=resource-leakage
dirpath = '/proc/' + six.text_type(pinfo['pid']) + '/fd/'
listdir = os.listdir(dirpath)
maplines = maps.readlines()
except (OSError, IOError):
yield False
# /proc/PID/maps
mapline = re.compile(r'^[\da-f]+-[\da-f]+ [r-][w-][x-][sp-] '
r'[\da-f]+ [\da-f]{2}:[\da-f]{2} (\d+) *(.+)( \(deleted\))?\n$')
for line in maplines:
line = salt.utils.stringutils.to_unicode(line)
matched = mapline.match(line)
if not matched:
continue
path = matched.group(2)
if not path:
continue
valid = _valid_deleted_file(path)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], path[0:-10])
if val not in deleted_files:
deleted_files.append(val)
yield val
# /proc/PID/fd
try:
for link in listdir:
path = dirpath + link
readlink = os.readlink(path)
filenames = []
if os.path.isfile(readlink):
filenames.append(readlink)
elif os.path.isdir(readlink) and readlink != '/':
for root, dummy_dirs, files in salt.utils.path.os_walk(readlink, followlinks=True):
for name in files:
filenames.append(os.path.join(root, name))
for filename in filenames:
valid = _valid_deleted_file(filename)
if not valid:
continue
val = (pinfo['name'], pinfo['pid'], filename)
if val not in deleted_files:
deleted_files.append(val)
yield val
except OSError:
pass
except psutil.NoSuchProcess:
pass
def _format_output(kernel_restart, packages, verbose, restartable, nonrestartable, restartservicecommands,
restartinitcommands):
'''
Formats the output of the restartcheck module.
Returns:
String - formatted output.
Args:
kernel_restart: indicates that newer kernel is instaled
packages: list of packages that should be restarted
verbose: enables extensive output
restartable: list of restartable packages
nonrestartable: list of non-restartable packages
restartservicecommands: list of commands to restart services
restartinitcommands: list of commands to restart init.d scripts
'''
if not verbose:
packages = restartable + nonrestartable
if kernel_restart:
packages.append('System restart required.')
return packages
else:
ret = ''
if kernel_restart:
ret = 'System restart required.\n\n'
if packages:
ret += "Found {0} processes using old versions of upgraded files.\n".format(len(packages))
ret += "These are the packages:\n"
if restartable:
ret += "Of these, {0} seem to contain systemd service definitions or init scripts " \
"which can be used to restart them:\n".format(len(restartable))
for package in restartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
if restartservicecommands:
ret += "\n\nThese are the systemd services:\n"
ret += '\n'.join(restartservicecommands)
if restartinitcommands:
ret += "\n\nThese are the initd scripts:\n"
ret += '\n'.join(restartinitcommands)
if nonrestartable:
ret += "\n\nThese processes {0} do not seem to have an associated init script " \
"to restart them:\n".format(len(nonrestartable))
for package in nonrestartable:
ret += package + ':\n'
for program in packages[package]['processes']:
ret += program + '\n'
return ret
def _kernel_versions_debian():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kernel_get_selections = __salt__['cmd.run']('dpkg --get-selections linux-image-*')
kernels = []
kernel_versions = []
for line in kernel_get_selections.splitlines():
kernels.append(line)
try:
kernel = kernels[-2]
except IndexError:
kernel = kernels[0]
kernel = kernel.rstrip('\t\tinstall')
kernel_get_version = __salt__['cmd.run']('apt-cache policy ' + kernel)
for line in kernel_get_version.splitlines():
if line.startswith(' Installed: '):
kernel_v = line.strip(' Installed: ')
kernel_versions.append(kernel_v)
break
if __grains__['os'] == 'Ubuntu':
kernel_v = kernel_versions[0].rsplit('.', 1)
kernel_ubuntu_generic = kernel_v[0] + '-generic #' + kernel_v[1]
kernel_ubuntu_lowlatency = kernel_v[0] + '-lowlatency #' + kernel_v[1]
kernel_versions.extend([kernel_ubuntu_generic, kernel_ubuntu_lowlatency])
return kernel_versions
def _kernel_versions_redhat():
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
kernel_get_last = __salt__['cmd.run']('rpm -q --last kernel')
kernels = []
kernel_versions = []
for line in kernel_get_last.splitlines():
if 'kernel-' in line:
kernels.append(line)
kernel = kernels[0].split(' ', 1)[0]
kernel = kernel.strip('kernel-')
kernel_versions.append(kernel)
return kernel_versions
def _kernel_versions_nilrt():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kver = None
def _get_kver_from_bin(kbin):
'''
Get kernel version from a binary image or None if detection fails
'''
kvregex = r'[0-9]+\.[0-9]+\.[0-9]+-rt\S+'
kernel_strings = __salt__['cmd.run']('strings {0}'.format(kbin))
re_result = re.search(kvregex, kernel_strings)
return None if re_result is None else re_result.group(0)
if __grains__.get('lsb_distrib_id') == 'nilrt':
if 'arm' in __grains__.get('cpuarch'):
# the kernel is inside a uboot created itb (FIT) image alongside the
# device tree, ramdisk and a bootscript. There is no package management
# or any other kind of versioning info, so we need to extract the itb.
itb_path = '/boot/linux_runmode.itb'
compressed_kernel = '/var/volatile/tmp/uImage.gz'
uncompressed_kernel = '/var/volatile/tmp/uImage'
__salt__['cmd.run']('dumpimage -i {0} -T flat_dt -p0 kernel -o {1}'
.format(itb_path, compressed_kernel))
__salt__['cmd.run']('gunzip -f {0}'.format(compressed_kernel))
kver = _get_kver_from_bin(uncompressed_kernel)
else:
# the kernel bzImage is copied to rootfs without package management or
# other versioning info.
kver = _get_kver_from_bin('/boot/runmode/bzImage')
else:
# kernels in newer NILRT's are installed via package management and
# have the version appended to the kernel image filename
if 'arm' in __grains__.get('cpuarch'):
kver = os.path.basename(os.readlink('/boot/uImage')).strip('uImage-')
else:
kver = os.path.basename(os.readlink('/boot/bzImage')).strip('bzImage-')
return [] if kver is None else [kver]
def _check_timeout(start_time, timeout):
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
timeout_milisec = timeout * 60000
if timeout_milisec < (int(round(time.time() * 1000)) - start_time):
raise salt.exceptions.TimeoutError('Timeout expired.')
def _file_changed_nilrt(full_filepath):
'''
Detect whether a file changed in an NILinuxRT system using md5sum and timestamp
files from a state directory.
Returns:
- False if md5sum/timestamp state files don't exist
- True/False depending if ``base_filename`` got modified/touched
'''
rs_state_dir = "/var/lib/salt/restartcheck_state"
base_filename = os.path.basename(full_filepath)
timestamp_file = os.path.join(rs_state_dir, '{0}.timestamp'.format(base_filename))
md5sum_file = os.path.join(rs_state_dir, '{0}.md5sum'.format(base_filename))
if not os.path.exists(timestamp_file) or not os.path.exists(md5sum_file):
return True
prev_timestamp = __salt__['file.read'](timestamp_file).rstrip()
# Need timestamp in seconds so floor it using int()
cur_timestamp = str(int(os.path.getmtime(full_filepath)))
if prev_timestamp != cur_timestamp:
return True
return bool(__salt__['cmd.retcode']('md5sum -cs {0}'.format(md5sum_file), output_loglevel="quiet"))
def _kernel_modules_changed_nilrt(kernelversion):
'''
Once a NILRT kernel module is inserted, it can't be rmmod so systems need
rebooting (some modules explicitly ask for reboots even on first install),
hence this functionality of determining if the module state got modified by
testing if depmod was run.
Returns:
- True/False depending if modules.dep got modified/touched
'''
if kernelversion is not None:
return _file_changed_nilrt('/lib/modules/{0}/modules.dep'.format(kernelversion))
return False
def _sysapi_changed_nilrt():
'''
Besides the normal Linux kernel driver interfaces, NILinuxRT-supported hardware features an
extensible, plugin-based device enumeration and configuration interface named "System API".
When an installed package is extending the API it is very hard to know all repercurssions and
actions to be taken, so reboot making sure all drivers are reloaded, hardware reinitialized,
daemons restarted, etc.
Returns:
- True/False depending if nisysapi .ini files got modified/touched
- False if no nisysapi .ini files exist
'''
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path) and _file_changed_nilrt(nisysapi_path):
return True
restartcheck_state_dir = '/var/lib/salt/restartcheck_state'
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
rs_count_file = '{0}/sysapi.conf.d.count'.format(restartcheck_state_dir)
if not os.path.exists(rs_count_file):
return True
with salt.utils.files.fopen(rs_count_file, 'r') as fcount:
current_nb_files = len(os.listdir(nisysapi_conf_d_path))
rs_stored_nb_files = int(fcount.read())
if current_nb_files != rs_stored_nb_files:
return True
for fexpert in os.listdir(nisysapi_conf_d_path):
if _file_changed_nilrt('{0}/{1}'.format(nisysapi_conf_d_path, fexpert)):
return True
return False
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
|
saltstack/salt
|
salt/states/pbm.py
|
default_vsan_policy_configured
|
python
|
def default_vsan_policy_configured(name, policy):
'''
Configures the default VSAN policy on a vCenter.
The state assumes there is only one default VSAN policy on a vCenter.
policy
Dict representation of a policy
'''
# TODO Refactor when recurse_differ supports list_differ
# It's going to make the whole thing much easier
policy_copy = copy.deepcopy(policy)
proxy_type = __salt__['vsphere.get_proxy_type']()
log.trace('proxy_type = %s', proxy_type)
# All allowed proxies have a shim execution module with the same
# name which implementes a get_details function
# All allowed proxies have a vcenter detail
vcenter = __salt__['{0}.get_details'.format(proxy_type)]()['vcenter']
log.info('Running %s on vCenter \'%s\'', name, vcenter)
log.trace('policy = %s', policy)
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
comments = []
changes = {}
changes_required = False
si = None
try:
#TODO policy schema validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
current_policy = __salt__['vsphere.list_default_vsan_policy'](si)
log.trace('current_policy = %s', current_policy)
# Building all diffs between the current and expected policy
# XXX We simplify the comparison by assuming we have at most 1
# sub_profile
if policy.get('subprofiles'):
if len(policy['subprofiles']) > 1:
raise ArgumentValueError('Multiple sub_profiles ({0}) are not '
'supported in the input policy')
subprofile = policy['subprofiles'][0]
current_subprofile = current_policy['subprofiles'][0]
capabilities_differ = list_diff(current_subprofile['capabilities'],
subprofile.get('capabilities', []),
key='id')
del policy['subprofiles']
if subprofile.get('capabilities'):
del subprofile['capabilities']
del current_subprofile['capabilities']
# Get the subprofile diffs without the capability keys
subprofile_differ = recursive_diff(current_subprofile,
dict(subprofile))
del current_policy['subprofiles']
policy_differ = recursive_diff(current_policy, policy)
if policy_differ.diffs or capabilities_differ.diffs or \
subprofile_differ.diffs:
if 'name' in policy_differ.new_values or \
'description' in policy_differ.new_values:
raise ArgumentValueError(
'\'name\' and \'description\' of the default VSAN policy '
'cannot be updated')
changes_required = True
if __opts__['test']:
str_changes = []
if policy_differ.diffs:
str_changes.extend([change for change in
policy_differ.changes_str.split('\n')])
if subprofile_differ.diffs or capabilities_differ.diffs:
str_changes.append('subprofiles:')
if subprofile_differ.diffs:
str_changes.extend(
[' {0}'.format(change) for change in
subprofile_differ.changes_str.split('\n')])
if capabilities_differ.diffs:
str_changes.append(' capabilities:')
str_changes.extend(
[' {0}'.format(change) for change in
capabilities_differ.changes_str2.split('\n')])
comments.append(
'State {0} will update the default VSAN policy on '
'vCenter \'{1}\':\n{2}'
''.format(name, vcenter, '\n'.join(str_changes)))
else:
__salt__['vsphere.update_storage_policy'](
policy=current_policy['name'],
policy_dict=policy_copy,
service_instance=si)
comments.append('Updated the default VSAN policy in vCenter '
'\'{0}\''.format(vcenter))
log.info(comments[-1])
new_values = policy_differ.new_values
new_values['subprofiles'] = [subprofile_differ.new_values]
new_values['subprofiles'][0]['capabilities'] = \
capabilities_differ.new_values
if not new_values['subprofiles'][0]['capabilities']:
del new_values['subprofiles'][0]['capabilities']
if not new_values['subprofiles'][0]:
del new_values['subprofiles']
old_values = policy_differ.old_values
old_values['subprofiles'] = [subprofile_differ.old_values]
old_values['subprofiles'][0]['capabilities'] = \
capabilities_differ.old_values
if not old_values['subprofiles'][0]['capabilities']:
del old_values['subprofiles'][0]['capabilities']
if not old_values['subprofiles'][0]:
del old_values['subprofiles']
changes.update({'default_vsan_policy':
{'new': new_values,
'old': old_values}})
log.trace(changes)
__salt__['vsphere.disconnect'](si)
except CommandExecutionError as exc:
log.error('Error: %s', exc)
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
if not changes_required:
# We have no changes
ret.update({'comment': ('Default VSAN policy in vCenter '
'\'{0}\' is correctly configured. '
'Nothing to be done.'.format(vcenter)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
|
Configures the default VSAN policy on a vCenter.
The state assumes there is only one default VSAN policy on a vCenter.
policy
Dict representation of a policy
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pbm.py#L138-L275
|
[
"def recursive_diff(past_dict, current_dict, ignore_missing_keys=True):\n '''\n Returns a RecursiveDictDiffer object that computes the recursive diffs\n between two dictionaries\n\n past_dict\n Past dictionary\n\n current_dict\n Current dictionary\n\n ignore_missing_keys\n Flag specifying whether to ignore keys that no longer exist in the\n current_dict, but exist in the past_dict. If true, the diff will\n not contain the missing keys.\n Default is True.\n '''\n return RecursiveDictDiffer(past_dict, current_dict, ignore_missing_keys)\n",
"def list_diff(list_a, list_b, key):\n return ListDictDiffer(list_a, list_b, key)\n"
] |
# -*- coding: utf-8 -*-
'''
Manages VMware storage policies
(called pbm because the vCenter endpoint is /pbm)
Examples
========
Storage policy
--------------
.. code-block:: python
{
"name": "salt_storage_policy"
"description": "Managed by Salt. Random capability values.",
"resource_type": "STORAGE",
"subprofiles": [
{
"capabilities": [
{
"setting": {
"type": "scalar",
"value": 2
},
"namespace": "VSAN",
"id": "hostFailuresToTolerate"
},
{
"setting": {
"type": "scalar",
"value": 2
},
"namespace": "VSAN",
"id": "stripeWidth"
},
{
"setting": {
"type": "scalar",
"value": true
},
"namespace": "VSAN",
"id": "forceProvisioning"
},
{
"setting": {
"type": "scalar",
"value": 50
},
"namespace": "VSAN",
"id": "proportionalCapacity"
},
{
"setting": {
"type": "scalar",
"value": 0
},
"namespace": "VSAN",
"id": "cacheReservation"
}
],
"name": "Rule-Set 1: VSAN",
"force_provision": null
}
],
}
Dependencies
============
- pyVmomi Python Module
pyVmomi
-------
PyVmomi can be installed via pip:
.. code-block:: bash
pip install pyVmomi
.. note::
Version 6.0 of pyVmomi has some problems with SSL error handling on certain
versions of Python. If using version 6.0 of pyVmomi, Python 2.6,
Python 2.7.9, or newer must be present. This is due to an upstream dependency
in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the
version of Python is not in the supported range, you will need to install an
earlier version of pyVmomi. See `Issue #29537`_ for more information.
.. _Issue #29537: https://github.com/saltstack/salt/issues/29537
'''
# Import Python Libs
from __future__ import absolute_import
import logging
import copy
import sys
# Import Salt Libs
from salt.exceptions import CommandExecutionError, ArgumentValueError
from salt.utils.dictdiffer import recursive_diff
from salt.utils.listdiffer import list_diff
# External libraries
try:
from pyVmomi import VmomiSupport
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
# Get Logging Started
log = logging.getLogger(__name__)
def __virtual__():
if not HAS_PYVMOMI:
return False, 'State module did not load: pyVmomi not found'
# We check the supported vim versions to infer the pyVmomi version
if 'vim25/6.0' in VmomiSupport.versionMap and \
sys.version_info > (2, 7) and sys.version_info < (2, 7, 9):
return False, ('State module did not load: Incompatible versions '
'of Python and pyVmomi present. See Issue #29537.')
return True
def mod_init(low):
'''
Init function
'''
return True
def storage_policies_configured(name, policies):
'''
Configures storage policies on a vCenter.
policies
List of dict representation of the required storage policies
'''
comments = []
changes = []
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
log.trace('policies = %s', policies)
si = None
try:
proxy_type = __salt__['vsphere.get_proxy_type']()
log.trace('proxy_type = %s', proxy_type)
# All allowed proxies have a shim execution module with the same
# name which implementes a get_details function
# All allowed proxies have a vcenter detail
vcenter = __salt__['{0}.get_details'.format(proxy_type)]()['vcenter']
log.info('Running state \'%s\' on vCenter \'%s\'', name, vcenter)
si = __salt__['vsphere.get_service_instance_via_proxy']()
current_policies = __salt__['vsphere.list_storage_policies'](
policy_names=[policy['name'] for policy in policies],
service_instance=si)
log.trace('current_policies = %s', current_policies)
# TODO Refactor when recurse_differ supports list_differ
# It's going to make the whole thing much easier
for policy in policies:
policy_copy = copy.deepcopy(policy)
filtered_policies = [p for p in current_policies
if p['name'] == policy['name']]
current_policy = filtered_policies[0] \
if filtered_policies else None
if not current_policy:
changes_required = True
if __opts__['test']:
comments.append('State {0} will create the storage policy '
'\'{1}\' on vCenter \'{2}\''
''.format(name, policy['name'], vcenter))
else:
__salt__['vsphere.create_storage_policy'](
policy['name'], policy, service_instance=si)
comments.append('Created storage policy \'{0}\' on '
'vCenter \'{1}\''.format(policy['name'],
vcenter))
changes.append({'new': policy, 'old': None})
log.trace(comments[-1])
# Continue with next
continue
# Building all diffs between the current and expected policy
# XXX We simplify the comparison by assuming we have at most 1
# sub_profile
if policy.get('subprofiles'):
if len(policy['subprofiles']) > 1:
raise ArgumentValueError('Multiple sub_profiles ({0}) are not '
'supported in the input policy')
subprofile = policy['subprofiles'][0]
current_subprofile = current_policy['subprofiles'][0]
capabilities_differ = list_diff(current_subprofile['capabilities'],
subprofile.get('capabilities', []),
key='id')
del policy['subprofiles']
if subprofile.get('capabilities'):
del subprofile['capabilities']
del current_subprofile['capabilities']
# Get the subprofile diffs without the capability keys
subprofile_differ = recursive_diff(current_subprofile,
dict(subprofile))
del current_policy['subprofiles']
policy_differ = recursive_diff(current_policy, policy)
if policy_differ.diffs or capabilities_differ.diffs or \
subprofile_differ.diffs:
changes_required = True
if __opts__['test']:
str_changes = []
if policy_differ.diffs:
str_changes.extend(
[change for change in
policy_differ.changes_str.split('\n')])
if subprofile_differ.diffs or \
capabilities_differ.diffs:
str_changes.append('subprofiles:')
if subprofile_differ.diffs:
str_changes.extend(
[' {0}'.format(change) for change in
subprofile_differ.changes_str.split('\n')])
if capabilities_differ.diffs:
str_changes.append(' capabilities:')
str_changes.extend(
[' {0}'.format(change) for change in
capabilities_differ.changes_str2.split('\n')])
comments.append(
'State {0} will update the storage policy \'{1}\''
' on vCenter \'{2}\':\n{3}'
''.format(name, policy['name'], vcenter,
'\n'.join(str_changes)))
else:
__salt__['vsphere.update_storage_policy'](
policy=current_policy['name'],
policy_dict=policy_copy,
service_instance=si)
comments.append('Updated the storage policy \'{0}\''
'in vCenter \'{1}\''
''.format(policy['name'], vcenter))
log.info(comments[-1])
# Build new/old values to report what was changed
new_values = policy_differ.new_values
new_values['subprofiles'] = [subprofile_differ.new_values]
new_values['subprofiles'][0]['capabilities'] = \
capabilities_differ.new_values
if not new_values['subprofiles'][0]['capabilities']:
del new_values['subprofiles'][0]['capabilities']
if not new_values['subprofiles'][0]:
del new_values['subprofiles']
old_values = policy_differ.old_values
old_values['subprofiles'] = [subprofile_differ.old_values]
old_values['subprofiles'][0]['capabilities'] = \
capabilities_differ.old_values
if not old_values['subprofiles'][0]['capabilities']:
del old_values['subprofiles'][0]['capabilities']
if not old_values['subprofiles'][0]:
del old_values['subprofiles']
changes.append({'new': new_values,
'old': old_values})
else:
# No diffs found - no updates required
comments.append('Storage policy \'{0}\' is up to date. '
'Nothing to be done.'.format(policy['name']))
__salt__['vsphere.disconnect'](si)
except CommandExecutionError as exc:
log.error('Error: %s', exc)
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
if not changes_required:
# We have no changes
ret.update({'comment': ('All storage policy in vCenter '
'\'{0}\' is correctly configured. '
'Nothing to be done.'.format(vcenter)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': {'storage_policies': changes},
'result': None if __opts__['test'] else True,
})
return ret
def default_storage_policy_assigned(name, policy, datastore):
'''
Assigns a default storage policy to a datastore
policy
Name of storage policy
datastore
Name of datastore
'''
log.info('Running state %s for policy \'%s\', datastore \'%s\'.',
name, policy, datastore)
changes = {}
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
si = None
try:
si = __salt__['vsphere.get_service_instance_via_proxy']()
existing_policy = \
__salt__['vsphere.list_default_storage_policy_of_datastore'](
datastore=datastore, service_instance=si)
if existing_policy['name'] == policy:
comment = ('Storage policy \'{0}\' is already assigned to '
'datastore \'{1}\'. Nothing to be done.'
''.format(policy, datastore))
else:
changes_required = True
changes = {
'default_storage_policy': {'old': existing_policy['name'],
'new': policy}}
if __opts__['test']:
comment = ('State {0} will assign storage policy \'{1}\' to '
'datastore \'{2}\'.').format(name, policy,
datastore)
else:
__salt__['vsphere.assign_default_storage_policy_to_datastore'](
policy=policy, datastore=datastore, service_instance=si)
comment = ('Storage policy \'{0} was assigned to datastore '
'\'{1}\'.').format(policy, name)
log.info(comment)
except CommandExecutionError as exc:
log.error('Error: %s', exc)
if si:
__salt__['vsphere.disconnect'](si)
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
ret['comment'] = comment
if changes_required:
ret.update({
'changes': changes,
'result': None if __opts__['test'] else True,
})
else:
ret['result'] = True
return ret
|
saltstack/salt
|
salt/states/pbm.py
|
default_storage_policy_assigned
|
python
|
def default_storage_policy_assigned(name, policy, datastore):
'''
Assigns a default storage policy to a datastore
policy
Name of storage policy
datastore
Name of datastore
'''
log.info('Running state %s for policy \'%s\', datastore \'%s\'.',
name, policy, datastore)
changes = {}
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
si = None
try:
si = __salt__['vsphere.get_service_instance_via_proxy']()
existing_policy = \
__salt__['vsphere.list_default_storage_policy_of_datastore'](
datastore=datastore, service_instance=si)
if existing_policy['name'] == policy:
comment = ('Storage policy \'{0}\' is already assigned to '
'datastore \'{1}\'. Nothing to be done.'
''.format(policy, datastore))
else:
changes_required = True
changes = {
'default_storage_policy': {'old': existing_policy['name'],
'new': policy}}
if __opts__['test']:
comment = ('State {0} will assign storage policy \'{1}\' to '
'datastore \'{2}\'.').format(name, policy,
datastore)
else:
__salt__['vsphere.assign_default_storage_policy_to_datastore'](
policy=policy, datastore=datastore, service_instance=si)
comment = ('Storage policy \'{0} was assigned to datastore '
'\'{1}\'.').format(policy, name)
log.info(comment)
except CommandExecutionError as exc:
log.error('Error: %s', exc)
if si:
__salt__['vsphere.disconnect'](si)
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
ret['comment'] = comment
if changes_required:
ret.update({
'changes': changes,
'result': None if __opts__['test'] else True,
})
else:
ret['result'] = True
return ret
|
Assigns a default storage policy to a datastore
policy
Name of storage policy
datastore
Name of datastore
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pbm.py#L441-L500
| null |
# -*- coding: utf-8 -*-
'''
Manages VMware storage policies
(called pbm because the vCenter endpoint is /pbm)
Examples
========
Storage policy
--------------
.. code-block:: python
{
"name": "salt_storage_policy"
"description": "Managed by Salt. Random capability values.",
"resource_type": "STORAGE",
"subprofiles": [
{
"capabilities": [
{
"setting": {
"type": "scalar",
"value": 2
},
"namespace": "VSAN",
"id": "hostFailuresToTolerate"
},
{
"setting": {
"type": "scalar",
"value": 2
},
"namespace": "VSAN",
"id": "stripeWidth"
},
{
"setting": {
"type": "scalar",
"value": true
},
"namespace": "VSAN",
"id": "forceProvisioning"
},
{
"setting": {
"type": "scalar",
"value": 50
},
"namespace": "VSAN",
"id": "proportionalCapacity"
},
{
"setting": {
"type": "scalar",
"value": 0
},
"namespace": "VSAN",
"id": "cacheReservation"
}
],
"name": "Rule-Set 1: VSAN",
"force_provision": null
}
],
}
Dependencies
============
- pyVmomi Python Module
pyVmomi
-------
PyVmomi can be installed via pip:
.. code-block:: bash
pip install pyVmomi
.. note::
Version 6.0 of pyVmomi has some problems with SSL error handling on certain
versions of Python. If using version 6.0 of pyVmomi, Python 2.6,
Python 2.7.9, or newer must be present. This is due to an upstream dependency
in pyVmomi 6.0 that is not supported in Python versions 2.7 to 2.7.8. If the
version of Python is not in the supported range, you will need to install an
earlier version of pyVmomi. See `Issue #29537`_ for more information.
.. _Issue #29537: https://github.com/saltstack/salt/issues/29537
'''
# Import Python Libs
from __future__ import absolute_import
import logging
import copy
import sys
# Import Salt Libs
from salt.exceptions import CommandExecutionError, ArgumentValueError
from salt.utils.dictdiffer import recursive_diff
from salt.utils.listdiffer import list_diff
# External libraries
try:
from pyVmomi import VmomiSupport
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
# Get Logging Started
log = logging.getLogger(__name__)
def __virtual__():
if not HAS_PYVMOMI:
return False, 'State module did not load: pyVmomi not found'
# We check the supported vim versions to infer the pyVmomi version
if 'vim25/6.0' in VmomiSupport.versionMap and \
sys.version_info > (2, 7) and sys.version_info < (2, 7, 9):
return False, ('State module did not load: Incompatible versions '
'of Python and pyVmomi present. See Issue #29537.')
return True
def mod_init(low):
'''
Init function
'''
return True
def default_vsan_policy_configured(name, policy):
'''
Configures the default VSAN policy on a vCenter.
The state assumes there is only one default VSAN policy on a vCenter.
policy
Dict representation of a policy
'''
# TODO Refactor when recurse_differ supports list_differ
# It's going to make the whole thing much easier
policy_copy = copy.deepcopy(policy)
proxy_type = __salt__['vsphere.get_proxy_type']()
log.trace('proxy_type = %s', proxy_type)
# All allowed proxies have a shim execution module with the same
# name which implementes a get_details function
# All allowed proxies have a vcenter detail
vcenter = __salt__['{0}.get_details'.format(proxy_type)]()['vcenter']
log.info('Running %s on vCenter \'%s\'', name, vcenter)
log.trace('policy = %s', policy)
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
comments = []
changes = {}
changes_required = False
si = None
try:
#TODO policy schema validation
si = __salt__['vsphere.get_service_instance_via_proxy']()
current_policy = __salt__['vsphere.list_default_vsan_policy'](si)
log.trace('current_policy = %s', current_policy)
# Building all diffs between the current and expected policy
# XXX We simplify the comparison by assuming we have at most 1
# sub_profile
if policy.get('subprofiles'):
if len(policy['subprofiles']) > 1:
raise ArgumentValueError('Multiple sub_profiles ({0}) are not '
'supported in the input policy')
subprofile = policy['subprofiles'][0]
current_subprofile = current_policy['subprofiles'][0]
capabilities_differ = list_diff(current_subprofile['capabilities'],
subprofile.get('capabilities', []),
key='id')
del policy['subprofiles']
if subprofile.get('capabilities'):
del subprofile['capabilities']
del current_subprofile['capabilities']
# Get the subprofile diffs without the capability keys
subprofile_differ = recursive_diff(current_subprofile,
dict(subprofile))
del current_policy['subprofiles']
policy_differ = recursive_diff(current_policy, policy)
if policy_differ.diffs or capabilities_differ.diffs or \
subprofile_differ.diffs:
if 'name' in policy_differ.new_values or \
'description' in policy_differ.new_values:
raise ArgumentValueError(
'\'name\' and \'description\' of the default VSAN policy '
'cannot be updated')
changes_required = True
if __opts__['test']:
str_changes = []
if policy_differ.diffs:
str_changes.extend([change for change in
policy_differ.changes_str.split('\n')])
if subprofile_differ.diffs or capabilities_differ.diffs:
str_changes.append('subprofiles:')
if subprofile_differ.diffs:
str_changes.extend(
[' {0}'.format(change) for change in
subprofile_differ.changes_str.split('\n')])
if capabilities_differ.diffs:
str_changes.append(' capabilities:')
str_changes.extend(
[' {0}'.format(change) for change in
capabilities_differ.changes_str2.split('\n')])
comments.append(
'State {0} will update the default VSAN policy on '
'vCenter \'{1}\':\n{2}'
''.format(name, vcenter, '\n'.join(str_changes)))
else:
__salt__['vsphere.update_storage_policy'](
policy=current_policy['name'],
policy_dict=policy_copy,
service_instance=si)
comments.append('Updated the default VSAN policy in vCenter '
'\'{0}\''.format(vcenter))
log.info(comments[-1])
new_values = policy_differ.new_values
new_values['subprofiles'] = [subprofile_differ.new_values]
new_values['subprofiles'][0]['capabilities'] = \
capabilities_differ.new_values
if not new_values['subprofiles'][0]['capabilities']:
del new_values['subprofiles'][0]['capabilities']
if not new_values['subprofiles'][0]:
del new_values['subprofiles']
old_values = policy_differ.old_values
old_values['subprofiles'] = [subprofile_differ.old_values]
old_values['subprofiles'][0]['capabilities'] = \
capabilities_differ.old_values
if not old_values['subprofiles'][0]['capabilities']:
del old_values['subprofiles'][0]['capabilities']
if not old_values['subprofiles'][0]:
del old_values['subprofiles']
changes.update({'default_vsan_policy':
{'new': new_values,
'old': old_values}})
log.trace(changes)
__salt__['vsphere.disconnect'](si)
except CommandExecutionError as exc:
log.error('Error: %s', exc)
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
if not changes_required:
# We have no changes
ret.update({'comment': ('Default VSAN policy in vCenter '
'\'{0}\' is correctly configured. '
'Nothing to be done.'.format(vcenter)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': changes,
'result': None if __opts__['test'] else True,
})
return ret
def storage_policies_configured(name, policies):
'''
Configures storage policies on a vCenter.
policies
List of dict representation of the required storage policies
'''
comments = []
changes = []
changes_required = False
ret = {'name': name,
'changes': {},
'result': None,
'comment': None}
log.trace('policies = %s', policies)
si = None
try:
proxy_type = __salt__['vsphere.get_proxy_type']()
log.trace('proxy_type = %s', proxy_type)
# All allowed proxies have a shim execution module with the same
# name which implementes a get_details function
# All allowed proxies have a vcenter detail
vcenter = __salt__['{0}.get_details'.format(proxy_type)]()['vcenter']
log.info('Running state \'%s\' on vCenter \'%s\'', name, vcenter)
si = __salt__['vsphere.get_service_instance_via_proxy']()
current_policies = __salt__['vsphere.list_storage_policies'](
policy_names=[policy['name'] for policy in policies],
service_instance=si)
log.trace('current_policies = %s', current_policies)
# TODO Refactor when recurse_differ supports list_differ
# It's going to make the whole thing much easier
for policy in policies:
policy_copy = copy.deepcopy(policy)
filtered_policies = [p for p in current_policies
if p['name'] == policy['name']]
current_policy = filtered_policies[0] \
if filtered_policies else None
if not current_policy:
changes_required = True
if __opts__['test']:
comments.append('State {0} will create the storage policy '
'\'{1}\' on vCenter \'{2}\''
''.format(name, policy['name'], vcenter))
else:
__salt__['vsphere.create_storage_policy'](
policy['name'], policy, service_instance=si)
comments.append('Created storage policy \'{0}\' on '
'vCenter \'{1}\''.format(policy['name'],
vcenter))
changes.append({'new': policy, 'old': None})
log.trace(comments[-1])
# Continue with next
continue
# Building all diffs between the current and expected policy
# XXX We simplify the comparison by assuming we have at most 1
# sub_profile
if policy.get('subprofiles'):
if len(policy['subprofiles']) > 1:
raise ArgumentValueError('Multiple sub_profiles ({0}) are not '
'supported in the input policy')
subprofile = policy['subprofiles'][0]
current_subprofile = current_policy['subprofiles'][0]
capabilities_differ = list_diff(current_subprofile['capabilities'],
subprofile.get('capabilities', []),
key='id')
del policy['subprofiles']
if subprofile.get('capabilities'):
del subprofile['capabilities']
del current_subprofile['capabilities']
# Get the subprofile diffs without the capability keys
subprofile_differ = recursive_diff(current_subprofile,
dict(subprofile))
del current_policy['subprofiles']
policy_differ = recursive_diff(current_policy, policy)
if policy_differ.diffs or capabilities_differ.diffs or \
subprofile_differ.diffs:
changes_required = True
if __opts__['test']:
str_changes = []
if policy_differ.diffs:
str_changes.extend(
[change for change in
policy_differ.changes_str.split('\n')])
if subprofile_differ.diffs or \
capabilities_differ.diffs:
str_changes.append('subprofiles:')
if subprofile_differ.diffs:
str_changes.extend(
[' {0}'.format(change) for change in
subprofile_differ.changes_str.split('\n')])
if capabilities_differ.diffs:
str_changes.append(' capabilities:')
str_changes.extend(
[' {0}'.format(change) for change in
capabilities_differ.changes_str2.split('\n')])
comments.append(
'State {0} will update the storage policy \'{1}\''
' on vCenter \'{2}\':\n{3}'
''.format(name, policy['name'], vcenter,
'\n'.join(str_changes)))
else:
__salt__['vsphere.update_storage_policy'](
policy=current_policy['name'],
policy_dict=policy_copy,
service_instance=si)
comments.append('Updated the storage policy \'{0}\''
'in vCenter \'{1}\''
''.format(policy['name'], vcenter))
log.info(comments[-1])
# Build new/old values to report what was changed
new_values = policy_differ.new_values
new_values['subprofiles'] = [subprofile_differ.new_values]
new_values['subprofiles'][0]['capabilities'] = \
capabilities_differ.new_values
if not new_values['subprofiles'][0]['capabilities']:
del new_values['subprofiles'][0]['capabilities']
if not new_values['subprofiles'][0]:
del new_values['subprofiles']
old_values = policy_differ.old_values
old_values['subprofiles'] = [subprofile_differ.old_values]
old_values['subprofiles'][0]['capabilities'] = \
capabilities_differ.old_values
if not old_values['subprofiles'][0]['capabilities']:
del old_values['subprofiles'][0]['capabilities']
if not old_values['subprofiles'][0]:
del old_values['subprofiles']
changes.append({'new': new_values,
'old': old_values})
else:
# No diffs found - no updates required
comments.append('Storage policy \'{0}\' is up to date. '
'Nothing to be done.'.format(policy['name']))
__salt__['vsphere.disconnect'](si)
except CommandExecutionError as exc:
log.error('Error: %s', exc)
if si:
__salt__['vsphere.disconnect'](si)
if not __opts__['test']:
ret['result'] = False
ret.update({'comment': exc.strerror,
'result': False if not __opts__['test'] else None})
return ret
if not changes_required:
# We have no changes
ret.update({'comment': ('All storage policy in vCenter '
'\'{0}\' is correctly configured. '
'Nothing to be done.'.format(vcenter)),
'result': True})
else:
ret.update({
'comment': '\n'.join(comments),
'changes': {'storage_policies': changes},
'result': None if __opts__['test'] else True,
})
return ret
|
saltstack/salt
|
salt/modules/cloud.py
|
_get_client
|
python
|
def _get_client():
'''
Return a cloud client
'''
client = salt.cloud.CloudClient(
os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),
pillars=copy.deepcopy(__pillar__.get('cloud', {}))
)
return client
|
Return a cloud client
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L41-L49
| null |
# -*- coding: utf-8 -*-
'''
Salt-specific interface for calling Salt Cloud directly
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
import copy
import salt.utils.data
# Import salt libs
try:
import salt.cloud
HAS_SALTCLOUD = True
except ImportError:
HAS_SALTCLOUD = False
from salt.exceptions import SaltCloudConfigError
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
__func_alias__ = {
'profile_': 'profile'
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if HAS_SALTCLOUD:
return True
return (False, 'The cloud execution module cannot be loaded: only available on non-Windows systems.')
def list_sizes(provider='all'):
'''
List cloud provider sizes for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_sizes my-gce-config
'''
client = _get_client()
sizes = client.list_sizes(provider)
return sizes
def list_images(provider='all'):
'''
List cloud provider images for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_images my-gce-config
'''
client = _get_client()
images = client.list_images(provider)
return images
def list_locations(provider='all'):
'''
List cloud provider locations for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_locations my-gce-config
'''
client = _get_client()
locations = client.list_locations(provider)
return locations
def query(query_type='list_nodes'):
'''
List cloud provider data for all providers
CLI Examples:
.. code-block:: bash
salt minionname cloud.query
salt minionname cloud.query list_nodes_full
salt minionname cloud.query list_nodes_select
'''
client = _get_client()
info = client.query(query_type)
return info
def full_query(query_type='list_nodes_full'):
'''
List all available cloud provider data
CLI Example:
.. code-block:: bash
salt minionname cloud.full_query
'''
return query(query_type=query_type)
def select_query(query_type='list_nodes_select'):
'''
List selected nodes
CLI Example:
.. code-block:: bash
salt minionname cloud.select_query
'''
return query(query_type=query_type)
def has_instance(name, provider=None):
'''
Return true if the instance is found on a provider
CLI Example:
.. code-block:: bash
salt minionname cloud.has_instance myinstance
'''
data = get_instance(name, provider)
if data is None:
return False
return True
def get_instance(name, provider=None):
'''
Return details on an instance.
Similar to the cloud action show_instance
but returns only the instance details.
CLI Example:
.. code-block:: bash
salt minionname cloud.get_instance myinstance
SLS Example:
.. code-block:: bash
{{ salt['cloud.get_instance']('myinstance')['mac_address'] }}
'''
data = action(fun='show_instance', names=[name], provider=provider)
info = salt.utils.data.simple_types_filter(data)
try:
# get the first: [alias][driver][vm_name]
info = next(six.itervalues(next(six.itervalues(next(six.itervalues(info))))))
except AttributeError:
return None
return info
def profile_(profile, names, vm_overrides=None, opts=None, **kwargs):
'''
Spin up an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.profile my-gce-config myinstance
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.profile(profile, names, vm_overrides=vm_overrides, **kwargs)
return info
def map_run(path=None, **kwargs):
'''
Execute a salt cloud map file
Cloud Map data can be retrieved from several sources:
- a local file (provide the path to the file to the 'path' argument)
- a JSON-formatted map directly (provide the appropriately formatted to using the 'map_data' argument)
- the Salt Pillar (provide the map name of under 'pillar:cloud:maps' to the 'map_pillar' argument)
.. note::
Only one of these sources can be read at a time. The options are listed
in their order of precedence.
CLI Examples:
.. code-block:: bash
salt minionname cloud.map_run /path/to/cloud.map
salt minionname cloud.map_run path=/path/to/cloud.map
salt minionname cloud.map_run map_pillar='<map_pillar>'
.. versionchanged:: 2018.3.1
salt minionname cloud.map_run map_data='<actual map data>'
'''
client = _get_client()
info = client.map_run(path, **kwargs)
return info
def destroy(names):
'''
Destroy the named VM(s)
CLI Example:
.. code-block:: bash
salt minionname cloud.destroy myinstance
'''
client = _get_client()
info = client.destroy(names)
return info
def action(
fun=None,
cloudmap=None,
names=None,
provider=None,
instance=None,
**kwargs):
'''
Execute a single action on the given provider/instance
CLI Example:
.. code-block:: bash
salt minionname cloud.action start instance=myinstance
salt minionname cloud.action stop instance=myinstance
salt minionname cloud.action show_image provider=my-ec2-config image=ami-1624987f
'''
client = _get_client()
try:
info = client.action(fun, cloudmap, names, provider, instance, kwargs)
except SaltCloudConfigError as err:
log.error(err)
return None
return info
def create(provider, names, opts=None, **kwargs):
'''
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.create(provider, names, **kwargs)
return info
def volume_list(provider):
'''
List block storage volumes
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_list my-nova
'''
client = _get_client()
info = client.extra_action(action='volume_list', provider=provider, names='name')
return info['name']
def volume_delete(provider, names, **kwargs):
'''
Delete volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_delete my-nova myblock
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_delete', **kwargs)
return info
def volume_create(provider, names, **kwargs):
'''
Create volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_create my-nova myblock size=100 voltype=SSD
'''
client = _get_client()
info = client.extra_action(action='volume_create', names=names, provider=provider, **kwargs)
return info
def volume_attach(provider, names, **kwargs):
'''
Attach volume to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_attach my-nova myblock server_name=myserver device='/dev/xvdf'
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_attach', **kwargs)
return info
def volume_detach(provider, names, **kwargs):
'''
Detach volume from a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_detach my-nova myblock server_name=myserver
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_detach', **kwargs)
return info
def network_list(provider):
'''
List private networks
CLI Example:
.. code-block:: bash
salt minionname cloud.network_list my-nova
'''
client = _get_client()
return client.extra_action(action='network_list', provider=provider, names='names')
def network_create(provider, names, **kwargs):
'''
Create private network
CLI Example:
.. code-block:: bash
salt minionname cloud.network_create my-nova names=['salt'] cidr='192.168.100.0/24'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='network_create', **kwargs)
def virtual_interface_list(provider, names, **kwargs):
'''
List virtual interfaces on a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_list my-nova names=['salt-master']
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_list', **kwargs)
def virtual_interface_create(provider, names, **kwargs):
'''
Attach private interfaces to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_create my-nova names=['salt-master'] net_name='salt'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_create', **kwargs)
|
saltstack/salt
|
salt/modules/cloud.py
|
has_instance
|
python
|
def has_instance(name, provider=None):
'''
Return true if the instance is found on a provider
CLI Example:
.. code-block:: bash
salt minionname cloud.has_instance myinstance
'''
data = get_instance(name, provider)
if data is None:
return False
return True
|
Return true if the instance is found on a provider
CLI Example:
.. code-block:: bash
salt minionname cloud.has_instance myinstance
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L140-L153
|
[
"def get_instance(name, provider=None):\n '''\n Return details on an instance.\n\n Similar to the cloud action show_instance\n but returns only the instance details.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt minionname cloud.get_instance myinstance\n\n SLS Example:\n\n .. code-block:: bash\n\n {{ salt['cloud.get_instance']('myinstance')['mac_address'] }}\n\n '''\n data = action(fun='show_instance', names=[name], provider=provider)\n info = salt.utils.data.simple_types_filter(data)\n try:\n # get the first: [alias][driver][vm_name]\n info = next(six.itervalues(next(six.itervalues(next(six.itervalues(info))))))\n except AttributeError:\n return None\n return info\n"
] |
# -*- coding: utf-8 -*-
'''
Salt-specific interface for calling Salt Cloud directly
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
import copy
import salt.utils.data
# Import salt libs
try:
import salt.cloud
HAS_SALTCLOUD = True
except ImportError:
HAS_SALTCLOUD = False
from salt.exceptions import SaltCloudConfigError
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
__func_alias__ = {
'profile_': 'profile'
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if HAS_SALTCLOUD:
return True
return (False, 'The cloud execution module cannot be loaded: only available on non-Windows systems.')
def _get_client():
'''
Return a cloud client
'''
client = salt.cloud.CloudClient(
os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),
pillars=copy.deepcopy(__pillar__.get('cloud', {}))
)
return client
def list_sizes(provider='all'):
'''
List cloud provider sizes for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_sizes my-gce-config
'''
client = _get_client()
sizes = client.list_sizes(provider)
return sizes
def list_images(provider='all'):
'''
List cloud provider images for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_images my-gce-config
'''
client = _get_client()
images = client.list_images(provider)
return images
def list_locations(provider='all'):
'''
List cloud provider locations for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_locations my-gce-config
'''
client = _get_client()
locations = client.list_locations(provider)
return locations
def query(query_type='list_nodes'):
'''
List cloud provider data for all providers
CLI Examples:
.. code-block:: bash
salt minionname cloud.query
salt minionname cloud.query list_nodes_full
salt minionname cloud.query list_nodes_select
'''
client = _get_client()
info = client.query(query_type)
return info
def full_query(query_type='list_nodes_full'):
'''
List all available cloud provider data
CLI Example:
.. code-block:: bash
salt minionname cloud.full_query
'''
return query(query_type=query_type)
def select_query(query_type='list_nodes_select'):
'''
List selected nodes
CLI Example:
.. code-block:: bash
salt minionname cloud.select_query
'''
return query(query_type=query_type)
def get_instance(name, provider=None):
'''
Return details on an instance.
Similar to the cloud action show_instance
but returns only the instance details.
CLI Example:
.. code-block:: bash
salt minionname cloud.get_instance myinstance
SLS Example:
.. code-block:: bash
{{ salt['cloud.get_instance']('myinstance')['mac_address'] }}
'''
data = action(fun='show_instance', names=[name], provider=provider)
info = salt.utils.data.simple_types_filter(data)
try:
# get the first: [alias][driver][vm_name]
info = next(six.itervalues(next(six.itervalues(next(six.itervalues(info))))))
except AttributeError:
return None
return info
def profile_(profile, names, vm_overrides=None, opts=None, **kwargs):
'''
Spin up an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.profile my-gce-config myinstance
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.profile(profile, names, vm_overrides=vm_overrides, **kwargs)
return info
def map_run(path=None, **kwargs):
'''
Execute a salt cloud map file
Cloud Map data can be retrieved from several sources:
- a local file (provide the path to the file to the 'path' argument)
- a JSON-formatted map directly (provide the appropriately formatted to using the 'map_data' argument)
- the Salt Pillar (provide the map name of under 'pillar:cloud:maps' to the 'map_pillar' argument)
.. note::
Only one of these sources can be read at a time. The options are listed
in their order of precedence.
CLI Examples:
.. code-block:: bash
salt minionname cloud.map_run /path/to/cloud.map
salt minionname cloud.map_run path=/path/to/cloud.map
salt minionname cloud.map_run map_pillar='<map_pillar>'
.. versionchanged:: 2018.3.1
salt minionname cloud.map_run map_data='<actual map data>'
'''
client = _get_client()
info = client.map_run(path, **kwargs)
return info
def destroy(names):
'''
Destroy the named VM(s)
CLI Example:
.. code-block:: bash
salt minionname cloud.destroy myinstance
'''
client = _get_client()
info = client.destroy(names)
return info
def action(
fun=None,
cloudmap=None,
names=None,
provider=None,
instance=None,
**kwargs):
'''
Execute a single action on the given provider/instance
CLI Example:
.. code-block:: bash
salt minionname cloud.action start instance=myinstance
salt minionname cloud.action stop instance=myinstance
salt minionname cloud.action show_image provider=my-ec2-config image=ami-1624987f
'''
client = _get_client()
try:
info = client.action(fun, cloudmap, names, provider, instance, kwargs)
except SaltCloudConfigError as err:
log.error(err)
return None
return info
def create(provider, names, opts=None, **kwargs):
'''
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.create(provider, names, **kwargs)
return info
def volume_list(provider):
'''
List block storage volumes
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_list my-nova
'''
client = _get_client()
info = client.extra_action(action='volume_list', provider=provider, names='name')
return info['name']
def volume_delete(provider, names, **kwargs):
'''
Delete volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_delete my-nova myblock
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_delete', **kwargs)
return info
def volume_create(provider, names, **kwargs):
'''
Create volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_create my-nova myblock size=100 voltype=SSD
'''
client = _get_client()
info = client.extra_action(action='volume_create', names=names, provider=provider, **kwargs)
return info
def volume_attach(provider, names, **kwargs):
'''
Attach volume to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_attach my-nova myblock server_name=myserver device='/dev/xvdf'
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_attach', **kwargs)
return info
def volume_detach(provider, names, **kwargs):
'''
Detach volume from a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_detach my-nova myblock server_name=myserver
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_detach', **kwargs)
return info
def network_list(provider):
'''
List private networks
CLI Example:
.. code-block:: bash
salt minionname cloud.network_list my-nova
'''
client = _get_client()
return client.extra_action(action='network_list', provider=provider, names='names')
def network_create(provider, names, **kwargs):
'''
Create private network
CLI Example:
.. code-block:: bash
salt minionname cloud.network_create my-nova names=['salt'] cidr='192.168.100.0/24'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='network_create', **kwargs)
def virtual_interface_list(provider, names, **kwargs):
'''
List virtual interfaces on a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_list my-nova names=['salt-master']
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_list', **kwargs)
def virtual_interface_create(provider, names, **kwargs):
'''
Attach private interfaces to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_create my-nova names=['salt-master'] net_name='salt'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_create', **kwargs)
|
saltstack/salt
|
salt/modules/cloud.py
|
get_instance
|
python
|
def get_instance(name, provider=None):
'''
Return details on an instance.
Similar to the cloud action show_instance
but returns only the instance details.
CLI Example:
.. code-block:: bash
salt minionname cloud.get_instance myinstance
SLS Example:
.. code-block:: bash
{{ salt['cloud.get_instance']('myinstance')['mac_address'] }}
'''
data = action(fun='show_instance', names=[name], provider=provider)
info = salt.utils.data.simple_types_filter(data)
try:
# get the first: [alias][driver][vm_name]
info = next(six.itervalues(next(six.itervalues(next(six.itervalues(info))))))
except AttributeError:
return None
return info
|
Return details on an instance.
Similar to the cloud action show_instance
but returns only the instance details.
CLI Example:
.. code-block:: bash
salt minionname cloud.get_instance myinstance
SLS Example:
.. code-block:: bash
{{ salt['cloud.get_instance']('myinstance')['mac_address'] }}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L156-L183
|
[
"def itervalues(d, **kw):\n return d.itervalues(**kw)\n",
"def action(\n fun=None,\n cloudmap=None,\n names=None,\n provider=None,\n instance=None,\n **kwargs):\n '''\n Execute a single action on the given provider/instance\n\n CLI Example:\n\n .. code-block:: bash\n\n salt minionname cloud.action start instance=myinstance\n salt minionname cloud.action stop instance=myinstance\n salt minionname cloud.action show_image provider=my-ec2-config image=ami-1624987f\n '''\n client = _get_client()\n try:\n info = client.action(fun, cloudmap, names, provider, instance, kwargs)\n except SaltCloudConfigError as err:\n log.error(err)\n return None\n\n return info\n",
"def simple_types_filter(data):\n '''\n Convert the data list, dictionary into simple types, i.e., int, float, string,\n bool, etc.\n '''\n if data is None:\n return data\n\n simpletypes_keys = (six.string_types, six.text_type, six.integer_types, float, bool)\n simpletypes_values = tuple(list(simpletypes_keys) + [list, tuple])\n\n if isinstance(data, (list, tuple)):\n simplearray = []\n for value in data:\n if value is not None:\n if isinstance(value, (dict, list)):\n value = simple_types_filter(value)\n elif not isinstance(value, simpletypes_values):\n value = repr(value)\n simplearray.append(value)\n return simplearray\n\n if isinstance(data, dict):\n simpledict = {}\n for key, value in six.iteritems(data):\n if key is not None and not isinstance(key, simpletypes_keys):\n key = repr(key)\n if value is not None and isinstance(value, (dict, list, tuple)):\n value = simple_types_filter(value)\n elif value is not None and not isinstance(value, simpletypes_values):\n value = repr(value)\n simpledict[key] = value\n return simpledict\n\n return data\n"
] |
# -*- coding: utf-8 -*-
'''
Salt-specific interface for calling Salt Cloud directly
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
import copy
import salt.utils.data
# Import salt libs
try:
import salt.cloud
HAS_SALTCLOUD = True
except ImportError:
HAS_SALTCLOUD = False
from salt.exceptions import SaltCloudConfigError
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
__func_alias__ = {
'profile_': 'profile'
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if HAS_SALTCLOUD:
return True
return (False, 'The cloud execution module cannot be loaded: only available on non-Windows systems.')
def _get_client():
'''
Return a cloud client
'''
client = salt.cloud.CloudClient(
os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),
pillars=copy.deepcopy(__pillar__.get('cloud', {}))
)
return client
def list_sizes(provider='all'):
'''
List cloud provider sizes for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_sizes my-gce-config
'''
client = _get_client()
sizes = client.list_sizes(provider)
return sizes
def list_images(provider='all'):
'''
List cloud provider images for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_images my-gce-config
'''
client = _get_client()
images = client.list_images(provider)
return images
def list_locations(provider='all'):
'''
List cloud provider locations for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_locations my-gce-config
'''
client = _get_client()
locations = client.list_locations(provider)
return locations
def query(query_type='list_nodes'):
'''
List cloud provider data for all providers
CLI Examples:
.. code-block:: bash
salt minionname cloud.query
salt minionname cloud.query list_nodes_full
salt minionname cloud.query list_nodes_select
'''
client = _get_client()
info = client.query(query_type)
return info
def full_query(query_type='list_nodes_full'):
'''
List all available cloud provider data
CLI Example:
.. code-block:: bash
salt minionname cloud.full_query
'''
return query(query_type=query_type)
def select_query(query_type='list_nodes_select'):
'''
List selected nodes
CLI Example:
.. code-block:: bash
salt minionname cloud.select_query
'''
return query(query_type=query_type)
def has_instance(name, provider=None):
'''
Return true if the instance is found on a provider
CLI Example:
.. code-block:: bash
salt minionname cloud.has_instance myinstance
'''
data = get_instance(name, provider)
if data is None:
return False
return True
def profile_(profile, names, vm_overrides=None, opts=None, **kwargs):
'''
Spin up an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.profile my-gce-config myinstance
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.profile(profile, names, vm_overrides=vm_overrides, **kwargs)
return info
def map_run(path=None, **kwargs):
'''
Execute a salt cloud map file
Cloud Map data can be retrieved from several sources:
- a local file (provide the path to the file to the 'path' argument)
- a JSON-formatted map directly (provide the appropriately formatted to using the 'map_data' argument)
- the Salt Pillar (provide the map name of under 'pillar:cloud:maps' to the 'map_pillar' argument)
.. note::
Only one of these sources can be read at a time. The options are listed
in their order of precedence.
CLI Examples:
.. code-block:: bash
salt minionname cloud.map_run /path/to/cloud.map
salt minionname cloud.map_run path=/path/to/cloud.map
salt minionname cloud.map_run map_pillar='<map_pillar>'
.. versionchanged:: 2018.3.1
salt minionname cloud.map_run map_data='<actual map data>'
'''
client = _get_client()
info = client.map_run(path, **kwargs)
return info
def destroy(names):
'''
Destroy the named VM(s)
CLI Example:
.. code-block:: bash
salt minionname cloud.destroy myinstance
'''
client = _get_client()
info = client.destroy(names)
return info
def action(
fun=None,
cloudmap=None,
names=None,
provider=None,
instance=None,
**kwargs):
'''
Execute a single action on the given provider/instance
CLI Example:
.. code-block:: bash
salt minionname cloud.action start instance=myinstance
salt minionname cloud.action stop instance=myinstance
salt minionname cloud.action show_image provider=my-ec2-config image=ami-1624987f
'''
client = _get_client()
try:
info = client.action(fun, cloudmap, names, provider, instance, kwargs)
except SaltCloudConfigError as err:
log.error(err)
return None
return info
def create(provider, names, opts=None, **kwargs):
'''
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.create(provider, names, **kwargs)
return info
def volume_list(provider):
'''
List block storage volumes
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_list my-nova
'''
client = _get_client()
info = client.extra_action(action='volume_list', provider=provider, names='name')
return info['name']
def volume_delete(provider, names, **kwargs):
'''
Delete volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_delete my-nova myblock
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_delete', **kwargs)
return info
def volume_create(provider, names, **kwargs):
'''
Create volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_create my-nova myblock size=100 voltype=SSD
'''
client = _get_client()
info = client.extra_action(action='volume_create', names=names, provider=provider, **kwargs)
return info
def volume_attach(provider, names, **kwargs):
'''
Attach volume to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_attach my-nova myblock server_name=myserver device='/dev/xvdf'
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_attach', **kwargs)
return info
def volume_detach(provider, names, **kwargs):
'''
Detach volume from a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_detach my-nova myblock server_name=myserver
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_detach', **kwargs)
return info
def network_list(provider):
'''
List private networks
CLI Example:
.. code-block:: bash
salt minionname cloud.network_list my-nova
'''
client = _get_client()
return client.extra_action(action='network_list', provider=provider, names='names')
def network_create(provider, names, **kwargs):
'''
Create private network
CLI Example:
.. code-block:: bash
salt minionname cloud.network_create my-nova names=['salt'] cidr='192.168.100.0/24'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='network_create', **kwargs)
def virtual_interface_list(provider, names, **kwargs):
'''
List virtual interfaces on a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_list my-nova names=['salt-master']
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_list', **kwargs)
def virtual_interface_create(provider, names, **kwargs):
'''
Attach private interfaces to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_create my-nova names=['salt-master'] net_name='salt'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_create', **kwargs)
|
saltstack/salt
|
salt/modules/cloud.py
|
profile_
|
python
|
def profile_(profile, names, vm_overrides=None, opts=None, **kwargs):
'''
Spin up an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.profile my-gce-config myinstance
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.profile(profile, names, vm_overrides=vm_overrides, **kwargs)
return info
|
Spin up an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.profile my-gce-config myinstance
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L186-L200
|
[
"def _get_client():\n '''\n Return a cloud client\n '''\n client = salt.cloud.CloudClient(\n os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),\n pillars=copy.deepcopy(__pillar__.get('cloud', {}))\n )\n return client\n",
"def profile(self, profile, names, vm_overrides=None, **kwargs):\n '''\n Pass in a profile to create, names is a list of vm names to allocate\n\n vm_overrides is a special dict that will be per node options\n overrides\n\n Example:\n\n .. code-block:: python\n\n >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud')\n >>> client.profile('do_512_git', names=['minion01',])\n {'minion01': {'backups_active': 'False',\n 'created_at': '2014-09-04T18:10:15Z',\n 'droplet': {'event_id': 31000502,\n 'id': 2530006,\n 'image_id': 5140006,\n 'name': 'minion01',\n 'size_id': 66},\n 'id': '2530006',\n 'image_id': '5140006',\n 'ip_address': '107.XXX.XXX.XXX',\n 'locked': 'True',\n 'name': 'minion01',\n 'private_ip_address': None,\n 'region_id': '4',\n 'size_id': '66',\n 'status': 'new'}}\n\n\n '''\n if not vm_overrides:\n vm_overrides = {}\n kwargs['profile'] = profile\n mapper = salt.cloud.Map(self._opts_defaults(**kwargs))\n if isinstance(names, six.string_types):\n names = names.split(',')\n return salt.utils.data.simple_types_filter(\n mapper.run_profile(profile, names, vm_overrides=vm_overrides)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Salt-specific interface for calling Salt Cloud directly
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
import copy
import salt.utils.data
# Import salt libs
try:
import salt.cloud
HAS_SALTCLOUD = True
except ImportError:
HAS_SALTCLOUD = False
from salt.exceptions import SaltCloudConfigError
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
__func_alias__ = {
'profile_': 'profile'
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if HAS_SALTCLOUD:
return True
return (False, 'The cloud execution module cannot be loaded: only available on non-Windows systems.')
def _get_client():
'''
Return a cloud client
'''
client = salt.cloud.CloudClient(
os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),
pillars=copy.deepcopy(__pillar__.get('cloud', {}))
)
return client
def list_sizes(provider='all'):
'''
List cloud provider sizes for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_sizes my-gce-config
'''
client = _get_client()
sizes = client.list_sizes(provider)
return sizes
def list_images(provider='all'):
'''
List cloud provider images for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_images my-gce-config
'''
client = _get_client()
images = client.list_images(provider)
return images
def list_locations(provider='all'):
'''
List cloud provider locations for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_locations my-gce-config
'''
client = _get_client()
locations = client.list_locations(provider)
return locations
def query(query_type='list_nodes'):
'''
List cloud provider data for all providers
CLI Examples:
.. code-block:: bash
salt minionname cloud.query
salt minionname cloud.query list_nodes_full
salt minionname cloud.query list_nodes_select
'''
client = _get_client()
info = client.query(query_type)
return info
def full_query(query_type='list_nodes_full'):
'''
List all available cloud provider data
CLI Example:
.. code-block:: bash
salt minionname cloud.full_query
'''
return query(query_type=query_type)
def select_query(query_type='list_nodes_select'):
'''
List selected nodes
CLI Example:
.. code-block:: bash
salt minionname cloud.select_query
'''
return query(query_type=query_type)
def has_instance(name, provider=None):
'''
Return true if the instance is found on a provider
CLI Example:
.. code-block:: bash
salt minionname cloud.has_instance myinstance
'''
data = get_instance(name, provider)
if data is None:
return False
return True
def get_instance(name, provider=None):
'''
Return details on an instance.
Similar to the cloud action show_instance
but returns only the instance details.
CLI Example:
.. code-block:: bash
salt minionname cloud.get_instance myinstance
SLS Example:
.. code-block:: bash
{{ salt['cloud.get_instance']('myinstance')['mac_address'] }}
'''
data = action(fun='show_instance', names=[name], provider=provider)
info = salt.utils.data.simple_types_filter(data)
try:
# get the first: [alias][driver][vm_name]
info = next(six.itervalues(next(six.itervalues(next(six.itervalues(info))))))
except AttributeError:
return None
return info
def map_run(path=None, **kwargs):
'''
Execute a salt cloud map file
Cloud Map data can be retrieved from several sources:
- a local file (provide the path to the file to the 'path' argument)
- a JSON-formatted map directly (provide the appropriately formatted to using the 'map_data' argument)
- the Salt Pillar (provide the map name of under 'pillar:cloud:maps' to the 'map_pillar' argument)
.. note::
Only one of these sources can be read at a time. The options are listed
in their order of precedence.
CLI Examples:
.. code-block:: bash
salt minionname cloud.map_run /path/to/cloud.map
salt minionname cloud.map_run path=/path/to/cloud.map
salt minionname cloud.map_run map_pillar='<map_pillar>'
.. versionchanged:: 2018.3.1
salt minionname cloud.map_run map_data='<actual map data>'
'''
client = _get_client()
info = client.map_run(path, **kwargs)
return info
def destroy(names):
'''
Destroy the named VM(s)
CLI Example:
.. code-block:: bash
salt minionname cloud.destroy myinstance
'''
client = _get_client()
info = client.destroy(names)
return info
def action(
fun=None,
cloudmap=None,
names=None,
provider=None,
instance=None,
**kwargs):
'''
Execute a single action on the given provider/instance
CLI Example:
.. code-block:: bash
salt minionname cloud.action start instance=myinstance
salt minionname cloud.action stop instance=myinstance
salt minionname cloud.action show_image provider=my-ec2-config image=ami-1624987f
'''
client = _get_client()
try:
info = client.action(fun, cloudmap, names, provider, instance, kwargs)
except SaltCloudConfigError as err:
log.error(err)
return None
return info
def create(provider, names, opts=None, **kwargs):
'''
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.create(provider, names, **kwargs)
return info
def volume_list(provider):
'''
List block storage volumes
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_list my-nova
'''
client = _get_client()
info = client.extra_action(action='volume_list', provider=provider, names='name')
return info['name']
def volume_delete(provider, names, **kwargs):
'''
Delete volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_delete my-nova myblock
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_delete', **kwargs)
return info
def volume_create(provider, names, **kwargs):
'''
Create volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_create my-nova myblock size=100 voltype=SSD
'''
client = _get_client()
info = client.extra_action(action='volume_create', names=names, provider=provider, **kwargs)
return info
def volume_attach(provider, names, **kwargs):
'''
Attach volume to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_attach my-nova myblock server_name=myserver device='/dev/xvdf'
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_attach', **kwargs)
return info
def volume_detach(provider, names, **kwargs):
'''
Detach volume from a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_detach my-nova myblock server_name=myserver
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_detach', **kwargs)
return info
def network_list(provider):
'''
List private networks
CLI Example:
.. code-block:: bash
salt minionname cloud.network_list my-nova
'''
client = _get_client()
return client.extra_action(action='network_list', provider=provider, names='names')
def network_create(provider, names, **kwargs):
'''
Create private network
CLI Example:
.. code-block:: bash
salt minionname cloud.network_create my-nova names=['salt'] cidr='192.168.100.0/24'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='network_create', **kwargs)
def virtual_interface_list(provider, names, **kwargs):
'''
List virtual interfaces on a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_list my-nova names=['salt-master']
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_list', **kwargs)
def virtual_interface_create(provider, names, **kwargs):
'''
Attach private interfaces to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_create my-nova names=['salt-master'] net_name='salt'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_create', **kwargs)
|
saltstack/salt
|
salt/modules/cloud.py
|
map_run
|
python
|
def map_run(path=None, **kwargs):
'''
Execute a salt cloud map file
Cloud Map data can be retrieved from several sources:
- a local file (provide the path to the file to the 'path' argument)
- a JSON-formatted map directly (provide the appropriately formatted to using the 'map_data' argument)
- the Salt Pillar (provide the map name of under 'pillar:cloud:maps' to the 'map_pillar' argument)
.. note::
Only one of these sources can be read at a time. The options are listed
in their order of precedence.
CLI Examples:
.. code-block:: bash
salt minionname cloud.map_run /path/to/cloud.map
salt minionname cloud.map_run path=/path/to/cloud.map
salt minionname cloud.map_run map_pillar='<map_pillar>'
.. versionchanged:: 2018.3.1
salt minionname cloud.map_run map_data='<actual map data>'
'''
client = _get_client()
info = client.map_run(path, **kwargs)
return info
|
Execute a salt cloud map file
Cloud Map data can be retrieved from several sources:
- a local file (provide the path to the file to the 'path' argument)
- a JSON-formatted map directly (provide the appropriately formatted to using the 'map_data' argument)
- the Salt Pillar (provide the map name of under 'pillar:cloud:maps' to the 'map_pillar' argument)
.. note::
Only one of these sources can be read at a time. The options are listed
in their order of precedence.
CLI Examples:
.. code-block:: bash
salt minionname cloud.map_run /path/to/cloud.map
salt minionname cloud.map_run path=/path/to/cloud.map
salt minionname cloud.map_run map_pillar='<map_pillar>'
.. versionchanged:: 2018.3.1
salt minionname cloud.map_run map_data='<actual map data>'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L203-L229
|
[
"def _get_client():\n '''\n Return a cloud client\n '''\n client = salt.cloud.CloudClient(\n os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),\n pillars=copy.deepcopy(__pillar__.get('cloud', {}))\n )\n return client\n",
"def map_run(self, path=None, **kwargs):\n '''\n To execute a map\n '''\n kwarg = {}\n if path:\n kwarg['map'] = path\n kwarg.update(kwargs)\n mapper = salt.cloud.Map(self._opts_defaults(**kwarg))\n dmap = mapper.map_data()\n return salt.utils.data.simple_types_filter(\n mapper.run_map(dmap)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Salt-specific interface for calling Salt Cloud directly
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
import copy
import salt.utils.data
# Import salt libs
try:
import salt.cloud
HAS_SALTCLOUD = True
except ImportError:
HAS_SALTCLOUD = False
from salt.exceptions import SaltCloudConfigError
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
__func_alias__ = {
'profile_': 'profile'
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if HAS_SALTCLOUD:
return True
return (False, 'The cloud execution module cannot be loaded: only available on non-Windows systems.')
def _get_client():
'''
Return a cloud client
'''
client = salt.cloud.CloudClient(
os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),
pillars=copy.deepcopy(__pillar__.get('cloud', {}))
)
return client
def list_sizes(provider='all'):
'''
List cloud provider sizes for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_sizes my-gce-config
'''
client = _get_client()
sizes = client.list_sizes(provider)
return sizes
def list_images(provider='all'):
'''
List cloud provider images for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_images my-gce-config
'''
client = _get_client()
images = client.list_images(provider)
return images
def list_locations(provider='all'):
'''
List cloud provider locations for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_locations my-gce-config
'''
client = _get_client()
locations = client.list_locations(provider)
return locations
def query(query_type='list_nodes'):
'''
List cloud provider data for all providers
CLI Examples:
.. code-block:: bash
salt minionname cloud.query
salt minionname cloud.query list_nodes_full
salt minionname cloud.query list_nodes_select
'''
client = _get_client()
info = client.query(query_type)
return info
def full_query(query_type='list_nodes_full'):
'''
List all available cloud provider data
CLI Example:
.. code-block:: bash
salt minionname cloud.full_query
'''
return query(query_type=query_type)
def select_query(query_type='list_nodes_select'):
'''
List selected nodes
CLI Example:
.. code-block:: bash
salt minionname cloud.select_query
'''
return query(query_type=query_type)
def has_instance(name, provider=None):
'''
Return true if the instance is found on a provider
CLI Example:
.. code-block:: bash
salt minionname cloud.has_instance myinstance
'''
data = get_instance(name, provider)
if data is None:
return False
return True
def get_instance(name, provider=None):
'''
Return details on an instance.
Similar to the cloud action show_instance
but returns only the instance details.
CLI Example:
.. code-block:: bash
salt minionname cloud.get_instance myinstance
SLS Example:
.. code-block:: bash
{{ salt['cloud.get_instance']('myinstance')['mac_address'] }}
'''
data = action(fun='show_instance', names=[name], provider=provider)
info = salt.utils.data.simple_types_filter(data)
try:
# get the first: [alias][driver][vm_name]
info = next(six.itervalues(next(six.itervalues(next(six.itervalues(info))))))
except AttributeError:
return None
return info
def profile_(profile, names, vm_overrides=None, opts=None, **kwargs):
'''
Spin up an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.profile my-gce-config myinstance
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.profile(profile, names, vm_overrides=vm_overrides, **kwargs)
return info
def destroy(names):
'''
Destroy the named VM(s)
CLI Example:
.. code-block:: bash
salt minionname cloud.destroy myinstance
'''
client = _get_client()
info = client.destroy(names)
return info
def action(
fun=None,
cloudmap=None,
names=None,
provider=None,
instance=None,
**kwargs):
'''
Execute a single action on the given provider/instance
CLI Example:
.. code-block:: bash
salt minionname cloud.action start instance=myinstance
salt minionname cloud.action stop instance=myinstance
salt minionname cloud.action show_image provider=my-ec2-config image=ami-1624987f
'''
client = _get_client()
try:
info = client.action(fun, cloudmap, names, provider, instance, kwargs)
except SaltCloudConfigError as err:
log.error(err)
return None
return info
def create(provider, names, opts=None, **kwargs):
'''
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.create(provider, names, **kwargs)
return info
def volume_list(provider):
'''
List block storage volumes
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_list my-nova
'''
client = _get_client()
info = client.extra_action(action='volume_list', provider=provider, names='name')
return info['name']
def volume_delete(provider, names, **kwargs):
'''
Delete volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_delete my-nova myblock
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_delete', **kwargs)
return info
def volume_create(provider, names, **kwargs):
'''
Create volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_create my-nova myblock size=100 voltype=SSD
'''
client = _get_client()
info = client.extra_action(action='volume_create', names=names, provider=provider, **kwargs)
return info
def volume_attach(provider, names, **kwargs):
'''
Attach volume to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_attach my-nova myblock server_name=myserver device='/dev/xvdf'
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_attach', **kwargs)
return info
def volume_detach(provider, names, **kwargs):
'''
Detach volume from a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_detach my-nova myblock server_name=myserver
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_detach', **kwargs)
return info
def network_list(provider):
'''
List private networks
CLI Example:
.. code-block:: bash
salt minionname cloud.network_list my-nova
'''
client = _get_client()
return client.extra_action(action='network_list', provider=provider, names='names')
def network_create(provider, names, **kwargs):
'''
Create private network
CLI Example:
.. code-block:: bash
salt minionname cloud.network_create my-nova names=['salt'] cidr='192.168.100.0/24'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='network_create', **kwargs)
def virtual_interface_list(provider, names, **kwargs):
'''
List virtual interfaces on a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_list my-nova names=['salt-master']
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_list', **kwargs)
def virtual_interface_create(provider, names, **kwargs):
'''
Attach private interfaces to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_create my-nova names=['salt-master'] net_name='salt'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_create', **kwargs)
|
saltstack/salt
|
salt/modules/cloud.py
|
action
|
python
|
def action(
fun=None,
cloudmap=None,
names=None,
provider=None,
instance=None,
**kwargs):
'''
Execute a single action on the given provider/instance
CLI Example:
.. code-block:: bash
salt minionname cloud.action start instance=myinstance
salt minionname cloud.action stop instance=myinstance
salt minionname cloud.action show_image provider=my-ec2-config image=ami-1624987f
'''
client = _get_client()
try:
info = client.action(fun, cloudmap, names, provider, instance, kwargs)
except SaltCloudConfigError as err:
log.error(err)
return None
return info
|
Execute a single action on the given provider/instance
CLI Example:
.. code-block:: bash
salt minionname cloud.action start instance=myinstance
salt minionname cloud.action stop instance=myinstance
salt minionname cloud.action show_image provider=my-ec2-config image=ami-1624987f
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L247-L272
|
[
"def _get_client():\n '''\n Return a cloud client\n '''\n client = salt.cloud.CloudClient(\n os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),\n pillars=copy.deepcopy(__pillar__.get('cloud', {}))\n )\n return client\n",
"def action(\n self,\n fun=None,\n cloudmap=None,\n names=None,\n provider=None,\n instance=None,\n kwargs=None\n):\n '''\n Execute a single action via the cloud plugin backend\n\n Examples:\n\n .. code-block:: python\n\n client.action(fun='show_instance', names=['myinstance'])\n client.action(fun='show_image', provider='my-ec2-config',\n kwargs={'image': 'ami-10314d79'}\n )\n '''\n if kwargs is None:\n kwargs = {}\n\n mapper = salt.cloud.Map(self._opts_defaults(\n action=fun,\n names=names,\n **kwargs))\n if instance:\n if names:\n raise SaltCloudConfigError(\n 'Please specify either a list of \\'names\\' or a single '\n '\\'instance\\', but not both.'\n )\n names = [instance]\n\n if names and not provider:\n self.opts['action'] = fun\n return mapper.do_action(names, kwargs)\n\n if provider and not names:\n return mapper.do_function(provider, fun, kwargs)\n else:\n # This should not be called without either an instance or a\n # provider. If both an instance/list of names and a provider\n # are given, then we also need to exit. We can only have one\n # or the other.\n raise SaltCloudConfigError(\n 'Either an instance (or list of names) or a provider must be '\n 'specified, but not both.'\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Salt-specific interface for calling Salt Cloud directly
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
import copy
import salt.utils.data
# Import salt libs
try:
import salt.cloud
HAS_SALTCLOUD = True
except ImportError:
HAS_SALTCLOUD = False
from salt.exceptions import SaltCloudConfigError
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
__func_alias__ = {
'profile_': 'profile'
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if HAS_SALTCLOUD:
return True
return (False, 'The cloud execution module cannot be loaded: only available on non-Windows systems.')
def _get_client():
'''
Return a cloud client
'''
client = salt.cloud.CloudClient(
os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),
pillars=copy.deepcopy(__pillar__.get('cloud', {}))
)
return client
def list_sizes(provider='all'):
'''
List cloud provider sizes for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_sizes my-gce-config
'''
client = _get_client()
sizes = client.list_sizes(provider)
return sizes
def list_images(provider='all'):
'''
List cloud provider images for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_images my-gce-config
'''
client = _get_client()
images = client.list_images(provider)
return images
def list_locations(provider='all'):
'''
List cloud provider locations for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_locations my-gce-config
'''
client = _get_client()
locations = client.list_locations(provider)
return locations
def query(query_type='list_nodes'):
'''
List cloud provider data for all providers
CLI Examples:
.. code-block:: bash
salt minionname cloud.query
salt minionname cloud.query list_nodes_full
salt minionname cloud.query list_nodes_select
'''
client = _get_client()
info = client.query(query_type)
return info
def full_query(query_type='list_nodes_full'):
'''
List all available cloud provider data
CLI Example:
.. code-block:: bash
salt minionname cloud.full_query
'''
return query(query_type=query_type)
def select_query(query_type='list_nodes_select'):
'''
List selected nodes
CLI Example:
.. code-block:: bash
salt minionname cloud.select_query
'''
return query(query_type=query_type)
def has_instance(name, provider=None):
'''
Return true if the instance is found on a provider
CLI Example:
.. code-block:: bash
salt minionname cloud.has_instance myinstance
'''
data = get_instance(name, provider)
if data is None:
return False
return True
def get_instance(name, provider=None):
'''
Return details on an instance.
Similar to the cloud action show_instance
but returns only the instance details.
CLI Example:
.. code-block:: bash
salt minionname cloud.get_instance myinstance
SLS Example:
.. code-block:: bash
{{ salt['cloud.get_instance']('myinstance')['mac_address'] }}
'''
data = action(fun='show_instance', names=[name], provider=provider)
info = salt.utils.data.simple_types_filter(data)
try:
# get the first: [alias][driver][vm_name]
info = next(six.itervalues(next(six.itervalues(next(six.itervalues(info))))))
except AttributeError:
return None
return info
def profile_(profile, names, vm_overrides=None, opts=None, **kwargs):
'''
Spin up an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.profile my-gce-config myinstance
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.profile(profile, names, vm_overrides=vm_overrides, **kwargs)
return info
def map_run(path=None, **kwargs):
'''
Execute a salt cloud map file
Cloud Map data can be retrieved from several sources:
- a local file (provide the path to the file to the 'path' argument)
- a JSON-formatted map directly (provide the appropriately formatted to using the 'map_data' argument)
- the Salt Pillar (provide the map name of under 'pillar:cloud:maps' to the 'map_pillar' argument)
.. note::
Only one of these sources can be read at a time. The options are listed
in their order of precedence.
CLI Examples:
.. code-block:: bash
salt minionname cloud.map_run /path/to/cloud.map
salt minionname cloud.map_run path=/path/to/cloud.map
salt minionname cloud.map_run map_pillar='<map_pillar>'
.. versionchanged:: 2018.3.1
salt minionname cloud.map_run map_data='<actual map data>'
'''
client = _get_client()
info = client.map_run(path, **kwargs)
return info
def destroy(names):
'''
Destroy the named VM(s)
CLI Example:
.. code-block:: bash
salt minionname cloud.destroy myinstance
'''
client = _get_client()
info = client.destroy(names)
return info
def create(provider, names, opts=None, **kwargs):
'''
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.create(provider, names, **kwargs)
return info
def volume_list(provider):
'''
List block storage volumes
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_list my-nova
'''
client = _get_client()
info = client.extra_action(action='volume_list', provider=provider, names='name')
return info['name']
def volume_delete(provider, names, **kwargs):
'''
Delete volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_delete my-nova myblock
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_delete', **kwargs)
return info
def volume_create(provider, names, **kwargs):
'''
Create volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_create my-nova myblock size=100 voltype=SSD
'''
client = _get_client()
info = client.extra_action(action='volume_create', names=names, provider=provider, **kwargs)
return info
def volume_attach(provider, names, **kwargs):
'''
Attach volume to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_attach my-nova myblock server_name=myserver device='/dev/xvdf'
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_attach', **kwargs)
return info
def volume_detach(provider, names, **kwargs):
'''
Detach volume from a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_detach my-nova myblock server_name=myserver
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_detach', **kwargs)
return info
def network_list(provider):
'''
List private networks
CLI Example:
.. code-block:: bash
salt minionname cloud.network_list my-nova
'''
client = _get_client()
return client.extra_action(action='network_list', provider=provider, names='names')
def network_create(provider, names, **kwargs):
'''
Create private network
CLI Example:
.. code-block:: bash
salt minionname cloud.network_create my-nova names=['salt'] cidr='192.168.100.0/24'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='network_create', **kwargs)
def virtual_interface_list(provider, names, **kwargs):
'''
List virtual interfaces on a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_list my-nova names=['salt-master']
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_list', **kwargs)
def virtual_interface_create(provider, names, **kwargs):
'''
Attach private interfaces to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_create my-nova names=['salt-master'] net_name='salt'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_create', **kwargs)
|
saltstack/salt
|
salt/modules/cloud.py
|
create
|
python
|
def create(provider, names, opts=None, **kwargs):
'''
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.create(provider, names, **kwargs)
return info
|
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L275-L289
|
[
"def _get_client():\n '''\n Return a cloud client\n '''\n client = salt.cloud.CloudClient(\n os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),\n pillars=copy.deepcopy(__pillar__.get('cloud', {}))\n )\n return client\n",
"def create(self, provider, names, **kwargs):\n '''\n Create the named VMs, without using a profile\n\n Example:\n\n .. code-block:: python\n\n client.create(provider='my-ec2-config', names=['myinstance'],\n image='ami-1624987f', size='t1.micro', ssh_username='ec2-user',\n securitygroup='default', delvol_on_destroy=True)\n '''\n mapper = salt.cloud.Map(self._opts_defaults())\n providers = self.opts['providers']\n if provider in providers:\n provider += ':{0}'.format(next(six.iterkeys(providers[provider])))\n else:\n return False\n if isinstance(names, six.string_types):\n names = names.split(',')\n ret = {}\n for name in names:\n vm_ = kwargs.copy()\n vm_['name'] = name\n vm_['driver'] = provider\n\n # This function doesn't require a profile, but many cloud drivers\n # check for profile information (which includes the provider key) to\n # help with config file debugging and setting up instances. Setting\n # the profile and provider defaults here avoids errors in other\n # cloud functions relying on these keys. See SaltStack Issue #41971\n # and PR #38166 for more information.\n vm_['profile'] = None\n vm_['provider'] = provider\n\n ret[name] = salt.utils.data.simple_types_filter(\n mapper.create(vm_))\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Salt-specific interface for calling Salt Cloud directly
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
import copy
import salt.utils.data
# Import salt libs
try:
import salt.cloud
HAS_SALTCLOUD = True
except ImportError:
HAS_SALTCLOUD = False
from salt.exceptions import SaltCloudConfigError
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
__func_alias__ = {
'profile_': 'profile'
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if HAS_SALTCLOUD:
return True
return (False, 'The cloud execution module cannot be loaded: only available on non-Windows systems.')
def _get_client():
'''
Return a cloud client
'''
client = salt.cloud.CloudClient(
os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),
pillars=copy.deepcopy(__pillar__.get('cloud', {}))
)
return client
def list_sizes(provider='all'):
'''
List cloud provider sizes for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_sizes my-gce-config
'''
client = _get_client()
sizes = client.list_sizes(provider)
return sizes
def list_images(provider='all'):
'''
List cloud provider images for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_images my-gce-config
'''
client = _get_client()
images = client.list_images(provider)
return images
def list_locations(provider='all'):
'''
List cloud provider locations for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_locations my-gce-config
'''
client = _get_client()
locations = client.list_locations(provider)
return locations
def query(query_type='list_nodes'):
'''
List cloud provider data for all providers
CLI Examples:
.. code-block:: bash
salt minionname cloud.query
salt minionname cloud.query list_nodes_full
salt minionname cloud.query list_nodes_select
'''
client = _get_client()
info = client.query(query_type)
return info
def full_query(query_type='list_nodes_full'):
'''
List all available cloud provider data
CLI Example:
.. code-block:: bash
salt minionname cloud.full_query
'''
return query(query_type=query_type)
def select_query(query_type='list_nodes_select'):
'''
List selected nodes
CLI Example:
.. code-block:: bash
salt minionname cloud.select_query
'''
return query(query_type=query_type)
def has_instance(name, provider=None):
'''
Return true if the instance is found on a provider
CLI Example:
.. code-block:: bash
salt minionname cloud.has_instance myinstance
'''
data = get_instance(name, provider)
if data is None:
return False
return True
def get_instance(name, provider=None):
'''
Return details on an instance.
Similar to the cloud action show_instance
but returns only the instance details.
CLI Example:
.. code-block:: bash
salt minionname cloud.get_instance myinstance
SLS Example:
.. code-block:: bash
{{ salt['cloud.get_instance']('myinstance')['mac_address'] }}
'''
data = action(fun='show_instance', names=[name], provider=provider)
info = salt.utils.data.simple_types_filter(data)
try:
# get the first: [alias][driver][vm_name]
info = next(six.itervalues(next(six.itervalues(next(six.itervalues(info))))))
except AttributeError:
return None
return info
def profile_(profile, names, vm_overrides=None, opts=None, **kwargs):
'''
Spin up an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.profile my-gce-config myinstance
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.profile(profile, names, vm_overrides=vm_overrides, **kwargs)
return info
def map_run(path=None, **kwargs):
'''
Execute a salt cloud map file
Cloud Map data can be retrieved from several sources:
- a local file (provide the path to the file to the 'path' argument)
- a JSON-formatted map directly (provide the appropriately formatted to using the 'map_data' argument)
- the Salt Pillar (provide the map name of under 'pillar:cloud:maps' to the 'map_pillar' argument)
.. note::
Only one of these sources can be read at a time. The options are listed
in their order of precedence.
CLI Examples:
.. code-block:: bash
salt minionname cloud.map_run /path/to/cloud.map
salt minionname cloud.map_run path=/path/to/cloud.map
salt minionname cloud.map_run map_pillar='<map_pillar>'
.. versionchanged:: 2018.3.1
salt minionname cloud.map_run map_data='<actual map data>'
'''
client = _get_client()
info = client.map_run(path, **kwargs)
return info
def destroy(names):
'''
Destroy the named VM(s)
CLI Example:
.. code-block:: bash
salt minionname cloud.destroy myinstance
'''
client = _get_client()
info = client.destroy(names)
return info
def action(
fun=None,
cloudmap=None,
names=None,
provider=None,
instance=None,
**kwargs):
'''
Execute a single action on the given provider/instance
CLI Example:
.. code-block:: bash
salt minionname cloud.action start instance=myinstance
salt minionname cloud.action stop instance=myinstance
salt minionname cloud.action show_image provider=my-ec2-config image=ami-1624987f
'''
client = _get_client()
try:
info = client.action(fun, cloudmap, names, provider, instance, kwargs)
except SaltCloudConfigError as err:
log.error(err)
return None
return info
def volume_list(provider):
'''
List block storage volumes
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_list my-nova
'''
client = _get_client()
info = client.extra_action(action='volume_list', provider=provider, names='name')
return info['name']
def volume_delete(provider, names, **kwargs):
'''
Delete volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_delete my-nova myblock
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_delete', **kwargs)
return info
def volume_create(provider, names, **kwargs):
'''
Create volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_create my-nova myblock size=100 voltype=SSD
'''
client = _get_client()
info = client.extra_action(action='volume_create', names=names, provider=provider, **kwargs)
return info
def volume_attach(provider, names, **kwargs):
'''
Attach volume to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_attach my-nova myblock server_name=myserver device='/dev/xvdf'
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_attach', **kwargs)
return info
def volume_detach(provider, names, **kwargs):
'''
Detach volume from a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_detach my-nova myblock server_name=myserver
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_detach', **kwargs)
return info
def network_list(provider):
'''
List private networks
CLI Example:
.. code-block:: bash
salt minionname cloud.network_list my-nova
'''
client = _get_client()
return client.extra_action(action='network_list', provider=provider, names='names')
def network_create(provider, names, **kwargs):
'''
Create private network
CLI Example:
.. code-block:: bash
salt minionname cloud.network_create my-nova names=['salt'] cidr='192.168.100.0/24'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='network_create', **kwargs)
def virtual_interface_list(provider, names, **kwargs):
'''
List virtual interfaces on a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_list my-nova names=['salt-master']
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_list', **kwargs)
def virtual_interface_create(provider, names, **kwargs):
'''
Attach private interfaces to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_create my-nova names=['salt-master'] net_name='salt'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_create', **kwargs)
|
saltstack/salt
|
salt/modules/cloud.py
|
volume_list
|
python
|
def volume_list(provider):
'''
List block storage volumes
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_list my-nova
'''
client = _get_client()
info = client.extra_action(action='volume_list', provider=provider, names='name')
return info['name']
|
List block storage volumes
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_list my-nova
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L292-L305
|
[
"def _get_client():\n '''\n Return a cloud client\n '''\n client = salt.cloud.CloudClient(\n os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),\n pillars=copy.deepcopy(__pillar__.get('cloud', {}))\n )\n return client\n",
"def extra_action(self, names, provider, action, **kwargs):\n '''\n Perform actions with block storage devices\n\n Example:\n\n .. code-block:: python\n\n client.extra_action(names=['myblock'], action='volume_create',\n provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000}\n )\n client.extra_action(names=['salt-net'], action='network_create',\n provider='my-nova', kwargs={'cidr': '192.168.100.0/24'}\n )\n '''\n mapper = salt.cloud.Map(self._opts_defaults())\n providers = mapper.map_providers_parallel()\n if provider in providers:\n provider += ':{0}'.format(next(six.iterkeys(providers[provider])))\n else:\n return False\n if isinstance(names, six.string_types):\n names = names.split(',')\n\n ret = {}\n for name in names:\n extra_ = kwargs.copy()\n extra_['name'] = name\n extra_['provider'] = provider\n extra_['profile'] = None\n extra_['action'] = action\n ret[name] = salt.utils.data.simple_types_filter(\n mapper.extras(extra_)\n )\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Salt-specific interface for calling Salt Cloud directly
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
import copy
import salt.utils.data
# Import salt libs
try:
import salt.cloud
HAS_SALTCLOUD = True
except ImportError:
HAS_SALTCLOUD = False
from salt.exceptions import SaltCloudConfigError
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
__func_alias__ = {
'profile_': 'profile'
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if HAS_SALTCLOUD:
return True
return (False, 'The cloud execution module cannot be loaded: only available on non-Windows systems.')
def _get_client():
'''
Return a cloud client
'''
client = salt.cloud.CloudClient(
os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),
pillars=copy.deepcopy(__pillar__.get('cloud', {}))
)
return client
def list_sizes(provider='all'):
'''
List cloud provider sizes for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_sizes my-gce-config
'''
client = _get_client()
sizes = client.list_sizes(provider)
return sizes
def list_images(provider='all'):
'''
List cloud provider images for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_images my-gce-config
'''
client = _get_client()
images = client.list_images(provider)
return images
def list_locations(provider='all'):
'''
List cloud provider locations for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_locations my-gce-config
'''
client = _get_client()
locations = client.list_locations(provider)
return locations
def query(query_type='list_nodes'):
'''
List cloud provider data for all providers
CLI Examples:
.. code-block:: bash
salt minionname cloud.query
salt minionname cloud.query list_nodes_full
salt minionname cloud.query list_nodes_select
'''
client = _get_client()
info = client.query(query_type)
return info
def full_query(query_type='list_nodes_full'):
'''
List all available cloud provider data
CLI Example:
.. code-block:: bash
salt minionname cloud.full_query
'''
return query(query_type=query_type)
def select_query(query_type='list_nodes_select'):
'''
List selected nodes
CLI Example:
.. code-block:: bash
salt minionname cloud.select_query
'''
return query(query_type=query_type)
def has_instance(name, provider=None):
'''
Return true if the instance is found on a provider
CLI Example:
.. code-block:: bash
salt minionname cloud.has_instance myinstance
'''
data = get_instance(name, provider)
if data is None:
return False
return True
def get_instance(name, provider=None):
'''
Return details on an instance.
Similar to the cloud action show_instance
but returns only the instance details.
CLI Example:
.. code-block:: bash
salt minionname cloud.get_instance myinstance
SLS Example:
.. code-block:: bash
{{ salt['cloud.get_instance']('myinstance')['mac_address'] }}
'''
data = action(fun='show_instance', names=[name], provider=provider)
info = salt.utils.data.simple_types_filter(data)
try:
# get the first: [alias][driver][vm_name]
info = next(six.itervalues(next(six.itervalues(next(six.itervalues(info))))))
except AttributeError:
return None
return info
def profile_(profile, names, vm_overrides=None, opts=None, **kwargs):
'''
Spin up an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.profile my-gce-config myinstance
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.profile(profile, names, vm_overrides=vm_overrides, **kwargs)
return info
def map_run(path=None, **kwargs):
'''
Execute a salt cloud map file
Cloud Map data can be retrieved from several sources:
- a local file (provide the path to the file to the 'path' argument)
- a JSON-formatted map directly (provide the appropriately formatted to using the 'map_data' argument)
- the Salt Pillar (provide the map name of under 'pillar:cloud:maps' to the 'map_pillar' argument)
.. note::
Only one of these sources can be read at a time. The options are listed
in their order of precedence.
CLI Examples:
.. code-block:: bash
salt minionname cloud.map_run /path/to/cloud.map
salt minionname cloud.map_run path=/path/to/cloud.map
salt minionname cloud.map_run map_pillar='<map_pillar>'
.. versionchanged:: 2018.3.1
salt minionname cloud.map_run map_data='<actual map data>'
'''
client = _get_client()
info = client.map_run(path, **kwargs)
return info
def destroy(names):
'''
Destroy the named VM(s)
CLI Example:
.. code-block:: bash
salt minionname cloud.destroy myinstance
'''
client = _get_client()
info = client.destroy(names)
return info
def action(
fun=None,
cloudmap=None,
names=None,
provider=None,
instance=None,
**kwargs):
'''
Execute a single action on the given provider/instance
CLI Example:
.. code-block:: bash
salt minionname cloud.action start instance=myinstance
salt minionname cloud.action stop instance=myinstance
salt minionname cloud.action show_image provider=my-ec2-config image=ami-1624987f
'''
client = _get_client()
try:
info = client.action(fun, cloudmap, names, provider, instance, kwargs)
except SaltCloudConfigError as err:
log.error(err)
return None
return info
def create(provider, names, opts=None, **kwargs):
'''
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.create(provider, names, **kwargs)
return info
def volume_delete(provider, names, **kwargs):
'''
Delete volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_delete my-nova myblock
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_delete', **kwargs)
return info
def volume_create(provider, names, **kwargs):
'''
Create volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_create my-nova myblock size=100 voltype=SSD
'''
client = _get_client()
info = client.extra_action(action='volume_create', names=names, provider=provider, **kwargs)
return info
def volume_attach(provider, names, **kwargs):
'''
Attach volume to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_attach my-nova myblock server_name=myserver device='/dev/xvdf'
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_attach', **kwargs)
return info
def volume_detach(provider, names, **kwargs):
'''
Detach volume from a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_detach my-nova myblock server_name=myserver
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_detach', **kwargs)
return info
def network_list(provider):
'''
List private networks
CLI Example:
.. code-block:: bash
salt minionname cloud.network_list my-nova
'''
client = _get_client()
return client.extra_action(action='network_list', provider=provider, names='names')
def network_create(provider, names, **kwargs):
'''
Create private network
CLI Example:
.. code-block:: bash
salt minionname cloud.network_create my-nova names=['salt'] cidr='192.168.100.0/24'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='network_create', **kwargs)
def virtual_interface_list(provider, names, **kwargs):
'''
List virtual interfaces on a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_list my-nova names=['salt-master']
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_list', **kwargs)
def virtual_interface_create(provider, names, **kwargs):
'''
Attach private interfaces to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_create my-nova names=['salt-master'] net_name='salt'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_create', **kwargs)
|
saltstack/salt
|
salt/modules/cloud.py
|
volume_attach
|
python
|
def volume_attach(provider, names, **kwargs):
'''
Attach volume to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_attach my-nova myblock server_name=myserver device='/dev/xvdf'
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_attach', **kwargs)
return info
|
Attach volume to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_attach my-nova myblock server_name=myserver device='/dev/xvdf'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L340-L353
|
[
"def _get_client():\n '''\n Return a cloud client\n '''\n client = salt.cloud.CloudClient(\n os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),\n pillars=copy.deepcopy(__pillar__.get('cloud', {}))\n )\n return client\n",
"def extra_action(self, names, provider, action, **kwargs):\n '''\n Perform actions with block storage devices\n\n Example:\n\n .. code-block:: python\n\n client.extra_action(names=['myblock'], action='volume_create',\n provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000}\n )\n client.extra_action(names=['salt-net'], action='network_create',\n provider='my-nova', kwargs={'cidr': '192.168.100.0/24'}\n )\n '''\n mapper = salt.cloud.Map(self._opts_defaults())\n providers = mapper.map_providers_parallel()\n if provider in providers:\n provider += ':{0}'.format(next(six.iterkeys(providers[provider])))\n else:\n return False\n if isinstance(names, six.string_types):\n names = names.split(',')\n\n ret = {}\n for name in names:\n extra_ = kwargs.copy()\n extra_['name'] = name\n extra_['provider'] = provider\n extra_['profile'] = None\n extra_['action'] = action\n ret[name] = salt.utils.data.simple_types_filter(\n mapper.extras(extra_)\n )\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Salt-specific interface for calling Salt Cloud directly
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
import copy
import salt.utils.data
# Import salt libs
try:
import salt.cloud
HAS_SALTCLOUD = True
except ImportError:
HAS_SALTCLOUD = False
from salt.exceptions import SaltCloudConfigError
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
__func_alias__ = {
'profile_': 'profile'
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if HAS_SALTCLOUD:
return True
return (False, 'The cloud execution module cannot be loaded: only available on non-Windows systems.')
def _get_client():
'''
Return a cloud client
'''
client = salt.cloud.CloudClient(
os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),
pillars=copy.deepcopy(__pillar__.get('cloud', {}))
)
return client
def list_sizes(provider='all'):
'''
List cloud provider sizes for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_sizes my-gce-config
'''
client = _get_client()
sizes = client.list_sizes(provider)
return sizes
def list_images(provider='all'):
'''
List cloud provider images for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_images my-gce-config
'''
client = _get_client()
images = client.list_images(provider)
return images
def list_locations(provider='all'):
'''
List cloud provider locations for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_locations my-gce-config
'''
client = _get_client()
locations = client.list_locations(provider)
return locations
def query(query_type='list_nodes'):
'''
List cloud provider data for all providers
CLI Examples:
.. code-block:: bash
salt minionname cloud.query
salt minionname cloud.query list_nodes_full
salt minionname cloud.query list_nodes_select
'''
client = _get_client()
info = client.query(query_type)
return info
def full_query(query_type='list_nodes_full'):
'''
List all available cloud provider data
CLI Example:
.. code-block:: bash
salt minionname cloud.full_query
'''
return query(query_type=query_type)
def select_query(query_type='list_nodes_select'):
'''
List selected nodes
CLI Example:
.. code-block:: bash
salt minionname cloud.select_query
'''
return query(query_type=query_type)
def has_instance(name, provider=None):
'''
Return true if the instance is found on a provider
CLI Example:
.. code-block:: bash
salt minionname cloud.has_instance myinstance
'''
data = get_instance(name, provider)
if data is None:
return False
return True
def get_instance(name, provider=None):
'''
Return details on an instance.
Similar to the cloud action show_instance
but returns only the instance details.
CLI Example:
.. code-block:: bash
salt minionname cloud.get_instance myinstance
SLS Example:
.. code-block:: bash
{{ salt['cloud.get_instance']('myinstance')['mac_address'] }}
'''
data = action(fun='show_instance', names=[name], provider=provider)
info = salt.utils.data.simple_types_filter(data)
try:
# get the first: [alias][driver][vm_name]
info = next(six.itervalues(next(six.itervalues(next(six.itervalues(info))))))
except AttributeError:
return None
return info
def profile_(profile, names, vm_overrides=None, opts=None, **kwargs):
'''
Spin up an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.profile my-gce-config myinstance
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.profile(profile, names, vm_overrides=vm_overrides, **kwargs)
return info
def map_run(path=None, **kwargs):
'''
Execute a salt cloud map file
Cloud Map data can be retrieved from several sources:
- a local file (provide the path to the file to the 'path' argument)
- a JSON-formatted map directly (provide the appropriately formatted to using the 'map_data' argument)
- the Salt Pillar (provide the map name of under 'pillar:cloud:maps' to the 'map_pillar' argument)
.. note::
Only one of these sources can be read at a time. The options are listed
in their order of precedence.
CLI Examples:
.. code-block:: bash
salt minionname cloud.map_run /path/to/cloud.map
salt minionname cloud.map_run path=/path/to/cloud.map
salt minionname cloud.map_run map_pillar='<map_pillar>'
.. versionchanged:: 2018.3.1
salt minionname cloud.map_run map_data='<actual map data>'
'''
client = _get_client()
info = client.map_run(path, **kwargs)
return info
def destroy(names):
'''
Destroy the named VM(s)
CLI Example:
.. code-block:: bash
salt minionname cloud.destroy myinstance
'''
client = _get_client()
info = client.destroy(names)
return info
def action(
fun=None,
cloudmap=None,
names=None,
provider=None,
instance=None,
**kwargs):
'''
Execute a single action on the given provider/instance
CLI Example:
.. code-block:: bash
salt minionname cloud.action start instance=myinstance
salt minionname cloud.action stop instance=myinstance
salt minionname cloud.action show_image provider=my-ec2-config image=ami-1624987f
'''
client = _get_client()
try:
info = client.action(fun, cloudmap, names, provider, instance, kwargs)
except SaltCloudConfigError as err:
log.error(err)
return None
return info
def create(provider, names, opts=None, **kwargs):
'''
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.create(provider, names, **kwargs)
return info
def volume_list(provider):
'''
List block storage volumes
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_list my-nova
'''
client = _get_client()
info = client.extra_action(action='volume_list', provider=provider, names='name')
return info['name']
def volume_delete(provider, names, **kwargs):
'''
Delete volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_delete my-nova myblock
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_delete', **kwargs)
return info
def volume_create(provider, names, **kwargs):
'''
Create volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_create my-nova myblock size=100 voltype=SSD
'''
client = _get_client()
info = client.extra_action(action='volume_create', names=names, provider=provider, **kwargs)
return info
def volume_detach(provider, names, **kwargs):
'''
Detach volume from a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_detach my-nova myblock server_name=myserver
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_detach', **kwargs)
return info
def network_list(provider):
'''
List private networks
CLI Example:
.. code-block:: bash
salt minionname cloud.network_list my-nova
'''
client = _get_client()
return client.extra_action(action='network_list', provider=provider, names='names')
def network_create(provider, names, **kwargs):
'''
Create private network
CLI Example:
.. code-block:: bash
salt minionname cloud.network_create my-nova names=['salt'] cidr='192.168.100.0/24'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='network_create', **kwargs)
def virtual_interface_list(provider, names, **kwargs):
'''
List virtual interfaces on a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_list my-nova names=['salt-master']
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_list', **kwargs)
def virtual_interface_create(provider, names, **kwargs):
'''
Attach private interfaces to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_create my-nova names=['salt-master'] net_name='salt'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_create', **kwargs)
|
saltstack/salt
|
salt/modules/cloud.py
|
network_list
|
python
|
def network_list(provider):
'''
List private networks
CLI Example:
.. code-block:: bash
salt minionname cloud.network_list my-nova
'''
client = _get_client()
return client.extra_action(action='network_list', provider=provider, names='names')
|
List private networks
CLI Example:
.. code-block:: bash
salt minionname cloud.network_list my-nova
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L372-L384
|
[
"def _get_client():\n '''\n Return a cloud client\n '''\n client = salt.cloud.CloudClient(\n os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),\n pillars=copy.deepcopy(__pillar__.get('cloud', {}))\n )\n return client\n",
"def extra_action(self, names, provider, action, **kwargs):\n '''\n Perform actions with block storage devices\n\n Example:\n\n .. code-block:: python\n\n client.extra_action(names=['myblock'], action='volume_create',\n provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000}\n )\n client.extra_action(names=['salt-net'], action='network_create',\n provider='my-nova', kwargs={'cidr': '192.168.100.0/24'}\n )\n '''\n mapper = salt.cloud.Map(self._opts_defaults())\n providers = mapper.map_providers_parallel()\n if provider in providers:\n provider += ':{0}'.format(next(six.iterkeys(providers[provider])))\n else:\n return False\n if isinstance(names, six.string_types):\n names = names.split(',')\n\n ret = {}\n for name in names:\n extra_ = kwargs.copy()\n extra_['name'] = name\n extra_['provider'] = provider\n extra_['profile'] = None\n extra_['action'] = action\n ret[name] = salt.utils.data.simple_types_filter(\n mapper.extras(extra_)\n )\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Salt-specific interface for calling Salt Cloud directly
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
import copy
import salt.utils.data
# Import salt libs
try:
import salt.cloud
HAS_SALTCLOUD = True
except ImportError:
HAS_SALTCLOUD = False
from salt.exceptions import SaltCloudConfigError
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
__func_alias__ = {
'profile_': 'profile'
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if HAS_SALTCLOUD:
return True
return (False, 'The cloud execution module cannot be loaded: only available on non-Windows systems.')
def _get_client():
'''
Return a cloud client
'''
client = salt.cloud.CloudClient(
os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),
pillars=copy.deepcopy(__pillar__.get('cloud', {}))
)
return client
def list_sizes(provider='all'):
'''
List cloud provider sizes for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_sizes my-gce-config
'''
client = _get_client()
sizes = client.list_sizes(provider)
return sizes
def list_images(provider='all'):
'''
List cloud provider images for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_images my-gce-config
'''
client = _get_client()
images = client.list_images(provider)
return images
def list_locations(provider='all'):
'''
List cloud provider locations for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_locations my-gce-config
'''
client = _get_client()
locations = client.list_locations(provider)
return locations
def query(query_type='list_nodes'):
'''
List cloud provider data for all providers
CLI Examples:
.. code-block:: bash
salt minionname cloud.query
salt minionname cloud.query list_nodes_full
salt minionname cloud.query list_nodes_select
'''
client = _get_client()
info = client.query(query_type)
return info
def full_query(query_type='list_nodes_full'):
'''
List all available cloud provider data
CLI Example:
.. code-block:: bash
salt minionname cloud.full_query
'''
return query(query_type=query_type)
def select_query(query_type='list_nodes_select'):
'''
List selected nodes
CLI Example:
.. code-block:: bash
salt minionname cloud.select_query
'''
return query(query_type=query_type)
def has_instance(name, provider=None):
'''
Return true if the instance is found on a provider
CLI Example:
.. code-block:: bash
salt minionname cloud.has_instance myinstance
'''
data = get_instance(name, provider)
if data is None:
return False
return True
def get_instance(name, provider=None):
'''
Return details on an instance.
Similar to the cloud action show_instance
but returns only the instance details.
CLI Example:
.. code-block:: bash
salt minionname cloud.get_instance myinstance
SLS Example:
.. code-block:: bash
{{ salt['cloud.get_instance']('myinstance')['mac_address'] }}
'''
data = action(fun='show_instance', names=[name], provider=provider)
info = salt.utils.data.simple_types_filter(data)
try:
# get the first: [alias][driver][vm_name]
info = next(six.itervalues(next(six.itervalues(next(six.itervalues(info))))))
except AttributeError:
return None
return info
def profile_(profile, names, vm_overrides=None, opts=None, **kwargs):
'''
Spin up an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.profile my-gce-config myinstance
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.profile(profile, names, vm_overrides=vm_overrides, **kwargs)
return info
def map_run(path=None, **kwargs):
'''
Execute a salt cloud map file
Cloud Map data can be retrieved from several sources:
- a local file (provide the path to the file to the 'path' argument)
- a JSON-formatted map directly (provide the appropriately formatted to using the 'map_data' argument)
- the Salt Pillar (provide the map name of under 'pillar:cloud:maps' to the 'map_pillar' argument)
.. note::
Only one of these sources can be read at a time. The options are listed
in their order of precedence.
CLI Examples:
.. code-block:: bash
salt minionname cloud.map_run /path/to/cloud.map
salt minionname cloud.map_run path=/path/to/cloud.map
salt minionname cloud.map_run map_pillar='<map_pillar>'
.. versionchanged:: 2018.3.1
salt minionname cloud.map_run map_data='<actual map data>'
'''
client = _get_client()
info = client.map_run(path, **kwargs)
return info
def destroy(names):
'''
Destroy the named VM(s)
CLI Example:
.. code-block:: bash
salt minionname cloud.destroy myinstance
'''
client = _get_client()
info = client.destroy(names)
return info
def action(
fun=None,
cloudmap=None,
names=None,
provider=None,
instance=None,
**kwargs):
'''
Execute a single action on the given provider/instance
CLI Example:
.. code-block:: bash
salt minionname cloud.action start instance=myinstance
salt minionname cloud.action stop instance=myinstance
salt minionname cloud.action show_image provider=my-ec2-config image=ami-1624987f
'''
client = _get_client()
try:
info = client.action(fun, cloudmap, names, provider, instance, kwargs)
except SaltCloudConfigError as err:
log.error(err)
return None
return info
def create(provider, names, opts=None, **kwargs):
'''
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.create(provider, names, **kwargs)
return info
def volume_list(provider):
'''
List block storage volumes
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_list my-nova
'''
client = _get_client()
info = client.extra_action(action='volume_list', provider=provider, names='name')
return info['name']
def volume_delete(provider, names, **kwargs):
'''
Delete volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_delete my-nova myblock
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_delete', **kwargs)
return info
def volume_create(provider, names, **kwargs):
'''
Create volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_create my-nova myblock size=100 voltype=SSD
'''
client = _get_client()
info = client.extra_action(action='volume_create', names=names, provider=provider, **kwargs)
return info
def volume_attach(provider, names, **kwargs):
'''
Attach volume to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_attach my-nova myblock server_name=myserver device='/dev/xvdf'
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_attach', **kwargs)
return info
def volume_detach(provider, names, **kwargs):
'''
Detach volume from a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_detach my-nova myblock server_name=myserver
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_detach', **kwargs)
return info
def network_create(provider, names, **kwargs):
'''
Create private network
CLI Example:
.. code-block:: bash
salt minionname cloud.network_create my-nova names=['salt'] cidr='192.168.100.0/24'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='network_create', **kwargs)
def virtual_interface_list(provider, names, **kwargs):
'''
List virtual interfaces on a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_list my-nova names=['salt-master']
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_list', **kwargs)
def virtual_interface_create(provider, names, **kwargs):
'''
Attach private interfaces to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_create my-nova names=['salt-master'] net_name='salt'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_create', **kwargs)
|
saltstack/salt
|
salt/modules/cloud.py
|
network_create
|
python
|
def network_create(provider, names, **kwargs):
'''
Create private network
CLI Example:
.. code-block:: bash
salt minionname cloud.network_create my-nova names=['salt'] cidr='192.168.100.0/24'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='network_create', **kwargs)
|
Create private network
CLI Example:
.. code-block:: bash
salt minionname cloud.network_create my-nova names=['salt'] cidr='192.168.100.0/24'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L387-L399
|
[
"def _get_client():\n '''\n Return a cloud client\n '''\n client = salt.cloud.CloudClient(\n os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),\n pillars=copy.deepcopy(__pillar__.get('cloud', {}))\n )\n return client\n",
"def extra_action(self, names, provider, action, **kwargs):\n '''\n Perform actions with block storage devices\n\n Example:\n\n .. code-block:: python\n\n client.extra_action(names=['myblock'], action='volume_create',\n provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000}\n )\n client.extra_action(names=['salt-net'], action='network_create',\n provider='my-nova', kwargs={'cidr': '192.168.100.0/24'}\n )\n '''\n mapper = salt.cloud.Map(self._opts_defaults())\n providers = mapper.map_providers_parallel()\n if provider in providers:\n provider += ':{0}'.format(next(six.iterkeys(providers[provider])))\n else:\n return False\n if isinstance(names, six.string_types):\n names = names.split(',')\n\n ret = {}\n for name in names:\n extra_ = kwargs.copy()\n extra_['name'] = name\n extra_['provider'] = provider\n extra_['profile'] = None\n extra_['action'] = action\n ret[name] = salt.utils.data.simple_types_filter(\n mapper.extras(extra_)\n )\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Salt-specific interface for calling Salt Cloud directly
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
import copy
import salt.utils.data
# Import salt libs
try:
import salt.cloud
HAS_SALTCLOUD = True
except ImportError:
HAS_SALTCLOUD = False
from salt.exceptions import SaltCloudConfigError
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
__func_alias__ = {
'profile_': 'profile'
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if HAS_SALTCLOUD:
return True
return (False, 'The cloud execution module cannot be loaded: only available on non-Windows systems.')
def _get_client():
'''
Return a cloud client
'''
client = salt.cloud.CloudClient(
os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),
pillars=copy.deepcopy(__pillar__.get('cloud', {}))
)
return client
def list_sizes(provider='all'):
'''
List cloud provider sizes for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_sizes my-gce-config
'''
client = _get_client()
sizes = client.list_sizes(provider)
return sizes
def list_images(provider='all'):
'''
List cloud provider images for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_images my-gce-config
'''
client = _get_client()
images = client.list_images(provider)
return images
def list_locations(provider='all'):
'''
List cloud provider locations for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_locations my-gce-config
'''
client = _get_client()
locations = client.list_locations(provider)
return locations
def query(query_type='list_nodes'):
'''
List cloud provider data for all providers
CLI Examples:
.. code-block:: bash
salt minionname cloud.query
salt minionname cloud.query list_nodes_full
salt minionname cloud.query list_nodes_select
'''
client = _get_client()
info = client.query(query_type)
return info
def full_query(query_type='list_nodes_full'):
'''
List all available cloud provider data
CLI Example:
.. code-block:: bash
salt minionname cloud.full_query
'''
return query(query_type=query_type)
def select_query(query_type='list_nodes_select'):
'''
List selected nodes
CLI Example:
.. code-block:: bash
salt minionname cloud.select_query
'''
return query(query_type=query_type)
def has_instance(name, provider=None):
'''
Return true if the instance is found on a provider
CLI Example:
.. code-block:: bash
salt minionname cloud.has_instance myinstance
'''
data = get_instance(name, provider)
if data is None:
return False
return True
def get_instance(name, provider=None):
'''
Return details on an instance.
Similar to the cloud action show_instance
but returns only the instance details.
CLI Example:
.. code-block:: bash
salt minionname cloud.get_instance myinstance
SLS Example:
.. code-block:: bash
{{ salt['cloud.get_instance']('myinstance')['mac_address'] }}
'''
data = action(fun='show_instance', names=[name], provider=provider)
info = salt.utils.data.simple_types_filter(data)
try:
# get the first: [alias][driver][vm_name]
info = next(six.itervalues(next(six.itervalues(next(six.itervalues(info))))))
except AttributeError:
return None
return info
def profile_(profile, names, vm_overrides=None, opts=None, **kwargs):
'''
Spin up an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.profile my-gce-config myinstance
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.profile(profile, names, vm_overrides=vm_overrides, **kwargs)
return info
def map_run(path=None, **kwargs):
'''
Execute a salt cloud map file
Cloud Map data can be retrieved from several sources:
- a local file (provide the path to the file to the 'path' argument)
- a JSON-formatted map directly (provide the appropriately formatted to using the 'map_data' argument)
- the Salt Pillar (provide the map name of under 'pillar:cloud:maps' to the 'map_pillar' argument)
.. note::
Only one of these sources can be read at a time. The options are listed
in their order of precedence.
CLI Examples:
.. code-block:: bash
salt minionname cloud.map_run /path/to/cloud.map
salt minionname cloud.map_run path=/path/to/cloud.map
salt minionname cloud.map_run map_pillar='<map_pillar>'
.. versionchanged:: 2018.3.1
salt minionname cloud.map_run map_data='<actual map data>'
'''
client = _get_client()
info = client.map_run(path, **kwargs)
return info
def destroy(names):
'''
Destroy the named VM(s)
CLI Example:
.. code-block:: bash
salt minionname cloud.destroy myinstance
'''
client = _get_client()
info = client.destroy(names)
return info
def action(
fun=None,
cloudmap=None,
names=None,
provider=None,
instance=None,
**kwargs):
'''
Execute a single action on the given provider/instance
CLI Example:
.. code-block:: bash
salt minionname cloud.action start instance=myinstance
salt minionname cloud.action stop instance=myinstance
salt minionname cloud.action show_image provider=my-ec2-config image=ami-1624987f
'''
client = _get_client()
try:
info = client.action(fun, cloudmap, names, provider, instance, kwargs)
except SaltCloudConfigError as err:
log.error(err)
return None
return info
def create(provider, names, opts=None, **kwargs):
'''
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.create(provider, names, **kwargs)
return info
def volume_list(provider):
'''
List block storage volumes
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_list my-nova
'''
client = _get_client()
info = client.extra_action(action='volume_list', provider=provider, names='name')
return info['name']
def volume_delete(provider, names, **kwargs):
'''
Delete volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_delete my-nova myblock
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_delete', **kwargs)
return info
def volume_create(provider, names, **kwargs):
'''
Create volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_create my-nova myblock size=100 voltype=SSD
'''
client = _get_client()
info = client.extra_action(action='volume_create', names=names, provider=provider, **kwargs)
return info
def volume_attach(provider, names, **kwargs):
'''
Attach volume to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_attach my-nova myblock server_name=myserver device='/dev/xvdf'
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_attach', **kwargs)
return info
def volume_detach(provider, names, **kwargs):
'''
Detach volume from a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_detach my-nova myblock server_name=myserver
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_detach', **kwargs)
return info
def network_list(provider):
'''
List private networks
CLI Example:
.. code-block:: bash
salt minionname cloud.network_list my-nova
'''
client = _get_client()
return client.extra_action(action='network_list', provider=provider, names='names')
def virtual_interface_list(provider, names, **kwargs):
'''
List virtual interfaces on a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_list my-nova names=['salt-master']
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_list', **kwargs)
def virtual_interface_create(provider, names, **kwargs):
'''
Attach private interfaces to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_create my-nova names=['salt-master'] net_name='salt'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_create', **kwargs)
|
saltstack/salt
|
salt/modules/cloud.py
|
virtual_interface_list
|
python
|
def virtual_interface_list(provider, names, **kwargs):
'''
List virtual interfaces on a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_list my-nova names=['salt-master']
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_list', **kwargs)
|
List virtual interfaces on a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_list my-nova names=['salt-master']
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L402-L414
|
[
"def _get_client():\n '''\n Return a cloud client\n '''\n client = salt.cloud.CloudClient(\n os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),\n pillars=copy.deepcopy(__pillar__.get('cloud', {}))\n )\n return client\n",
"def extra_action(self, names, provider, action, **kwargs):\n '''\n Perform actions with block storage devices\n\n Example:\n\n .. code-block:: python\n\n client.extra_action(names=['myblock'], action='volume_create',\n provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000}\n )\n client.extra_action(names=['salt-net'], action='network_create',\n provider='my-nova', kwargs={'cidr': '192.168.100.0/24'}\n )\n '''\n mapper = salt.cloud.Map(self._opts_defaults())\n providers = mapper.map_providers_parallel()\n if provider in providers:\n provider += ':{0}'.format(next(six.iterkeys(providers[provider])))\n else:\n return False\n if isinstance(names, six.string_types):\n names = names.split(',')\n\n ret = {}\n for name in names:\n extra_ = kwargs.copy()\n extra_['name'] = name\n extra_['provider'] = provider\n extra_['profile'] = None\n extra_['action'] = action\n ret[name] = salt.utils.data.simple_types_filter(\n mapper.extras(extra_)\n )\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Salt-specific interface for calling Salt Cloud directly
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
import copy
import salt.utils.data
# Import salt libs
try:
import salt.cloud
HAS_SALTCLOUD = True
except ImportError:
HAS_SALTCLOUD = False
from salt.exceptions import SaltCloudConfigError
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
__func_alias__ = {
'profile_': 'profile'
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if HAS_SALTCLOUD:
return True
return (False, 'The cloud execution module cannot be loaded: only available on non-Windows systems.')
def _get_client():
'''
Return a cloud client
'''
client = salt.cloud.CloudClient(
os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),
pillars=copy.deepcopy(__pillar__.get('cloud', {}))
)
return client
def list_sizes(provider='all'):
'''
List cloud provider sizes for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_sizes my-gce-config
'''
client = _get_client()
sizes = client.list_sizes(provider)
return sizes
def list_images(provider='all'):
'''
List cloud provider images for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_images my-gce-config
'''
client = _get_client()
images = client.list_images(provider)
return images
def list_locations(provider='all'):
'''
List cloud provider locations for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_locations my-gce-config
'''
client = _get_client()
locations = client.list_locations(provider)
return locations
def query(query_type='list_nodes'):
'''
List cloud provider data for all providers
CLI Examples:
.. code-block:: bash
salt minionname cloud.query
salt minionname cloud.query list_nodes_full
salt minionname cloud.query list_nodes_select
'''
client = _get_client()
info = client.query(query_type)
return info
def full_query(query_type='list_nodes_full'):
'''
List all available cloud provider data
CLI Example:
.. code-block:: bash
salt minionname cloud.full_query
'''
return query(query_type=query_type)
def select_query(query_type='list_nodes_select'):
'''
List selected nodes
CLI Example:
.. code-block:: bash
salt minionname cloud.select_query
'''
return query(query_type=query_type)
def has_instance(name, provider=None):
'''
Return true if the instance is found on a provider
CLI Example:
.. code-block:: bash
salt minionname cloud.has_instance myinstance
'''
data = get_instance(name, provider)
if data is None:
return False
return True
def get_instance(name, provider=None):
'''
Return details on an instance.
Similar to the cloud action show_instance
but returns only the instance details.
CLI Example:
.. code-block:: bash
salt minionname cloud.get_instance myinstance
SLS Example:
.. code-block:: bash
{{ salt['cloud.get_instance']('myinstance')['mac_address'] }}
'''
data = action(fun='show_instance', names=[name], provider=provider)
info = salt.utils.data.simple_types_filter(data)
try:
# get the first: [alias][driver][vm_name]
info = next(six.itervalues(next(six.itervalues(next(six.itervalues(info))))))
except AttributeError:
return None
return info
def profile_(profile, names, vm_overrides=None, opts=None, **kwargs):
'''
Spin up an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.profile my-gce-config myinstance
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.profile(profile, names, vm_overrides=vm_overrides, **kwargs)
return info
def map_run(path=None, **kwargs):
'''
Execute a salt cloud map file
Cloud Map data can be retrieved from several sources:
- a local file (provide the path to the file to the 'path' argument)
- a JSON-formatted map directly (provide the appropriately formatted to using the 'map_data' argument)
- the Salt Pillar (provide the map name of under 'pillar:cloud:maps' to the 'map_pillar' argument)
.. note::
Only one of these sources can be read at a time. The options are listed
in their order of precedence.
CLI Examples:
.. code-block:: bash
salt minionname cloud.map_run /path/to/cloud.map
salt minionname cloud.map_run path=/path/to/cloud.map
salt minionname cloud.map_run map_pillar='<map_pillar>'
.. versionchanged:: 2018.3.1
salt minionname cloud.map_run map_data='<actual map data>'
'''
client = _get_client()
info = client.map_run(path, **kwargs)
return info
def destroy(names):
'''
Destroy the named VM(s)
CLI Example:
.. code-block:: bash
salt minionname cloud.destroy myinstance
'''
client = _get_client()
info = client.destroy(names)
return info
def action(
fun=None,
cloudmap=None,
names=None,
provider=None,
instance=None,
**kwargs):
'''
Execute a single action on the given provider/instance
CLI Example:
.. code-block:: bash
salt minionname cloud.action start instance=myinstance
salt minionname cloud.action stop instance=myinstance
salt minionname cloud.action show_image provider=my-ec2-config image=ami-1624987f
'''
client = _get_client()
try:
info = client.action(fun, cloudmap, names, provider, instance, kwargs)
except SaltCloudConfigError as err:
log.error(err)
return None
return info
def create(provider, names, opts=None, **kwargs):
'''
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.create(provider, names, **kwargs)
return info
def volume_list(provider):
'''
List block storage volumes
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_list my-nova
'''
client = _get_client()
info = client.extra_action(action='volume_list', provider=provider, names='name')
return info['name']
def volume_delete(provider, names, **kwargs):
'''
Delete volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_delete my-nova myblock
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_delete', **kwargs)
return info
def volume_create(provider, names, **kwargs):
'''
Create volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_create my-nova myblock size=100 voltype=SSD
'''
client = _get_client()
info = client.extra_action(action='volume_create', names=names, provider=provider, **kwargs)
return info
def volume_attach(provider, names, **kwargs):
'''
Attach volume to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_attach my-nova myblock server_name=myserver device='/dev/xvdf'
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_attach', **kwargs)
return info
def volume_detach(provider, names, **kwargs):
'''
Detach volume from a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_detach my-nova myblock server_name=myserver
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_detach', **kwargs)
return info
def network_list(provider):
'''
List private networks
CLI Example:
.. code-block:: bash
salt minionname cloud.network_list my-nova
'''
client = _get_client()
return client.extra_action(action='network_list', provider=provider, names='names')
def network_create(provider, names, **kwargs):
'''
Create private network
CLI Example:
.. code-block:: bash
salt minionname cloud.network_create my-nova names=['salt'] cidr='192.168.100.0/24'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='network_create', **kwargs)
def virtual_interface_create(provider, names, **kwargs):
'''
Attach private interfaces to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_create my-nova names=['salt-master'] net_name='salt'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_create', **kwargs)
|
saltstack/salt
|
salt/modules/cloud.py
|
virtual_interface_create
|
python
|
def virtual_interface_create(provider, names, **kwargs):
'''
Attach private interfaces to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_create my-nova names=['salt-master'] net_name='salt'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_create', **kwargs)
|
Attach private interfaces to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_create my-nova names=['salt-master'] net_name='salt'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L417-L429
|
[
"def _get_client():\n '''\n Return a cloud client\n '''\n client = salt.cloud.CloudClient(\n os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),\n pillars=copy.deepcopy(__pillar__.get('cloud', {}))\n )\n return client\n",
"def extra_action(self, names, provider, action, **kwargs):\n '''\n Perform actions with block storage devices\n\n Example:\n\n .. code-block:: python\n\n client.extra_action(names=['myblock'], action='volume_create',\n provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000}\n )\n client.extra_action(names=['salt-net'], action='network_create',\n provider='my-nova', kwargs={'cidr': '192.168.100.0/24'}\n )\n '''\n mapper = salt.cloud.Map(self._opts_defaults())\n providers = mapper.map_providers_parallel()\n if provider in providers:\n provider += ':{0}'.format(next(six.iterkeys(providers[provider])))\n else:\n return False\n if isinstance(names, six.string_types):\n names = names.split(',')\n\n ret = {}\n for name in names:\n extra_ = kwargs.copy()\n extra_['name'] = name\n extra_['provider'] = provider\n extra_['profile'] = None\n extra_['action'] = action\n ret[name] = salt.utils.data.simple_types_filter(\n mapper.extras(extra_)\n )\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Salt-specific interface for calling Salt Cloud directly
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import logging
import copy
import salt.utils.data
# Import salt libs
try:
import salt.cloud
HAS_SALTCLOUD = True
except ImportError:
HAS_SALTCLOUD = False
from salt.exceptions import SaltCloudConfigError
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
__func_alias__ = {
'profile_': 'profile'
}
def __virtual__():
'''
Only work on POSIX-like systems
'''
if HAS_SALTCLOUD:
return True
return (False, 'The cloud execution module cannot be loaded: only available on non-Windows systems.')
def _get_client():
'''
Return a cloud client
'''
client = salt.cloud.CloudClient(
os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud'),
pillars=copy.deepcopy(__pillar__.get('cloud', {}))
)
return client
def list_sizes(provider='all'):
'''
List cloud provider sizes for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_sizes my-gce-config
'''
client = _get_client()
sizes = client.list_sizes(provider)
return sizes
def list_images(provider='all'):
'''
List cloud provider images for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_images my-gce-config
'''
client = _get_client()
images = client.list_images(provider)
return images
def list_locations(provider='all'):
'''
List cloud provider locations for the given providers
CLI Example:
.. code-block:: bash
salt minionname cloud.list_locations my-gce-config
'''
client = _get_client()
locations = client.list_locations(provider)
return locations
def query(query_type='list_nodes'):
'''
List cloud provider data for all providers
CLI Examples:
.. code-block:: bash
salt minionname cloud.query
salt minionname cloud.query list_nodes_full
salt minionname cloud.query list_nodes_select
'''
client = _get_client()
info = client.query(query_type)
return info
def full_query(query_type='list_nodes_full'):
'''
List all available cloud provider data
CLI Example:
.. code-block:: bash
salt minionname cloud.full_query
'''
return query(query_type=query_type)
def select_query(query_type='list_nodes_select'):
'''
List selected nodes
CLI Example:
.. code-block:: bash
salt minionname cloud.select_query
'''
return query(query_type=query_type)
def has_instance(name, provider=None):
'''
Return true if the instance is found on a provider
CLI Example:
.. code-block:: bash
salt minionname cloud.has_instance myinstance
'''
data = get_instance(name, provider)
if data is None:
return False
return True
def get_instance(name, provider=None):
'''
Return details on an instance.
Similar to the cloud action show_instance
but returns only the instance details.
CLI Example:
.. code-block:: bash
salt minionname cloud.get_instance myinstance
SLS Example:
.. code-block:: bash
{{ salt['cloud.get_instance']('myinstance')['mac_address'] }}
'''
data = action(fun='show_instance', names=[name], provider=provider)
info = salt.utils.data.simple_types_filter(data)
try:
# get the first: [alias][driver][vm_name]
info = next(six.itervalues(next(six.itervalues(next(six.itervalues(info))))))
except AttributeError:
return None
return info
def profile_(profile, names, vm_overrides=None, opts=None, **kwargs):
'''
Spin up an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.profile my-gce-config myinstance
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.profile(profile, names, vm_overrides=vm_overrides, **kwargs)
return info
def map_run(path=None, **kwargs):
'''
Execute a salt cloud map file
Cloud Map data can be retrieved from several sources:
- a local file (provide the path to the file to the 'path' argument)
- a JSON-formatted map directly (provide the appropriately formatted to using the 'map_data' argument)
- the Salt Pillar (provide the map name of under 'pillar:cloud:maps' to the 'map_pillar' argument)
.. note::
Only one of these sources can be read at a time. The options are listed
in their order of precedence.
CLI Examples:
.. code-block:: bash
salt minionname cloud.map_run /path/to/cloud.map
salt minionname cloud.map_run path=/path/to/cloud.map
salt minionname cloud.map_run map_pillar='<map_pillar>'
.. versionchanged:: 2018.3.1
salt minionname cloud.map_run map_data='<actual map data>'
'''
client = _get_client()
info = client.map_run(path, **kwargs)
return info
def destroy(names):
'''
Destroy the named VM(s)
CLI Example:
.. code-block:: bash
salt minionname cloud.destroy myinstance
'''
client = _get_client()
info = client.destroy(names)
return info
def action(
fun=None,
cloudmap=None,
names=None,
provider=None,
instance=None,
**kwargs):
'''
Execute a single action on the given provider/instance
CLI Example:
.. code-block:: bash
salt minionname cloud.action start instance=myinstance
salt minionname cloud.action stop instance=myinstance
salt minionname cloud.action show_image provider=my-ec2-config image=ami-1624987f
'''
client = _get_client()
try:
info = client.action(fun, cloudmap, names, provider, instance, kwargs)
except SaltCloudConfigError as err:
log.error(err)
return None
return info
def create(provider, names, opts=None, **kwargs):
'''
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt minionname cloud.create my-ec2-config myinstance image=ami-1624987f size='t1.micro' ssh_username=ec2-user securitygroup=default delvol_on_destroy=True
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.create(provider, names, **kwargs)
return info
def volume_list(provider):
'''
List block storage volumes
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_list my-nova
'''
client = _get_client()
info = client.extra_action(action='volume_list', provider=provider, names='name')
return info['name']
def volume_delete(provider, names, **kwargs):
'''
Delete volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_delete my-nova myblock
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_delete', **kwargs)
return info
def volume_create(provider, names, **kwargs):
'''
Create volume
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_create my-nova myblock size=100 voltype=SSD
'''
client = _get_client()
info = client.extra_action(action='volume_create', names=names, provider=provider, **kwargs)
return info
def volume_attach(provider, names, **kwargs):
'''
Attach volume to a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_attach my-nova myblock server_name=myserver device='/dev/xvdf'
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_attach', **kwargs)
return info
def volume_detach(provider, names, **kwargs):
'''
Detach volume from a server
CLI Example:
.. code-block:: bash
salt minionname cloud.volume_detach my-nova myblock server_name=myserver
'''
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_detach', **kwargs)
return info
def network_list(provider):
'''
List private networks
CLI Example:
.. code-block:: bash
salt minionname cloud.network_list my-nova
'''
client = _get_client()
return client.extra_action(action='network_list', provider=provider, names='names')
def network_create(provider, names, **kwargs):
'''
Create private network
CLI Example:
.. code-block:: bash
salt minionname cloud.network_create my-nova names=['salt'] cidr='192.168.100.0/24'
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='network_create', **kwargs)
def virtual_interface_list(provider, names, **kwargs):
'''
List virtual interfaces on a server
CLI Example:
.. code-block:: bash
salt minionname cloud.virtual_interface_list my-nova names=['salt-master']
'''
client = _get_client()
return client.extra_action(provider=provider, names=names, action='virtual_interface_list', **kwargs)
|
saltstack/salt
|
salt/modules/netbsd_sysctl.py
|
show
|
python
|
def show(config_file=False):
'''
Return a list of sysctl parameters for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.show
'''
roots = (
'kern',
'vm',
'vfs',
'net',
'hw',
'machdep',
'user',
'ddb',
'proc',
'emul',
'security',
'init'
)
cmd = 'sysctl -ae'
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace')
comps = ['']
for line in out.splitlines():
if any([line.startswith('{0}.'.format(root)) for root in roots]):
comps = re.split('[=:]', line, 1)
ret[comps[0]] = comps[1]
elif comps[0]:
ret[comps[0]] += '{0}\n'.format(line)
else:
continue
return ret
|
Return a list of sysctl parameters for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.show
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbsd_sysctl.py#L30-L66
| null |
# -*- coding: utf-8 -*-
'''
Module for viewing and modifying sysctl parameters
'''
from __future__ import absolute_import, print_function, unicode_literals
import os
import re
# Import salt libs
from salt.ext import six
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
# Define the module's virtual name
__virtualname__ = 'sysctl'
def __virtual__():
'''
Only run on NetBSD systems
'''
if __grains__['os'] == 'NetBSD':
return __virtualname__
return (False, 'The netbsd_sysctl execution module failed to load: '
'only available on NetBSD.')
def get(name):
'''
Return a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.get hw.physmem
'''
cmd = 'sysctl -n {0}'.format(name)
out = __salt__['cmd.run'](cmd, python_shell=False)
return out
def assign(name, value):
'''
Assign a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.assign net.inet.icmp.icmplim 50
'''
ret = {}
cmd = 'sysctl -w {0}="{1}"'.format(name, value)
data = __salt__['cmd.run_all'](cmd, python_shell=False)
if data['retcode'] != 0:
raise CommandExecutionError('sysctl failed: {0}'.format(
data['stderr']))
new_name, new_value = data['stdout'].split(':', 1)
ret[new_name] = new_value.split(' -> ')[-1]
return ret
def persist(name, value, config='/etc/sysctl.conf'):
'''
Assign and persist a simple sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.inet.icmp.icmplim 50
'''
nlines = []
edited = False
value = six.text_type(value)
# create /etc/sysctl.conf if not present
if not os.path.isfile(config):
try:
with salt.utils.files.fopen(config, 'w+'):
pass
except (IOError, OSError):
msg = 'Could not create {0}'
raise CommandExecutionError(msg.format(config))
with salt.utils.files.fopen(config, 'r') as ifile:
for line in ifile:
line = salt.utils.stringutils.to_unicode(line)
m = re.match(r'{0}(\??=)'.format(name), line)
if not m:
nlines.append(line)
continue
else:
key, rest = line.split('=', 1)
if rest.startswith('"'):
_, rest_v, rest = rest.split('"', 2)
elif rest.startswith('\''):
_, rest_v, rest = rest.split('\'', 2)
else:
rest_v = rest.split()[0]
rest = rest[len(rest_v):]
if rest_v == value:
return 'Already set'
new_line = '{0}{1}{2}{3}'.format(name, m.group(1), value, rest)
nlines.append(new_line)
edited = True
if not edited:
newline = '{0}={1}'.format(name, value)
nlines.append("{0}\n".format(newline))
with salt.utils.files.fopen(config, 'wb') as ofile:
ofile.writelines(
salt.utils.data.encode(nlines)
)
assign(name, value)
return 'Updated'
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/modules/netbsd_sysctl.py
|
get
|
python
|
def get(name):
'''
Return a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.get hw.physmem
'''
cmd = 'sysctl -n {0}'.format(name)
out = __salt__['cmd.run'](cmd, python_shell=False)
return out
|
Return a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.get hw.physmem
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbsd_sysctl.py#L69-L81
| null |
# -*- coding: utf-8 -*-
'''
Module for viewing and modifying sysctl parameters
'''
from __future__ import absolute_import, print_function, unicode_literals
import os
import re
# Import salt libs
from salt.ext import six
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
# Define the module's virtual name
__virtualname__ = 'sysctl'
def __virtual__():
'''
Only run on NetBSD systems
'''
if __grains__['os'] == 'NetBSD':
return __virtualname__
return (False, 'The netbsd_sysctl execution module failed to load: '
'only available on NetBSD.')
def show(config_file=False):
'''
Return a list of sysctl parameters for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.show
'''
roots = (
'kern',
'vm',
'vfs',
'net',
'hw',
'machdep',
'user',
'ddb',
'proc',
'emul',
'security',
'init'
)
cmd = 'sysctl -ae'
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace')
comps = ['']
for line in out.splitlines():
if any([line.startswith('{0}.'.format(root)) for root in roots]):
comps = re.split('[=:]', line, 1)
ret[comps[0]] = comps[1]
elif comps[0]:
ret[comps[0]] += '{0}\n'.format(line)
else:
continue
return ret
def assign(name, value):
'''
Assign a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.assign net.inet.icmp.icmplim 50
'''
ret = {}
cmd = 'sysctl -w {0}="{1}"'.format(name, value)
data = __salt__['cmd.run_all'](cmd, python_shell=False)
if data['retcode'] != 0:
raise CommandExecutionError('sysctl failed: {0}'.format(
data['stderr']))
new_name, new_value = data['stdout'].split(':', 1)
ret[new_name] = new_value.split(' -> ')[-1]
return ret
def persist(name, value, config='/etc/sysctl.conf'):
'''
Assign and persist a simple sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.inet.icmp.icmplim 50
'''
nlines = []
edited = False
value = six.text_type(value)
# create /etc/sysctl.conf if not present
if not os.path.isfile(config):
try:
with salt.utils.files.fopen(config, 'w+'):
pass
except (IOError, OSError):
msg = 'Could not create {0}'
raise CommandExecutionError(msg.format(config))
with salt.utils.files.fopen(config, 'r') as ifile:
for line in ifile:
line = salt.utils.stringutils.to_unicode(line)
m = re.match(r'{0}(\??=)'.format(name), line)
if not m:
nlines.append(line)
continue
else:
key, rest = line.split('=', 1)
if rest.startswith('"'):
_, rest_v, rest = rest.split('"', 2)
elif rest.startswith('\''):
_, rest_v, rest = rest.split('\'', 2)
else:
rest_v = rest.split()[0]
rest = rest[len(rest_v):]
if rest_v == value:
return 'Already set'
new_line = '{0}{1}{2}{3}'.format(name, m.group(1), value, rest)
nlines.append(new_line)
edited = True
if not edited:
newline = '{0}={1}'.format(name, value)
nlines.append("{0}\n".format(newline))
with salt.utils.files.fopen(config, 'wb') as ofile:
ofile.writelines(
salt.utils.data.encode(nlines)
)
assign(name, value)
return 'Updated'
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/modules/netbsd_sysctl.py
|
persist
|
python
|
def persist(name, value, config='/etc/sysctl.conf'):
'''
Assign and persist a simple sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.inet.icmp.icmplim 50
'''
nlines = []
edited = False
value = six.text_type(value)
# create /etc/sysctl.conf if not present
if not os.path.isfile(config):
try:
with salt.utils.files.fopen(config, 'w+'):
pass
except (IOError, OSError):
msg = 'Could not create {0}'
raise CommandExecutionError(msg.format(config))
with salt.utils.files.fopen(config, 'r') as ifile:
for line in ifile:
line = salt.utils.stringutils.to_unicode(line)
m = re.match(r'{0}(\??=)'.format(name), line)
if not m:
nlines.append(line)
continue
else:
key, rest = line.split('=', 1)
if rest.startswith('"'):
_, rest_v, rest = rest.split('"', 2)
elif rest.startswith('\''):
_, rest_v, rest = rest.split('\'', 2)
else:
rest_v = rest.split()[0]
rest = rest[len(rest_v):]
if rest_v == value:
return 'Already set'
new_line = '{0}{1}{2}{3}'.format(name, m.group(1), value, rest)
nlines.append(new_line)
edited = True
if not edited:
newline = '{0}={1}'.format(name, value)
nlines.append("{0}\n".format(newline))
with salt.utils.files.fopen(config, 'wb') as ofile:
ofile.writelines(
salt.utils.data.encode(nlines)
)
assign(name, value)
return 'Updated'
|
Assign and persist a simple sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.inet.icmp.icmplim 50
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbsd_sysctl.py#L106-L162
|
[
"def encode(data, encoding=None, errors='strict', keep=False,\n preserve_dict_class=False, preserve_tuples=False):\n '''\n Generic function which will encode whichever type is passed, if necessary\n\n If `strict` is True, and `keep` is False, and we fail to encode, a\n UnicodeEncodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where encoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs.\n '''\n if isinstance(data, Mapping):\n return encode_dict(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n elif isinstance(data, list):\n return encode_list(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n elif isinstance(data, tuple):\n return encode_tuple(data, encoding, errors, keep, preserve_dict_class) \\\n if preserve_tuples \\\n else encode_list(data, encoding, errors, keep,\n preserve_dict_class, preserve_tuples)\n else:\n try:\n return salt.utils.stringutils.to_bytes(data, encoding, errors)\n except TypeError:\n # to_bytes raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply\n # means we are going to leave the value as-is.\n pass\n except UnicodeEncodeError:\n if not keep:\n raise\n return data\n",
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n",
"def assign(name, value):\n '''\n Assign a single sysctl parameter for this minion\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' sysctl.assign net.inet.icmp.icmplim 50\n '''\n ret = {}\n cmd = 'sysctl -w {0}=\"{1}\"'.format(name, value)\n data = __salt__['cmd.run_all'](cmd, python_shell=False)\n\n if data['retcode'] != 0:\n raise CommandExecutionError('sysctl failed: {0}'.format(\n data['stderr']))\n new_name, new_value = data['stdout'].split(':', 1)\n ret[new_name] = new_value.split(' -> ')[-1]\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Module for viewing and modifying sysctl parameters
'''
from __future__ import absolute_import, print_function, unicode_literals
import os
import re
# Import salt libs
from salt.ext import six
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
# Define the module's virtual name
__virtualname__ = 'sysctl'
def __virtual__():
'''
Only run on NetBSD systems
'''
if __grains__['os'] == 'NetBSD':
return __virtualname__
return (False, 'The netbsd_sysctl execution module failed to load: '
'only available on NetBSD.')
def show(config_file=False):
'''
Return a list of sysctl parameters for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.show
'''
roots = (
'kern',
'vm',
'vfs',
'net',
'hw',
'machdep',
'user',
'ddb',
'proc',
'emul',
'security',
'init'
)
cmd = 'sysctl -ae'
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace')
comps = ['']
for line in out.splitlines():
if any([line.startswith('{0}.'.format(root)) for root in roots]):
comps = re.split('[=:]', line, 1)
ret[comps[0]] = comps[1]
elif comps[0]:
ret[comps[0]] += '{0}\n'.format(line)
else:
continue
return ret
def get(name):
'''
Return a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.get hw.physmem
'''
cmd = 'sysctl -n {0}'.format(name)
out = __salt__['cmd.run'](cmd, python_shell=False)
return out
def assign(name, value):
'''
Assign a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.assign net.inet.icmp.icmplim 50
'''
ret = {}
cmd = 'sysctl -w {0}="{1}"'.format(name, value)
data = __salt__['cmd.run_all'](cmd, python_shell=False)
if data['retcode'] != 0:
raise CommandExecutionError('sysctl failed: {0}'.format(
data['stderr']))
new_name, new_value = data['stdout'].split(':', 1)
ret[new_name] = new_value.split(' -> ')[-1]
return ret
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
saltstack/salt
|
salt/states/pushover.py
|
post_message
|
python
|
def post_message(name,
user=None,
device=None,
message=None,
title=None,
priority=None,
expire=None,
retry=None,
sound=None,
api_version=1,
token=None):
'''
Send a message to a PushOver channel.
.. code-block:: yaml
pushover-message:
pushover.post_message:
- user: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- title: Salt Returner
- device: phone
- priority: -1
- expire: 3600
- retry: 5
The following parameters are required:
name
The unique name for this event.
user
The user or group of users to send the message to. Must be ID of user, not name
or email address.
message
The message that is to be sent to the PushOver channel.
The following parameters are optional:
title
The title to use for the message.
device
The device for the user to send the message to.
priority
The priority for the message.
expire
The message should expire after specified amount of seconds.
retry
The message should be resent this many times.
token
The token for PushOver to use for authentication,
if not specified in the configuration options of master or minion.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'The following message is to be sent to PushOver: {0}'.format(message)
ret['result'] = None
return ret
if not user:
ret['comment'] = 'PushOver user is missing: {0}'.format(user)
return ret
if not message:
ret['comment'] = 'PushOver message is missing: {0}'.format(message)
return ret
result = __salt__['pushover.post_message'](
user=user,
message=message,
title=title,
device=device,
priority=priority,
expire=expire,
retry=retry,
token=token,
)
if result:
ret['result'] = True
ret['comment'] = 'Sent message: {0}'.format(name)
else:
ret['comment'] = 'Failed to send message: {0}'.format(name)
return ret
|
Send a message to a PushOver channel.
.. code-block:: yaml
pushover-message:
pushover.post_message:
- user: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- title: Salt Returner
- device: phone
- priority: -1
- expire: 3600
- retry: 5
The following parameters are required:
name
The unique name for this event.
user
The user or group of users to send the message to. Must be ID of user, not name
or email address.
message
The message that is to be sent to the PushOver channel.
The following parameters are optional:
title
The title to use for the message.
device
The device for the user to send the message to.
priority
The priority for the message.
expire
The message should expire after specified amount of seconds.
retry
The message should be resent this many times.
token
The token for PushOver to use for authentication,
if not specified in the configuration options of master or minion.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pushover.py#L42-L137
| null |
# -*- coding: utf-8 -*-
'''
Send a message to PushOver
==========================
This state is useful for sending messages to PushOver during state runs.
.. versionadded:: 2015.5.0
.. code-block:: yaml
pushover-message:
pushover.post_message:
- user: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- title: Salt Returner
- device: phone
- priority: -1
- expire: 3600
- retry: 5
- message: 'This state was executed successfully.'
The api key can be specified in the master or minion configuration like below:
.. code-block:: yaml
pushover:
token: peWcBiMOS9HrZG15peWcBiMOS9HrZG15
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
def __virtual__():
'''
Only load if the pushover module is available in __salt__
'''
return 'pushover' if 'pushover.post_message' in __salt__ else False
|
saltstack/salt
|
salt/modules/dig.py
|
check_ip
|
python
|
def check_ip(addr):
'''
Check if address is a valid IP. returns True if valid, otherwise False.
CLI Example:
.. code-block:: bash
salt ns1 dig.check_ip 127.0.0.1
salt ns1 dig.check_ip 1111:2222:3333:4444:5555:6666:7777:8888
'''
try:
addr = addr.rsplit('/', 1)
except AttributeError:
# Non-string passed
return False
if salt.utils.network.is_ipv4(addr[0]):
try:
if 1 <= int(addr[1]) <= 32:
return True
except ValueError:
# Non-int subnet notation
return False
except IndexError:
# No subnet notation used (i.e. just an IPv4 address)
return True
if salt.utils.network.is_ipv6(addr[0]):
try:
if 8 <= int(addr[1]) <= 128:
return True
except ValueError:
# Non-int subnet notation
return False
except IndexError:
# No subnet notation used (i.e. just an IPv4 address)
return True
return False
|
Check if address is a valid IP. returns True if valid, otherwise False.
CLI Example:
.. code-block:: bash
salt ns1 dig.check_ip 127.0.0.1
salt ns1 dig.check_ip 1111:2222:3333:4444:5555:6666:7777:8888
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dig.py#L32-L72
|
[
"def is_ipv4(ip):\n '''\n Returns a bool telling if the value passed to it was a valid IPv4 address\n '''\n try:\n return ipaddress.ip_address(ip).version == 4\n except ValueError:\n return False\n",
"def is_ipv6(ip):\n '''\n Returns a bool telling if the value passed to it was a valid IPv6 address\n '''\n try:\n return ipaddress.ip_address(ip).version == 6\n except ValueError:\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Compendium of generic DNS utilities.
The 'dig' command line tool must be installed in order to use this module.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
import salt.utils.network
import salt.utils.path
from salt.ext import six
# Import python libs
import logging
import re
log = logging.getLogger(__name__)
__virtualname__ = 'dig'
def __virtual__():
'''
Only load module if dig binary is present
'''
if salt.utils.path.which('dig'):
return __virtualname__
return (False, 'The dig execution module cannot be loaded: '
'the dig binary is not in the path.')
def A(host, nameserver=None):
'''
Return the A record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.A www.google.com
'''
dig = ['dig', '+short', six.text_type(host), 'A']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
# make sure all entries are IPs
return [x for x in cmd['stdout'].split('\n') if check_ip(x)]
def AAAA(host, nameserver=None):
'''
Return the AAAA record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.AAAA www.google.com
'''
dig = ['dig', '+short', six.text_type(host), 'AAAA']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
# make sure all entries are IPs
return [x for x in cmd['stdout'].split('\n') if check_ip(x)]
def NS(domain, resolve=True, nameserver=None):
'''
Return a list of IPs of the nameservers for ``domain``
If ``resolve`` is False, don't resolve names.
CLI Example:
.. code-block:: bash
salt ns1 dig.NS google.com
'''
dig = ['dig', '+short', six.text_type(domain), 'NS']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
if resolve:
ret = []
for ns_host in cmd['stdout'].split('\n'):
for ip_addr in A(ns_host, nameserver):
ret.append(ip_addr)
return ret
return cmd['stdout'].split('\n')
def SPF(domain, record='SPF', nameserver=None):
'''
Return the allowed IPv4 ranges in the SPF record for ``domain``.
If record is ``SPF`` and the SPF record is empty, the TXT record will be
searched automatically. If you know the domain uses TXT and not SPF,
specifying that will save a lookup.
CLI Example:
.. code-block:: bash
salt ns1 dig.SPF google.com
'''
spf_re = re.compile(r'(?:\+|~)?(ip[46]|include):(.+)')
cmd = ['dig', '+short', six.text_type(domain), record]
if nameserver is not None:
cmd.append('@{0}'.format(nameserver))
result = __salt__['cmd.run_all'](cmd, python_shell=False)
# In this case, 0 is not the same as False
if result['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
result['retcode']
)
return []
if result['stdout'] == '' and record == 'SPF':
# empty string is successful query, but nothing to return. So, try TXT
# record.
return SPF(domain, 'TXT', nameserver)
sections = re.sub('"', '', result['stdout']).split()
if not sections or sections[0] != 'v=spf1':
return []
if sections[1].startswith('redirect='):
# Run a lookup on the part after 'redirect=' (9 chars)
return SPF(sections[1][9:], 'SPF', nameserver)
ret = []
for section in sections[1:]:
try:
mechanism, address = spf_re.match(section).groups()
except AttributeError:
# Regex was not matched
continue
if mechanism == 'include':
ret.extend(SPF(address, 'SPF', nameserver))
elif mechanism in ('ip4', 'ip6') and check_ip(address):
ret.append(address)
return ret
def MX(domain, resolve=False, nameserver=None):
'''
Return a list of lists for the MX of ``domain``.
If the ``resolve`` argument is True, resolve IPs for the servers.
It's limited to one IP, because although in practice it's very rarely a
round robin, it is an acceptable configuration and pulling just one IP lets
the data be similar to the non-resolved version. If you think an MX has
multiple IPs, don't use the resolver here, resolve them in a separate step.
CLI Example:
.. code-block:: bash
salt ns1 dig.MX google.com
'''
dig = ['dig', '+short', six.text_type(domain), 'MX']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
stdout = [x.split() for x in cmd['stdout'].split('\n')]
if resolve:
return [
(lambda x: [x[0], A(x[1], nameserver)[0]])(x) for x in stdout
]
return stdout
def TXT(host, nameserver=None):
'''
Return the TXT record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.TXT google.com
'''
dig = ['dig', '+short', six.text_type(host), 'TXT']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
return [i for i in cmd['stdout'].split('\n')]
# Let lowercase work, since that is the convention for Salt functions
a = A
aaaa = AAAA
ns = NS
spf = SPF
mx = MX
|
saltstack/salt
|
salt/modules/dig.py
|
AAAA
|
python
|
def AAAA(host, nameserver=None):
'''
Return the AAAA record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.AAAA www.google.com
'''
dig = ['dig', '+short', six.text_type(host), 'AAAA']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
# make sure all entries are IPs
return [x for x in cmd['stdout'].split('\n') if check_ip(x)]
|
Return the AAAA record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.AAAA www.google.com
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dig.py#L105-L132
| null |
# -*- coding: utf-8 -*-
'''
Compendium of generic DNS utilities.
The 'dig' command line tool must be installed in order to use this module.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
import salt.utils.network
import salt.utils.path
from salt.ext import six
# Import python libs
import logging
import re
log = logging.getLogger(__name__)
__virtualname__ = 'dig'
def __virtual__():
'''
Only load module if dig binary is present
'''
if salt.utils.path.which('dig'):
return __virtualname__
return (False, 'The dig execution module cannot be loaded: '
'the dig binary is not in the path.')
def check_ip(addr):
'''
Check if address is a valid IP. returns True if valid, otherwise False.
CLI Example:
.. code-block:: bash
salt ns1 dig.check_ip 127.0.0.1
salt ns1 dig.check_ip 1111:2222:3333:4444:5555:6666:7777:8888
'''
try:
addr = addr.rsplit('/', 1)
except AttributeError:
# Non-string passed
return False
if salt.utils.network.is_ipv4(addr[0]):
try:
if 1 <= int(addr[1]) <= 32:
return True
except ValueError:
# Non-int subnet notation
return False
except IndexError:
# No subnet notation used (i.e. just an IPv4 address)
return True
if salt.utils.network.is_ipv6(addr[0]):
try:
if 8 <= int(addr[1]) <= 128:
return True
except ValueError:
# Non-int subnet notation
return False
except IndexError:
# No subnet notation used (i.e. just an IPv4 address)
return True
return False
def A(host, nameserver=None):
'''
Return the A record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.A www.google.com
'''
dig = ['dig', '+short', six.text_type(host), 'A']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
# make sure all entries are IPs
return [x for x in cmd['stdout'].split('\n') if check_ip(x)]
def NS(domain, resolve=True, nameserver=None):
'''
Return a list of IPs of the nameservers for ``domain``
If ``resolve`` is False, don't resolve names.
CLI Example:
.. code-block:: bash
salt ns1 dig.NS google.com
'''
dig = ['dig', '+short', six.text_type(domain), 'NS']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
if resolve:
ret = []
for ns_host in cmd['stdout'].split('\n'):
for ip_addr in A(ns_host, nameserver):
ret.append(ip_addr)
return ret
return cmd['stdout'].split('\n')
def SPF(domain, record='SPF', nameserver=None):
'''
Return the allowed IPv4 ranges in the SPF record for ``domain``.
If record is ``SPF`` and the SPF record is empty, the TXT record will be
searched automatically. If you know the domain uses TXT and not SPF,
specifying that will save a lookup.
CLI Example:
.. code-block:: bash
salt ns1 dig.SPF google.com
'''
spf_re = re.compile(r'(?:\+|~)?(ip[46]|include):(.+)')
cmd = ['dig', '+short', six.text_type(domain), record]
if nameserver is not None:
cmd.append('@{0}'.format(nameserver))
result = __salt__['cmd.run_all'](cmd, python_shell=False)
# In this case, 0 is not the same as False
if result['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
result['retcode']
)
return []
if result['stdout'] == '' and record == 'SPF':
# empty string is successful query, but nothing to return. So, try TXT
# record.
return SPF(domain, 'TXT', nameserver)
sections = re.sub('"', '', result['stdout']).split()
if not sections or sections[0] != 'v=spf1':
return []
if sections[1].startswith('redirect='):
# Run a lookup on the part after 'redirect=' (9 chars)
return SPF(sections[1][9:], 'SPF', nameserver)
ret = []
for section in sections[1:]:
try:
mechanism, address = spf_re.match(section).groups()
except AttributeError:
# Regex was not matched
continue
if mechanism == 'include':
ret.extend(SPF(address, 'SPF', nameserver))
elif mechanism in ('ip4', 'ip6') and check_ip(address):
ret.append(address)
return ret
def MX(domain, resolve=False, nameserver=None):
'''
Return a list of lists for the MX of ``domain``.
If the ``resolve`` argument is True, resolve IPs for the servers.
It's limited to one IP, because although in practice it's very rarely a
round robin, it is an acceptable configuration and pulling just one IP lets
the data be similar to the non-resolved version. If you think an MX has
multiple IPs, don't use the resolver here, resolve them in a separate step.
CLI Example:
.. code-block:: bash
salt ns1 dig.MX google.com
'''
dig = ['dig', '+short', six.text_type(domain), 'MX']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
stdout = [x.split() for x in cmd['stdout'].split('\n')]
if resolve:
return [
(lambda x: [x[0], A(x[1], nameserver)[0]])(x) for x in stdout
]
return stdout
def TXT(host, nameserver=None):
'''
Return the TXT record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.TXT google.com
'''
dig = ['dig', '+short', six.text_type(host), 'TXT']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
return [i for i in cmd['stdout'].split('\n')]
# Let lowercase work, since that is the convention for Salt functions
a = A
aaaa = AAAA
ns = NS
spf = SPF
mx = MX
|
saltstack/salt
|
salt/modules/dig.py
|
NS
|
python
|
def NS(domain, resolve=True, nameserver=None):
'''
Return a list of IPs of the nameservers for ``domain``
If ``resolve`` is False, don't resolve names.
CLI Example:
.. code-block:: bash
salt ns1 dig.NS google.com
'''
dig = ['dig', '+short', six.text_type(domain), 'NS']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
if resolve:
ret = []
for ns_host in cmd['stdout'].split('\n'):
for ip_addr in A(ns_host, nameserver):
ret.append(ip_addr)
return ret
return cmd['stdout'].split('\n')
|
Return a list of IPs of the nameservers for ``domain``
If ``resolve`` is False, don't resolve names.
CLI Example:
.. code-block:: bash
salt ns1 dig.NS google.com
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dig.py#L135-L168
|
[
"def A(host, nameserver=None):\n '''\n Return the A record for ``host``.\n\n Always returns a list.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt ns1 dig.A www.google.com\n '''\n dig = ['dig', '+short', six.text_type(host), 'A']\n\n if nameserver is not None:\n dig.append('@{0}'.format(nameserver))\n\n cmd = __salt__['cmd.run_all'](dig, python_shell=False)\n # In this case, 0 is not the same as False\n if cmd['retcode'] != 0:\n log.warning(\n 'dig returned exit code \\'%s\\'. Returning empty list as fallback.',\n cmd['retcode']\n )\n return []\n\n # make sure all entries are IPs\n return [x for x in cmd['stdout'].split('\\n') if check_ip(x)]\n"
] |
# -*- coding: utf-8 -*-
'''
Compendium of generic DNS utilities.
The 'dig' command line tool must be installed in order to use this module.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
import salt.utils.network
import salt.utils.path
from salt.ext import six
# Import python libs
import logging
import re
log = logging.getLogger(__name__)
__virtualname__ = 'dig'
def __virtual__():
'''
Only load module if dig binary is present
'''
if salt.utils.path.which('dig'):
return __virtualname__
return (False, 'The dig execution module cannot be loaded: '
'the dig binary is not in the path.')
def check_ip(addr):
'''
Check if address is a valid IP. returns True if valid, otherwise False.
CLI Example:
.. code-block:: bash
salt ns1 dig.check_ip 127.0.0.1
salt ns1 dig.check_ip 1111:2222:3333:4444:5555:6666:7777:8888
'''
try:
addr = addr.rsplit('/', 1)
except AttributeError:
# Non-string passed
return False
if salt.utils.network.is_ipv4(addr[0]):
try:
if 1 <= int(addr[1]) <= 32:
return True
except ValueError:
# Non-int subnet notation
return False
except IndexError:
# No subnet notation used (i.e. just an IPv4 address)
return True
if salt.utils.network.is_ipv6(addr[0]):
try:
if 8 <= int(addr[1]) <= 128:
return True
except ValueError:
# Non-int subnet notation
return False
except IndexError:
# No subnet notation used (i.e. just an IPv4 address)
return True
return False
def A(host, nameserver=None):
'''
Return the A record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.A www.google.com
'''
dig = ['dig', '+short', six.text_type(host), 'A']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
# make sure all entries are IPs
return [x for x in cmd['stdout'].split('\n') if check_ip(x)]
def AAAA(host, nameserver=None):
'''
Return the AAAA record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.AAAA www.google.com
'''
dig = ['dig', '+short', six.text_type(host), 'AAAA']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
# make sure all entries are IPs
return [x for x in cmd['stdout'].split('\n') if check_ip(x)]
def SPF(domain, record='SPF', nameserver=None):
'''
Return the allowed IPv4 ranges in the SPF record for ``domain``.
If record is ``SPF`` and the SPF record is empty, the TXT record will be
searched automatically. If you know the domain uses TXT and not SPF,
specifying that will save a lookup.
CLI Example:
.. code-block:: bash
salt ns1 dig.SPF google.com
'''
spf_re = re.compile(r'(?:\+|~)?(ip[46]|include):(.+)')
cmd = ['dig', '+short', six.text_type(domain), record]
if nameserver is not None:
cmd.append('@{0}'.format(nameserver))
result = __salt__['cmd.run_all'](cmd, python_shell=False)
# In this case, 0 is not the same as False
if result['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
result['retcode']
)
return []
if result['stdout'] == '' and record == 'SPF':
# empty string is successful query, but nothing to return. So, try TXT
# record.
return SPF(domain, 'TXT', nameserver)
sections = re.sub('"', '', result['stdout']).split()
if not sections or sections[0] != 'v=spf1':
return []
if sections[1].startswith('redirect='):
# Run a lookup on the part after 'redirect=' (9 chars)
return SPF(sections[1][9:], 'SPF', nameserver)
ret = []
for section in sections[1:]:
try:
mechanism, address = spf_re.match(section).groups()
except AttributeError:
# Regex was not matched
continue
if mechanism == 'include':
ret.extend(SPF(address, 'SPF', nameserver))
elif mechanism in ('ip4', 'ip6') and check_ip(address):
ret.append(address)
return ret
def MX(domain, resolve=False, nameserver=None):
'''
Return a list of lists for the MX of ``domain``.
If the ``resolve`` argument is True, resolve IPs for the servers.
It's limited to one IP, because although in practice it's very rarely a
round robin, it is an acceptable configuration and pulling just one IP lets
the data be similar to the non-resolved version. If you think an MX has
multiple IPs, don't use the resolver here, resolve them in a separate step.
CLI Example:
.. code-block:: bash
salt ns1 dig.MX google.com
'''
dig = ['dig', '+short', six.text_type(domain), 'MX']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
stdout = [x.split() for x in cmd['stdout'].split('\n')]
if resolve:
return [
(lambda x: [x[0], A(x[1], nameserver)[0]])(x) for x in stdout
]
return stdout
def TXT(host, nameserver=None):
'''
Return the TXT record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.TXT google.com
'''
dig = ['dig', '+short', six.text_type(host), 'TXT']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
return [i for i in cmd['stdout'].split('\n')]
# Let lowercase work, since that is the convention for Salt functions
a = A
aaaa = AAAA
ns = NS
spf = SPF
mx = MX
|
saltstack/salt
|
salt/modules/dig.py
|
SPF
|
python
|
def SPF(domain, record='SPF', nameserver=None):
'''
Return the allowed IPv4 ranges in the SPF record for ``domain``.
If record is ``SPF`` and the SPF record is empty, the TXT record will be
searched automatically. If you know the domain uses TXT and not SPF,
specifying that will save a lookup.
CLI Example:
.. code-block:: bash
salt ns1 dig.SPF google.com
'''
spf_re = re.compile(r'(?:\+|~)?(ip[46]|include):(.+)')
cmd = ['dig', '+short', six.text_type(domain), record]
if nameserver is not None:
cmd.append('@{0}'.format(nameserver))
result = __salt__['cmd.run_all'](cmd, python_shell=False)
# In this case, 0 is not the same as False
if result['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
result['retcode']
)
return []
if result['stdout'] == '' and record == 'SPF':
# empty string is successful query, but nothing to return. So, try TXT
# record.
return SPF(domain, 'TXT', nameserver)
sections = re.sub('"', '', result['stdout']).split()
if not sections or sections[0] != 'v=spf1':
return []
if sections[1].startswith('redirect='):
# Run a lookup on the part after 'redirect=' (9 chars)
return SPF(sections[1][9:], 'SPF', nameserver)
ret = []
for section in sections[1:]:
try:
mechanism, address = spf_re.match(section).groups()
except AttributeError:
# Regex was not matched
continue
if mechanism == 'include':
ret.extend(SPF(address, 'SPF', nameserver))
elif mechanism in ('ip4', 'ip6') and check_ip(address):
ret.append(address)
return ret
|
Return the allowed IPv4 ranges in the SPF record for ``domain``.
If record is ``SPF`` and the SPF record is empty, the TXT record will be
searched automatically. If you know the domain uses TXT and not SPF,
specifying that will save a lookup.
CLI Example:
.. code-block:: bash
salt ns1 dig.SPF google.com
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dig.py#L171-L223
|
[
"def check_ip(addr):\n '''\n Check if address is a valid IP. returns True if valid, otherwise False.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt ns1 dig.check_ip 127.0.0.1\n salt ns1 dig.check_ip 1111:2222:3333:4444:5555:6666:7777:8888\n '''\n\n try:\n addr = addr.rsplit('/', 1)\n except AttributeError:\n # Non-string passed\n return False\n\n if salt.utils.network.is_ipv4(addr[0]):\n try:\n if 1 <= int(addr[1]) <= 32:\n return True\n except ValueError:\n # Non-int subnet notation\n return False\n except IndexError:\n # No subnet notation used (i.e. just an IPv4 address)\n return True\n\n if salt.utils.network.is_ipv6(addr[0]):\n try:\n if 8 <= int(addr[1]) <= 128:\n return True\n except ValueError:\n # Non-int subnet notation\n return False\n except IndexError:\n # No subnet notation used (i.e. just an IPv4 address)\n return True\n\n return False\n",
"def SPF(domain, record='SPF', nameserver=None):\n '''\n Return the allowed IPv4 ranges in the SPF record for ``domain``.\n\n If record is ``SPF`` and the SPF record is empty, the TXT record will be\n searched automatically. If you know the domain uses TXT and not SPF,\n specifying that will save a lookup.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt ns1 dig.SPF google.com\n '''\n spf_re = re.compile(r'(?:\\+|~)?(ip[46]|include):(.+)')\n cmd = ['dig', '+short', six.text_type(domain), record]\n\n if nameserver is not None:\n cmd.append('@{0}'.format(nameserver))\n\n result = __salt__['cmd.run_all'](cmd, python_shell=False)\n # In this case, 0 is not the same as False\n if result['retcode'] != 0:\n log.warning(\n 'dig returned exit code \\'%s\\'. Returning empty list as fallback.',\n result['retcode']\n )\n return []\n\n if result['stdout'] == '' and record == 'SPF':\n # empty string is successful query, but nothing to return. So, try TXT\n # record.\n return SPF(domain, 'TXT', nameserver)\n\n sections = re.sub('\"', '', result['stdout']).split()\n if not sections or sections[0] != 'v=spf1':\n return []\n\n if sections[1].startswith('redirect='):\n # Run a lookup on the part after 'redirect=' (9 chars)\n return SPF(sections[1][9:], 'SPF', nameserver)\n ret = []\n for section in sections[1:]:\n try:\n mechanism, address = spf_re.match(section).groups()\n except AttributeError:\n # Regex was not matched\n continue\n if mechanism == 'include':\n ret.extend(SPF(address, 'SPF', nameserver))\n elif mechanism in ('ip4', 'ip6') and check_ip(address):\n ret.append(address)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Compendium of generic DNS utilities.
The 'dig' command line tool must be installed in order to use this module.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
import salt.utils.network
import salt.utils.path
from salt.ext import six
# Import python libs
import logging
import re
log = logging.getLogger(__name__)
__virtualname__ = 'dig'
def __virtual__():
'''
Only load module if dig binary is present
'''
if salt.utils.path.which('dig'):
return __virtualname__
return (False, 'The dig execution module cannot be loaded: '
'the dig binary is not in the path.')
def check_ip(addr):
'''
Check if address is a valid IP. returns True if valid, otherwise False.
CLI Example:
.. code-block:: bash
salt ns1 dig.check_ip 127.0.0.1
salt ns1 dig.check_ip 1111:2222:3333:4444:5555:6666:7777:8888
'''
try:
addr = addr.rsplit('/', 1)
except AttributeError:
# Non-string passed
return False
if salt.utils.network.is_ipv4(addr[0]):
try:
if 1 <= int(addr[1]) <= 32:
return True
except ValueError:
# Non-int subnet notation
return False
except IndexError:
# No subnet notation used (i.e. just an IPv4 address)
return True
if salt.utils.network.is_ipv6(addr[0]):
try:
if 8 <= int(addr[1]) <= 128:
return True
except ValueError:
# Non-int subnet notation
return False
except IndexError:
# No subnet notation used (i.e. just an IPv4 address)
return True
return False
def A(host, nameserver=None):
'''
Return the A record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.A www.google.com
'''
dig = ['dig', '+short', six.text_type(host), 'A']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
# make sure all entries are IPs
return [x for x in cmd['stdout'].split('\n') if check_ip(x)]
def AAAA(host, nameserver=None):
'''
Return the AAAA record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.AAAA www.google.com
'''
dig = ['dig', '+short', six.text_type(host), 'AAAA']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
# make sure all entries are IPs
return [x for x in cmd['stdout'].split('\n') if check_ip(x)]
def NS(domain, resolve=True, nameserver=None):
'''
Return a list of IPs of the nameservers for ``domain``
If ``resolve`` is False, don't resolve names.
CLI Example:
.. code-block:: bash
salt ns1 dig.NS google.com
'''
dig = ['dig', '+short', six.text_type(domain), 'NS']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
if resolve:
ret = []
for ns_host in cmd['stdout'].split('\n'):
for ip_addr in A(ns_host, nameserver):
ret.append(ip_addr)
return ret
return cmd['stdout'].split('\n')
def MX(domain, resolve=False, nameserver=None):
'''
Return a list of lists for the MX of ``domain``.
If the ``resolve`` argument is True, resolve IPs for the servers.
It's limited to one IP, because although in practice it's very rarely a
round robin, it is an acceptable configuration and pulling just one IP lets
the data be similar to the non-resolved version. If you think an MX has
multiple IPs, don't use the resolver here, resolve them in a separate step.
CLI Example:
.. code-block:: bash
salt ns1 dig.MX google.com
'''
dig = ['dig', '+short', six.text_type(domain), 'MX']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
stdout = [x.split() for x in cmd['stdout'].split('\n')]
if resolve:
return [
(lambda x: [x[0], A(x[1], nameserver)[0]])(x) for x in stdout
]
return stdout
def TXT(host, nameserver=None):
'''
Return the TXT record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.TXT google.com
'''
dig = ['dig', '+short', six.text_type(host), 'TXT']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
return [i for i in cmd['stdout'].split('\n')]
# Let lowercase work, since that is the convention for Salt functions
a = A
aaaa = AAAA
ns = NS
spf = SPF
mx = MX
|
saltstack/salt
|
salt/modules/dig.py
|
MX
|
python
|
def MX(domain, resolve=False, nameserver=None):
'''
Return a list of lists for the MX of ``domain``.
If the ``resolve`` argument is True, resolve IPs for the servers.
It's limited to one IP, because although in practice it's very rarely a
round robin, it is an acceptable configuration and pulling just one IP lets
the data be similar to the non-resolved version. If you think an MX has
multiple IPs, don't use the resolver here, resolve them in a separate step.
CLI Example:
.. code-block:: bash
salt ns1 dig.MX google.com
'''
dig = ['dig', '+short', six.text_type(domain), 'MX']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
stdout = [x.split() for x in cmd['stdout'].split('\n')]
if resolve:
return [
(lambda x: [x[0], A(x[1], nameserver)[0]])(x) for x in stdout
]
return stdout
|
Return a list of lists for the MX of ``domain``.
If the ``resolve`` argument is True, resolve IPs for the servers.
It's limited to one IP, because although in practice it's very rarely a
round robin, it is an acceptable configuration and pulling just one IP lets
the data be similar to the non-resolved version. If you think an MX has
multiple IPs, don't use the resolver here, resolve them in a separate step.
CLI Example:
.. code-block:: bash
salt ns1 dig.MX google.com
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dig.py#L226-L264
| null |
# -*- coding: utf-8 -*-
'''
Compendium of generic DNS utilities.
The 'dig' command line tool must be installed in order to use this module.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
import salt.utils.network
import salt.utils.path
from salt.ext import six
# Import python libs
import logging
import re
log = logging.getLogger(__name__)
__virtualname__ = 'dig'
def __virtual__():
'''
Only load module if dig binary is present
'''
if salt.utils.path.which('dig'):
return __virtualname__
return (False, 'The dig execution module cannot be loaded: '
'the dig binary is not in the path.')
def check_ip(addr):
'''
Check if address is a valid IP. returns True if valid, otherwise False.
CLI Example:
.. code-block:: bash
salt ns1 dig.check_ip 127.0.0.1
salt ns1 dig.check_ip 1111:2222:3333:4444:5555:6666:7777:8888
'''
try:
addr = addr.rsplit('/', 1)
except AttributeError:
# Non-string passed
return False
if salt.utils.network.is_ipv4(addr[0]):
try:
if 1 <= int(addr[1]) <= 32:
return True
except ValueError:
# Non-int subnet notation
return False
except IndexError:
# No subnet notation used (i.e. just an IPv4 address)
return True
if salt.utils.network.is_ipv6(addr[0]):
try:
if 8 <= int(addr[1]) <= 128:
return True
except ValueError:
# Non-int subnet notation
return False
except IndexError:
# No subnet notation used (i.e. just an IPv4 address)
return True
return False
def A(host, nameserver=None):
'''
Return the A record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.A www.google.com
'''
dig = ['dig', '+short', six.text_type(host), 'A']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
# make sure all entries are IPs
return [x for x in cmd['stdout'].split('\n') if check_ip(x)]
def AAAA(host, nameserver=None):
'''
Return the AAAA record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.AAAA www.google.com
'''
dig = ['dig', '+short', six.text_type(host), 'AAAA']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
# make sure all entries are IPs
return [x for x in cmd['stdout'].split('\n') if check_ip(x)]
def NS(domain, resolve=True, nameserver=None):
'''
Return a list of IPs of the nameservers for ``domain``
If ``resolve`` is False, don't resolve names.
CLI Example:
.. code-block:: bash
salt ns1 dig.NS google.com
'''
dig = ['dig', '+short', six.text_type(domain), 'NS']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
if resolve:
ret = []
for ns_host in cmd['stdout'].split('\n'):
for ip_addr in A(ns_host, nameserver):
ret.append(ip_addr)
return ret
return cmd['stdout'].split('\n')
def SPF(domain, record='SPF', nameserver=None):
'''
Return the allowed IPv4 ranges in the SPF record for ``domain``.
If record is ``SPF`` and the SPF record is empty, the TXT record will be
searched automatically. If you know the domain uses TXT and not SPF,
specifying that will save a lookup.
CLI Example:
.. code-block:: bash
salt ns1 dig.SPF google.com
'''
spf_re = re.compile(r'(?:\+|~)?(ip[46]|include):(.+)')
cmd = ['dig', '+short', six.text_type(domain), record]
if nameserver is not None:
cmd.append('@{0}'.format(nameserver))
result = __salt__['cmd.run_all'](cmd, python_shell=False)
# In this case, 0 is not the same as False
if result['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
result['retcode']
)
return []
if result['stdout'] == '' and record == 'SPF':
# empty string is successful query, but nothing to return. So, try TXT
# record.
return SPF(domain, 'TXT', nameserver)
sections = re.sub('"', '', result['stdout']).split()
if not sections or sections[0] != 'v=spf1':
return []
if sections[1].startswith('redirect='):
# Run a lookup on the part after 'redirect=' (9 chars)
return SPF(sections[1][9:], 'SPF', nameserver)
ret = []
for section in sections[1:]:
try:
mechanism, address = spf_re.match(section).groups()
except AttributeError:
# Regex was not matched
continue
if mechanism == 'include':
ret.extend(SPF(address, 'SPF', nameserver))
elif mechanism in ('ip4', 'ip6') and check_ip(address):
ret.append(address)
return ret
def TXT(host, nameserver=None):
'''
Return the TXT record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.TXT google.com
'''
dig = ['dig', '+short', six.text_type(host), 'TXT']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
return [i for i in cmd['stdout'].split('\n')]
# Let lowercase work, since that is the convention for Salt functions
a = A
aaaa = AAAA
ns = NS
spf = SPF
mx = MX
|
saltstack/salt
|
salt/modules/dig.py
|
TXT
|
python
|
def TXT(host, nameserver=None):
'''
Return the TXT record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.TXT google.com
'''
dig = ['dig', '+short', six.text_type(host), 'TXT']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
return [i for i in cmd['stdout'].split('\n')]
|
Return the TXT record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.TXT google.com
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dig.py#L267-L293
| null |
# -*- coding: utf-8 -*-
'''
Compendium of generic DNS utilities.
The 'dig' command line tool must be installed in order to use this module.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import salt libs
import salt.utils.network
import salt.utils.path
from salt.ext import six
# Import python libs
import logging
import re
log = logging.getLogger(__name__)
__virtualname__ = 'dig'
def __virtual__():
'''
Only load module if dig binary is present
'''
if salt.utils.path.which('dig'):
return __virtualname__
return (False, 'The dig execution module cannot be loaded: '
'the dig binary is not in the path.')
def check_ip(addr):
'''
Check if address is a valid IP. returns True if valid, otherwise False.
CLI Example:
.. code-block:: bash
salt ns1 dig.check_ip 127.0.0.1
salt ns1 dig.check_ip 1111:2222:3333:4444:5555:6666:7777:8888
'''
try:
addr = addr.rsplit('/', 1)
except AttributeError:
# Non-string passed
return False
if salt.utils.network.is_ipv4(addr[0]):
try:
if 1 <= int(addr[1]) <= 32:
return True
except ValueError:
# Non-int subnet notation
return False
except IndexError:
# No subnet notation used (i.e. just an IPv4 address)
return True
if salt.utils.network.is_ipv6(addr[0]):
try:
if 8 <= int(addr[1]) <= 128:
return True
except ValueError:
# Non-int subnet notation
return False
except IndexError:
# No subnet notation used (i.e. just an IPv4 address)
return True
return False
def A(host, nameserver=None):
'''
Return the A record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.A www.google.com
'''
dig = ['dig', '+short', six.text_type(host), 'A']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
# make sure all entries are IPs
return [x for x in cmd['stdout'].split('\n') if check_ip(x)]
def AAAA(host, nameserver=None):
'''
Return the AAAA record for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dig.AAAA www.google.com
'''
dig = ['dig', '+short', six.text_type(host), 'AAAA']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
# make sure all entries are IPs
return [x for x in cmd['stdout'].split('\n') if check_ip(x)]
def NS(domain, resolve=True, nameserver=None):
'''
Return a list of IPs of the nameservers for ``domain``
If ``resolve`` is False, don't resolve names.
CLI Example:
.. code-block:: bash
salt ns1 dig.NS google.com
'''
dig = ['dig', '+short', six.text_type(domain), 'NS']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
if resolve:
ret = []
for ns_host in cmd['stdout'].split('\n'):
for ip_addr in A(ns_host, nameserver):
ret.append(ip_addr)
return ret
return cmd['stdout'].split('\n')
def SPF(domain, record='SPF', nameserver=None):
'''
Return the allowed IPv4 ranges in the SPF record for ``domain``.
If record is ``SPF`` and the SPF record is empty, the TXT record will be
searched automatically. If you know the domain uses TXT and not SPF,
specifying that will save a lookup.
CLI Example:
.. code-block:: bash
salt ns1 dig.SPF google.com
'''
spf_re = re.compile(r'(?:\+|~)?(ip[46]|include):(.+)')
cmd = ['dig', '+short', six.text_type(domain), record]
if nameserver is not None:
cmd.append('@{0}'.format(nameserver))
result = __salt__['cmd.run_all'](cmd, python_shell=False)
# In this case, 0 is not the same as False
if result['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
result['retcode']
)
return []
if result['stdout'] == '' and record == 'SPF':
# empty string is successful query, but nothing to return. So, try TXT
# record.
return SPF(domain, 'TXT', nameserver)
sections = re.sub('"', '', result['stdout']).split()
if not sections or sections[0] != 'v=spf1':
return []
if sections[1].startswith('redirect='):
# Run a lookup on the part after 'redirect=' (9 chars)
return SPF(sections[1][9:], 'SPF', nameserver)
ret = []
for section in sections[1:]:
try:
mechanism, address = spf_re.match(section).groups()
except AttributeError:
# Regex was not matched
continue
if mechanism == 'include':
ret.extend(SPF(address, 'SPF', nameserver))
elif mechanism in ('ip4', 'ip6') and check_ip(address):
ret.append(address)
return ret
def MX(domain, resolve=False, nameserver=None):
'''
Return a list of lists for the MX of ``domain``.
If the ``resolve`` argument is True, resolve IPs for the servers.
It's limited to one IP, because although in practice it's very rarely a
round robin, it is an acceptable configuration and pulling just one IP lets
the data be similar to the non-resolved version. If you think an MX has
multiple IPs, don't use the resolver here, resolve them in a separate step.
CLI Example:
.. code-block:: bash
salt ns1 dig.MX google.com
'''
dig = ['dig', '+short', six.text_type(domain), 'MX']
if nameserver is not None:
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
# In this case, 0 is not the same as False
if cmd['retcode'] != 0:
log.warning(
'dig returned exit code \'%s\'. Returning empty list as fallback.',
cmd['retcode']
)
return []
stdout = [x.split() for x in cmd['stdout'].split('\n')]
if resolve:
return [
(lambda x: [x[0], A(x[1], nameserver)[0]])(x) for x in stdout
]
return stdout
# Let lowercase work, since that is the convention for Salt functions
a = A
aaaa = AAAA
ns = NS
spf = SPF
mx = MX
|
saltstack/salt
|
salt/modules/freebsd_sysctl.py
|
show
|
python
|
def show(config_file=False):
'''
Return a list of sysctl parameters for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.show
'''
roots = (
'compat',
'debug',
'dev',
'hptmv',
'hw',
'kern',
'machdep',
'net',
'p1003_1b',
'security',
'user',
'vfs',
'vm'
)
cmd = 'sysctl -ae'
ret = {}
comps = ['']
if config_file:
# If the file doesn't exist, return an empty list
if not os.path.exists(config_file):
return []
try:
with salt.utils.files.fopen(config_file, 'r') as f:
for line in f.readlines():
l = line.strip()
if l != "" and not l.startswith("#"):
comps = line.split('=', 1)
ret[comps[0]] = comps[1]
return ret
except (OSError, IOError):
log.error('Could not open sysctl config file')
return None
else:
out = __salt__['cmd.run'](cmd, output_loglevel='trace')
for line in out.splitlines():
if any([line.startswith('{0}.'.format(root)) for root in roots]):
comps = line.split('=', 1)
ret[comps[0]] = comps[1]
elif comps[0]:
ret[comps[0]] += '{0}\n'.format(line)
else:
continue
return ret
|
Return a list of sysctl parameters for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.show
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsd_sysctl.py#L40-L95
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n"
] |
# -*- coding: utf-8 -*-
'''
Module for viewing and modifying sysctl parameters
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import os
# Import salt libs
import salt.utils.files
from salt.exceptions import CommandExecutionError
from salt.ext import six
# Define the module's virtual name
__virtualname__ = 'sysctl'
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
'''
Only runs on FreeBSD systems
'''
if __grains__['os'] == 'FreeBSD':
return __virtualname__
return (False, 'The freebsd_sysctl execution module cannot be loaded: '
'only available on FreeBSD systems.')
def _formatfor(name, value, config, tail=''):
if config == '/boot/loader.conf':
return '{0}="{1}"{2}'.format(name, value, tail)
else:
return '{0}={1}{2}'.format(name, value, tail)
def get(name):
'''
Return a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.get hw.physmem
'''
cmd = 'sysctl -n {0}'.format(name)
out = __salt__['cmd.run'](cmd, python_shell=False)
return out
def assign(name, value):
'''
Assign a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.assign net.inet.icmp.icmplim 50
'''
ret = {}
cmd = 'sysctl {0}="{1}"'.format(name, value)
data = __salt__['cmd.run_all'](cmd, python_shell=False)
if data['retcode'] != 0:
raise CommandExecutionError('sysctl failed: {0}'.format(
data['stderr']))
new_name, new_value = data['stdout'].split(':', 1)
ret[new_name] = new_value.split(' -> ')[-1]
return ret
def persist(name, value, config='/etc/sysctl.conf'):
'''
Assign and persist a simple sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.inet.icmp.icmplim 50
salt '*' sysctl.persist coretemp_load NO config=/boot/loader.conf
'''
nlines = []
edited = False
value = six.text_type(value)
with salt.utils.files.fopen(config, 'r') as ifile:
for line in ifile:
line = salt.utils.stringutils.to_unicode(line).rstrip('\n')
if not line.startswith('{0}='.format(name)):
nlines.append(line)
continue
else:
key, rest = line.split('=', 1)
if rest.startswith('"'):
_, rest_v, rest = rest.split('"', 2)
elif rest.startswith('\''):
_, rest_v, rest = rest.split('\'', 2)
else:
rest_v = rest.split()[0]
rest = rest[len(rest_v):]
if rest_v == value:
return 'Already set'
new_line = _formatfor(key, value, config, rest)
nlines.append(new_line)
edited = True
if not edited:
nlines.append("{0}\n".format(_formatfor(name, value, config)))
with salt.utils.files.fopen(config, 'w+') as ofile:
nlines = [salt.utils.stringutils.to_str(_l) + '\n' for _l in nlines]
ofile.writelines(nlines)
if config != '/boot/loader.conf':
assign(name, value)
return 'Updated'
|
saltstack/salt
|
salt/modules/freebsd_sysctl.py
|
assign
|
python
|
def assign(name, value):
'''
Assign a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.assign net.inet.icmp.icmplim 50
'''
ret = {}
cmd = 'sysctl {0}="{1}"'.format(name, value)
data = __salt__['cmd.run_all'](cmd, python_shell=False)
if data['retcode'] != 0:
raise CommandExecutionError('sysctl failed: {0}'.format(
data['stderr']))
new_name, new_value = data['stdout'].split(':', 1)
ret[new_name] = new_value.split(' -> ')[-1]
return ret
|
Assign a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.assign net.inet.icmp.icmplim 50
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsd_sysctl.py#L113-L132
| null |
# -*- coding: utf-8 -*-
'''
Module for viewing and modifying sysctl parameters
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import os
# Import salt libs
import salt.utils.files
from salt.exceptions import CommandExecutionError
from salt.ext import six
# Define the module's virtual name
__virtualname__ = 'sysctl'
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
'''
Only runs on FreeBSD systems
'''
if __grains__['os'] == 'FreeBSD':
return __virtualname__
return (False, 'The freebsd_sysctl execution module cannot be loaded: '
'only available on FreeBSD systems.')
def _formatfor(name, value, config, tail=''):
if config == '/boot/loader.conf':
return '{0}="{1}"{2}'.format(name, value, tail)
else:
return '{0}={1}{2}'.format(name, value, tail)
def show(config_file=False):
'''
Return a list of sysctl parameters for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.show
'''
roots = (
'compat',
'debug',
'dev',
'hptmv',
'hw',
'kern',
'machdep',
'net',
'p1003_1b',
'security',
'user',
'vfs',
'vm'
)
cmd = 'sysctl -ae'
ret = {}
comps = ['']
if config_file:
# If the file doesn't exist, return an empty list
if not os.path.exists(config_file):
return []
try:
with salt.utils.files.fopen(config_file, 'r') as f:
for line in f.readlines():
l = line.strip()
if l != "" and not l.startswith("#"):
comps = line.split('=', 1)
ret[comps[0]] = comps[1]
return ret
except (OSError, IOError):
log.error('Could not open sysctl config file')
return None
else:
out = __salt__['cmd.run'](cmd, output_loglevel='trace')
for line in out.splitlines():
if any([line.startswith('{0}.'.format(root)) for root in roots]):
comps = line.split('=', 1)
ret[comps[0]] = comps[1]
elif comps[0]:
ret[comps[0]] += '{0}\n'.format(line)
else:
continue
return ret
def get(name):
'''
Return a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.get hw.physmem
'''
cmd = 'sysctl -n {0}'.format(name)
out = __salt__['cmd.run'](cmd, python_shell=False)
return out
def persist(name, value, config='/etc/sysctl.conf'):
'''
Assign and persist a simple sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.inet.icmp.icmplim 50
salt '*' sysctl.persist coretemp_load NO config=/boot/loader.conf
'''
nlines = []
edited = False
value = six.text_type(value)
with salt.utils.files.fopen(config, 'r') as ifile:
for line in ifile:
line = salt.utils.stringutils.to_unicode(line).rstrip('\n')
if not line.startswith('{0}='.format(name)):
nlines.append(line)
continue
else:
key, rest = line.split('=', 1)
if rest.startswith('"'):
_, rest_v, rest = rest.split('"', 2)
elif rest.startswith('\''):
_, rest_v, rest = rest.split('\'', 2)
else:
rest_v = rest.split()[0]
rest = rest[len(rest_v):]
if rest_v == value:
return 'Already set'
new_line = _formatfor(key, value, config, rest)
nlines.append(new_line)
edited = True
if not edited:
nlines.append("{0}\n".format(_formatfor(name, value, config)))
with salt.utils.files.fopen(config, 'w+') as ofile:
nlines = [salt.utils.stringutils.to_str(_l) + '\n' for _l in nlines]
ofile.writelines(nlines)
if config != '/boot/loader.conf':
assign(name, value)
return 'Updated'
|
saltstack/salt
|
salt/modules/freebsd_sysctl.py
|
persist
|
python
|
def persist(name, value, config='/etc/sysctl.conf'):
'''
Assign and persist a simple sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.inet.icmp.icmplim 50
salt '*' sysctl.persist coretemp_load NO config=/boot/loader.conf
'''
nlines = []
edited = False
value = six.text_type(value)
with salt.utils.files.fopen(config, 'r') as ifile:
for line in ifile:
line = salt.utils.stringutils.to_unicode(line).rstrip('\n')
if not line.startswith('{0}='.format(name)):
nlines.append(line)
continue
else:
key, rest = line.split('=', 1)
if rest.startswith('"'):
_, rest_v, rest = rest.split('"', 2)
elif rest.startswith('\''):
_, rest_v, rest = rest.split('\'', 2)
else:
rest_v = rest.split()[0]
rest = rest[len(rest_v):]
if rest_v == value:
return 'Already set'
new_line = _formatfor(key, value, config, rest)
nlines.append(new_line)
edited = True
if not edited:
nlines.append("{0}\n".format(_formatfor(name, value, config)))
with salt.utils.files.fopen(config, 'w+') as ofile:
nlines = [salt.utils.stringutils.to_str(_l) + '\n' for _l in nlines]
ofile.writelines(nlines)
if config != '/boot/loader.conf':
assign(name, value)
return 'Updated'
|
Assign and persist a simple sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.inet.icmp.icmplim 50
salt '*' sysctl.persist coretemp_load NO config=/boot/loader.conf
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsd_sysctl.py#L135-L177
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n",
"def assign(name, value):\n '''\n Assign a single sysctl parameter for this minion\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' sysctl.assign net.inet.icmp.icmplim 50\n '''\n ret = {}\n cmd = 'sysctl {0}=\"{1}\"'.format(name, value)\n data = __salt__['cmd.run_all'](cmd, python_shell=False)\n\n if data['retcode'] != 0:\n raise CommandExecutionError('sysctl failed: {0}'.format(\n data['stderr']))\n new_name, new_value = data['stdout'].split(':', 1)\n ret[new_name] = new_value.split(' -> ')[-1]\n return ret\n",
"def _formatfor(name, value, config, tail=''):\n if config == '/boot/loader.conf':\n return '{0}=\"{1}\"{2}'.format(name, value, tail)\n else:\n return '{0}={1}{2}'.format(name, value, tail)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for viewing and modifying sysctl parameters
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import os
# Import salt libs
import salt.utils.files
from salt.exceptions import CommandExecutionError
from salt.ext import six
# Define the module's virtual name
__virtualname__ = 'sysctl'
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
'''
Only runs on FreeBSD systems
'''
if __grains__['os'] == 'FreeBSD':
return __virtualname__
return (False, 'The freebsd_sysctl execution module cannot be loaded: '
'only available on FreeBSD systems.')
def _formatfor(name, value, config, tail=''):
if config == '/boot/loader.conf':
return '{0}="{1}"{2}'.format(name, value, tail)
else:
return '{0}={1}{2}'.format(name, value, tail)
def show(config_file=False):
'''
Return a list of sysctl parameters for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.show
'''
roots = (
'compat',
'debug',
'dev',
'hptmv',
'hw',
'kern',
'machdep',
'net',
'p1003_1b',
'security',
'user',
'vfs',
'vm'
)
cmd = 'sysctl -ae'
ret = {}
comps = ['']
if config_file:
# If the file doesn't exist, return an empty list
if not os.path.exists(config_file):
return []
try:
with salt.utils.files.fopen(config_file, 'r') as f:
for line in f.readlines():
l = line.strip()
if l != "" and not l.startswith("#"):
comps = line.split('=', 1)
ret[comps[0]] = comps[1]
return ret
except (OSError, IOError):
log.error('Could not open sysctl config file')
return None
else:
out = __salt__['cmd.run'](cmd, output_loglevel='trace')
for line in out.splitlines():
if any([line.startswith('{0}.'.format(root)) for root in roots]):
comps = line.split('=', 1)
ret[comps[0]] = comps[1]
elif comps[0]:
ret[comps[0]] += '{0}\n'.format(line)
else:
continue
return ret
def get(name):
'''
Return a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.get hw.physmem
'''
cmd = 'sysctl -n {0}'.format(name)
out = __salt__['cmd.run'](cmd, python_shell=False)
return out
def assign(name, value):
'''
Assign a single sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.assign net.inet.icmp.icmplim 50
'''
ret = {}
cmd = 'sysctl {0}="{1}"'.format(name, value)
data = __salt__['cmd.run_all'](cmd, python_shell=False)
if data['retcode'] != 0:
raise CommandExecutionError('sysctl failed: {0}'.format(
data['stderr']))
new_name, new_value = data['stdout'].split(':', 1)
ret[new_name] = new_value.split(' -> ')[-1]
return ret
|
saltstack/salt
|
salt/states/augeas.py
|
_workout_filename
|
python
|
def _workout_filename(filename):
'''
Recursively workout the file name from an augeas change
'''
if os.path.isfile(filename) or filename == '/':
if filename == '/':
filename = None
return filename
else:
return _workout_filename(os.path.dirname(filename))
|
Recursively workout the file name from an augeas change
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/augeas.py#L53-L62
| null |
# -*- coding: utf-8 -*-
'''
Configuration management using Augeas
.. versionadded:: 0.17.0
This state requires the ``augeas`` Python module.
.. _Augeas: http://augeas.net/
Augeas_ can be used to manage configuration files.
.. warning::
Minimal installations of Debian and Ubuntu have been seen to have packaging
bugs with python-augeas, causing the augeas module to fail to import. If
the minion has the augeas module installed, and the state fails with a
comment saying that the state is unavailable, first restart the salt-minion
service. If the problem persists past that, the following command can be
run from the master to determine what is causing the import to fail:
.. code-block:: bash
salt minion-id cmd.run 'python -c "from augeas import Augeas"'
For affected Debian/Ubuntu hosts, installing ``libpython2.7`` has been
known to resolve the issue.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import re
import os.path
import logging
import difflib
# Import Salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from salt.modules.augeas_cfg import METHOD_MAP
log = logging.getLogger(__name__)
def __virtual__():
return 'augeas' if 'augeas.execute' in __salt__ else False
def _check_filepath(changes):
'''
Ensure all changes are fully qualified and affect only one file.
This ensures that the diff output works and a state change is not
incorrectly reported.
'''
filename = None
for change_ in changes:
try:
cmd, arg = change_.split(' ', 1)
if cmd not in METHOD_MAP:
error = 'Command {0} is not supported (yet)'.format(cmd)
raise ValueError(error)
method = METHOD_MAP[cmd]
parts = salt.utils.args.shlex_split(arg)
if method in ['set', 'setm', 'move', 'remove']:
filename_ = parts[0]
else:
_, _, filename_ = parts
if not filename_.startswith('/files'):
error = 'Changes should be prefixed with ' \
'/files if no context is provided,' \
' change: {0}'.format(change_)
raise ValueError(error)
filename_ = re.sub('^/files|/$', '', filename_)
if filename is not None:
if filename != filename_:
error = 'Changes should be made to one ' \
'file at a time, detected changes ' \
'to {0} and {1}'.format(filename, filename_)
raise ValueError(error)
filename = filename_
except (ValueError, IndexError) as err:
log.error(err)
if 'error' not in locals():
error = 'Invalid formatted command, ' \
'see debug log for details: {0}' \
.format(change_)
else:
error = six.text_type(err)
raise ValueError(error)
filename = _workout_filename(filename)
return filename
def change(name, context=None, changes=None, lens=None,
load_path=None, **kwargs):
'''
.. versionadded:: 2014.7.0
This state replaces :py:func:`~salt.states.augeas.setvalue`.
Issue changes to Augeas, optionally for a specific context, with a
specific lens.
name
State name
context
A file path, prefixed by ``/files``. Should resolve to an actual file
(not an arbitrary augeas path). This is used to avoid duplicating the
file name for each item in the changes list (for example, ``set bind 0.0.0.0``
in the example below operates on the file specified by ``context``). If
``context`` is not specified, a file path prefixed by ``/files`` should be
included with the ``set`` command.
The file path is examined to determine if the
specified changes are already present.
.. code-block:: yaml
redis-conf:
augeas.change:
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
- set maxmemory 1G
changes
List of changes that are issued to Augeas. Available commands are
``set``, ``setm``, ``mv``/``move``, ``ins``/``insert``, and
``rm``/``remove``.
lens
The lens to use, needs to be suffixed with `.lns`, e.g.: `Nginx.lns`.
See the `list of stock lenses <http://augeas.net/stock_lenses.html>`_
shipped with Augeas.
.. versionadded:: 2016.3.0
load_path
A list of directories that modules should be searched in. This is in
addition to the standard load path and the directories in
AUGEAS_LENS_LIB.
Usage examples:
Set the ``bind`` parameter in ``/etc/redis/redis.conf``:
.. code-block:: yaml
redis-conf:
augeas.change:
- changes:
- set /files/etc/redis/redis.conf/bind 0.0.0.0
.. note::
Use the ``context`` parameter to specify the file you want to
manipulate. This way you don't have to include this in the changes
every time:
.. code-block:: yaml
redis-conf:
augeas.change:
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
- set databases 4
- set maxmemory 1G
Augeas is aware of a lot of common configuration files and their syntax.
It knows the difference between for example ini and yaml files, but also
files with very specific syntax, like the hosts file. This is done with
*lenses*, which provide mappings between the Augeas tree and the file.
There are many `preconfigured lenses`_ that come with Augeas by default,
and they specify the common locations for configuration files. So most
of the time Augeas will know how to manipulate a file. In the event that
you need to manipulate a file that Augeas doesn't know about, you can
specify the lens to use like this:
.. code-block:: yaml
redis-conf:
augeas.change:
- lens: redis.lns
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
.. note::
Even though Augeas knows that ``/etc/redis/redis.conf`` is a Redis
configuration file and knows how to parse it, it is recommended to
specify the lens anyway. This is because by default, Augeas loads all
known lenses and their associated file paths. All these files are
parsed when Augeas is loaded, which can take some time. When specifying
a lens, Augeas is loaded with only that lens, which speeds things up
quite a bit.
.. _preconfigured lenses: http://augeas.net/stock_lenses.html
A more complex example, this adds an entry to the services file for Zabbix,
and removes an obsolete service:
.. code-block:: yaml
zabbix-service:
augeas.change:
- lens: services.lns
- context: /files/etc/services
- changes:
- ins service-name after service-name[last()]
- set service-name[last()] "zabbix-agent"
- set "service-name[. = 'zabbix-agent']/port" 10050
- set "service-name[. = 'zabbix-agent']/protocol" tcp
- set "service-name[. = 'zabbix-agent']/#comment" "Zabbix Agent service"
- rm "service-name[. = 'im-obsolete']"
- unless: grep "zabbix-agent" /etc/services
.. warning::
Don't forget the ``unless`` here, otherwise it will fail on next runs
because the service is already defined. Additionally you have to quote
lines containing ``service-name[. = 'zabbix-agent']`` otherwise
:mod:`augeas_cfg <salt.modules.augeas_cfg>` execute will fail because
it will receive more parameters than expected.
.. note::
Order is important when defining a service with Augeas, in this case
it's ``port``, ``protocol`` and ``#comment``. For more info about
the lens check `services lens documentation`_.
.. _services lens documentation:
http://augeas.net/docs/references/lenses/files/services-aug.html#Services.record
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
if not changes or not isinstance(changes, list):
ret['comment'] = '\'changes\' must be specified as a list'
return ret
if load_path is not None:
if not isinstance(load_path, list):
ret['comment'] = '\'load_path\' must be specified as a list'
return ret
else:
load_path = ':'.join(load_path)
filename = None
if context is None:
try:
filename = _check_filepath(changes)
except ValueError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
else:
filename = re.sub('^/files|/$', '', context)
if __opts__['test']:
ret['result'] = True
ret['comment'] = 'Executing commands'
if context:
ret['comment'] += ' in file "{0}":\n'.format(context)
ret['comment'] += "\n".join(changes)
return ret
old_file = []
if filename is not None and os.path.isfile(filename):
with salt.utils.files.fopen(filename, 'r') as file_:
old_file = [salt.utils.stringutils.to_unicode(x)
for x in file_.readlines()]
result = __salt__['augeas.execute'](
context=context, lens=lens,
commands=changes, load_path=load_path)
ret['result'] = result['retval']
if ret['result'] is False:
ret['comment'] = 'Error: {0}'.format(result['error'])
return ret
if filename is not None and os.path.isfile(filename):
with salt.utils.files.fopen(filename, 'r') as file_:
new_file = [salt.utils.stringutils.to_unicode(x)
for x in file_.readlines()]
diff = ''.join(
difflib.unified_diff(old_file, new_file, n=0))
if diff:
ret['comment'] = 'Changes have been saved'
ret['changes'] = {'diff': diff}
else:
ret['comment'] = 'No changes made'
else:
ret['comment'] = 'Changes have been saved'
ret['changes'] = {'updates': changes}
return ret
|
saltstack/salt
|
salt/states/augeas.py
|
_check_filepath
|
python
|
def _check_filepath(changes):
'''
Ensure all changes are fully qualified and affect only one file.
This ensures that the diff output works and a state change is not
incorrectly reported.
'''
filename = None
for change_ in changes:
try:
cmd, arg = change_.split(' ', 1)
if cmd not in METHOD_MAP:
error = 'Command {0} is not supported (yet)'.format(cmd)
raise ValueError(error)
method = METHOD_MAP[cmd]
parts = salt.utils.args.shlex_split(arg)
if method in ['set', 'setm', 'move', 'remove']:
filename_ = parts[0]
else:
_, _, filename_ = parts
if not filename_.startswith('/files'):
error = 'Changes should be prefixed with ' \
'/files if no context is provided,' \
' change: {0}'.format(change_)
raise ValueError(error)
filename_ = re.sub('^/files|/$', '', filename_)
if filename is not None:
if filename != filename_:
error = 'Changes should be made to one ' \
'file at a time, detected changes ' \
'to {0} and {1}'.format(filename, filename_)
raise ValueError(error)
filename = filename_
except (ValueError, IndexError) as err:
log.error(err)
if 'error' not in locals():
error = 'Invalid formatted command, ' \
'see debug log for details: {0}' \
.format(change_)
else:
error = six.text_type(err)
raise ValueError(error)
filename = _workout_filename(filename)
return filename
|
Ensure all changes are fully qualified and affect only one file.
This ensures that the diff output works and a state change is not
incorrectly reported.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/augeas.py#L65-L110
| null |
# -*- coding: utf-8 -*-
'''
Configuration management using Augeas
.. versionadded:: 0.17.0
This state requires the ``augeas`` Python module.
.. _Augeas: http://augeas.net/
Augeas_ can be used to manage configuration files.
.. warning::
Minimal installations of Debian and Ubuntu have been seen to have packaging
bugs with python-augeas, causing the augeas module to fail to import. If
the minion has the augeas module installed, and the state fails with a
comment saying that the state is unavailable, first restart the salt-minion
service. If the problem persists past that, the following command can be
run from the master to determine what is causing the import to fail:
.. code-block:: bash
salt minion-id cmd.run 'python -c "from augeas import Augeas"'
For affected Debian/Ubuntu hosts, installing ``libpython2.7`` has been
known to resolve the issue.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import re
import os.path
import logging
import difflib
# Import Salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from salt.modules.augeas_cfg import METHOD_MAP
log = logging.getLogger(__name__)
def __virtual__():
return 'augeas' if 'augeas.execute' in __salt__ else False
def _workout_filename(filename):
'''
Recursively workout the file name from an augeas change
'''
if os.path.isfile(filename) or filename == '/':
if filename == '/':
filename = None
return filename
else:
return _workout_filename(os.path.dirname(filename))
def change(name, context=None, changes=None, lens=None,
load_path=None, **kwargs):
'''
.. versionadded:: 2014.7.0
This state replaces :py:func:`~salt.states.augeas.setvalue`.
Issue changes to Augeas, optionally for a specific context, with a
specific lens.
name
State name
context
A file path, prefixed by ``/files``. Should resolve to an actual file
(not an arbitrary augeas path). This is used to avoid duplicating the
file name for each item in the changes list (for example, ``set bind 0.0.0.0``
in the example below operates on the file specified by ``context``). If
``context`` is not specified, a file path prefixed by ``/files`` should be
included with the ``set`` command.
The file path is examined to determine if the
specified changes are already present.
.. code-block:: yaml
redis-conf:
augeas.change:
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
- set maxmemory 1G
changes
List of changes that are issued to Augeas. Available commands are
``set``, ``setm``, ``mv``/``move``, ``ins``/``insert``, and
``rm``/``remove``.
lens
The lens to use, needs to be suffixed with `.lns`, e.g.: `Nginx.lns`.
See the `list of stock lenses <http://augeas.net/stock_lenses.html>`_
shipped with Augeas.
.. versionadded:: 2016.3.0
load_path
A list of directories that modules should be searched in. This is in
addition to the standard load path and the directories in
AUGEAS_LENS_LIB.
Usage examples:
Set the ``bind`` parameter in ``/etc/redis/redis.conf``:
.. code-block:: yaml
redis-conf:
augeas.change:
- changes:
- set /files/etc/redis/redis.conf/bind 0.0.0.0
.. note::
Use the ``context`` parameter to specify the file you want to
manipulate. This way you don't have to include this in the changes
every time:
.. code-block:: yaml
redis-conf:
augeas.change:
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
- set databases 4
- set maxmemory 1G
Augeas is aware of a lot of common configuration files and their syntax.
It knows the difference between for example ini and yaml files, but also
files with very specific syntax, like the hosts file. This is done with
*lenses*, which provide mappings between the Augeas tree and the file.
There are many `preconfigured lenses`_ that come with Augeas by default,
and they specify the common locations for configuration files. So most
of the time Augeas will know how to manipulate a file. In the event that
you need to manipulate a file that Augeas doesn't know about, you can
specify the lens to use like this:
.. code-block:: yaml
redis-conf:
augeas.change:
- lens: redis.lns
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
.. note::
Even though Augeas knows that ``/etc/redis/redis.conf`` is a Redis
configuration file and knows how to parse it, it is recommended to
specify the lens anyway. This is because by default, Augeas loads all
known lenses and their associated file paths. All these files are
parsed when Augeas is loaded, which can take some time. When specifying
a lens, Augeas is loaded with only that lens, which speeds things up
quite a bit.
.. _preconfigured lenses: http://augeas.net/stock_lenses.html
A more complex example, this adds an entry to the services file for Zabbix,
and removes an obsolete service:
.. code-block:: yaml
zabbix-service:
augeas.change:
- lens: services.lns
- context: /files/etc/services
- changes:
- ins service-name after service-name[last()]
- set service-name[last()] "zabbix-agent"
- set "service-name[. = 'zabbix-agent']/port" 10050
- set "service-name[. = 'zabbix-agent']/protocol" tcp
- set "service-name[. = 'zabbix-agent']/#comment" "Zabbix Agent service"
- rm "service-name[. = 'im-obsolete']"
- unless: grep "zabbix-agent" /etc/services
.. warning::
Don't forget the ``unless`` here, otherwise it will fail on next runs
because the service is already defined. Additionally you have to quote
lines containing ``service-name[. = 'zabbix-agent']`` otherwise
:mod:`augeas_cfg <salt.modules.augeas_cfg>` execute will fail because
it will receive more parameters than expected.
.. note::
Order is important when defining a service with Augeas, in this case
it's ``port``, ``protocol`` and ``#comment``. For more info about
the lens check `services lens documentation`_.
.. _services lens documentation:
http://augeas.net/docs/references/lenses/files/services-aug.html#Services.record
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
if not changes or not isinstance(changes, list):
ret['comment'] = '\'changes\' must be specified as a list'
return ret
if load_path is not None:
if not isinstance(load_path, list):
ret['comment'] = '\'load_path\' must be specified as a list'
return ret
else:
load_path = ':'.join(load_path)
filename = None
if context is None:
try:
filename = _check_filepath(changes)
except ValueError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
else:
filename = re.sub('^/files|/$', '', context)
if __opts__['test']:
ret['result'] = True
ret['comment'] = 'Executing commands'
if context:
ret['comment'] += ' in file "{0}":\n'.format(context)
ret['comment'] += "\n".join(changes)
return ret
old_file = []
if filename is not None and os.path.isfile(filename):
with salt.utils.files.fopen(filename, 'r') as file_:
old_file = [salt.utils.stringutils.to_unicode(x)
for x in file_.readlines()]
result = __salt__['augeas.execute'](
context=context, lens=lens,
commands=changes, load_path=load_path)
ret['result'] = result['retval']
if ret['result'] is False:
ret['comment'] = 'Error: {0}'.format(result['error'])
return ret
if filename is not None and os.path.isfile(filename):
with salt.utils.files.fopen(filename, 'r') as file_:
new_file = [salt.utils.stringutils.to_unicode(x)
for x in file_.readlines()]
diff = ''.join(
difflib.unified_diff(old_file, new_file, n=0))
if diff:
ret['comment'] = 'Changes have been saved'
ret['changes'] = {'diff': diff}
else:
ret['comment'] = 'No changes made'
else:
ret['comment'] = 'Changes have been saved'
ret['changes'] = {'updates': changes}
return ret
|
saltstack/salt
|
salt/states/augeas.py
|
change
|
python
|
def change(name, context=None, changes=None, lens=None,
load_path=None, **kwargs):
'''
.. versionadded:: 2014.7.0
This state replaces :py:func:`~salt.states.augeas.setvalue`.
Issue changes to Augeas, optionally for a specific context, with a
specific lens.
name
State name
context
A file path, prefixed by ``/files``. Should resolve to an actual file
(not an arbitrary augeas path). This is used to avoid duplicating the
file name for each item in the changes list (for example, ``set bind 0.0.0.0``
in the example below operates on the file specified by ``context``). If
``context`` is not specified, a file path prefixed by ``/files`` should be
included with the ``set`` command.
The file path is examined to determine if the
specified changes are already present.
.. code-block:: yaml
redis-conf:
augeas.change:
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
- set maxmemory 1G
changes
List of changes that are issued to Augeas. Available commands are
``set``, ``setm``, ``mv``/``move``, ``ins``/``insert``, and
``rm``/``remove``.
lens
The lens to use, needs to be suffixed with `.lns`, e.g.: `Nginx.lns`.
See the `list of stock lenses <http://augeas.net/stock_lenses.html>`_
shipped with Augeas.
.. versionadded:: 2016.3.0
load_path
A list of directories that modules should be searched in. This is in
addition to the standard load path and the directories in
AUGEAS_LENS_LIB.
Usage examples:
Set the ``bind`` parameter in ``/etc/redis/redis.conf``:
.. code-block:: yaml
redis-conf:
augeas.change:
- changes:
- set /files/etc/redis/redis.conf/bind 0.0.0.0
.. note::
Use the ``context`` parameter to specify the file you want to
manipulate. This way you don't have to include this in the changes
every time:
.. code-block:: yaml
redis-conf:
augeas.change:
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
- set databases 4
- set maxmemory 1G
Augeas is aware of a lot of common configuration files and their syntax.
It knows the difference between for example ini and yaml files, but also
files with very specific syntax, like the hosts file. This is done with
*lenses*, which provide mappings between the Augeas tree and the file.
There are many `preconfigured lenses`_ that come with Augeas by default,
and they specify the common locations for configuration files. So most
of the time Augeas will know how to manipulate a file. In the event that
you need to manipulate a file that Augeas doesn't know about, you can
specify the lens to use like this:
.. code-block:: yaml
redis-conf:
augeas.change:
- lens: redis.lns
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
.. note::
Even though Augeas knows that ``/etc/redis/redis.conf`` is a Redis
configuration file and knows how to parse it, it is recommended to
specify the lens anyway. This is because by default, Augeas loads all
known lenses and their associated file paths. All these files are
parsed when Augeas is loaded, which can take some time. When specifying
a lens, Augeas is loaded with only that lens, which speeds things up
quite a bit.
.. _preconfigured lenses: http://augeas.net/stock_lenses.html
A more complex example, this adds an entry to the services file for Zabbix,
and removes an obsolete service:
.. code-block:: yaml
zabbix-service:
augeas.change:
- lens: services.lns
- context: /files/etc/services
- changes:
- ins service-name after service-name[last()]
- set service-name[last()] "zabbix-agent"
- set "service-name[. = 'zabbix-agent']/port" 10050
- set "service-name[. = 'zabbix-agent']/protocol" tcp
- set "service-name[. = 'zabbix-agent']/#comment" "Zabbix Agent service"
- rm "service-name[. = 'im-obsolete']"
- unless: grep "zabbix-agent" /etc/services
.. warning::
Don't forget the ``unless`` here, otherwise it will fail on next runs
because the service is already defined. Additionally you have to quote
lines containing ``service-name[. = 'zabbix-agent']`` otherwise
:mod:`augeas_cfg <salt.modules.augeas_cfg>` execute will fail because
it will receive more parameters than expected.
.. note::
Order is important when defining a service with Augeas, in this case
it's ``port``, ``protocol`` and ``#comment``. For more info about
the lens check `services lens documentation`_.
.. _services lens documentation:
http://augeas.net/docs/references/lenses/files/services-aug.html#Services.record
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
if not changes or not isinstance(changes, list):
ret['comment'] = '\'changes\' must be specified as a list'
return ret
if load_path is not None:
if not isinstance(load_path, list):
ret['comment'] = '\'load_path\' must be specified as a list'
return ret
else:
load_path = ':'.join(load_path)
filename = None
if context is None:
try:
filename = _check_filepath(changes)
except ValueError as err:
ret['comment'] = 'Error: {0}'.format(err)
return ret
else:
filename = re.sub('^/files|/$', '', context)
if __opts__['test']:
ret['result'] = True
ret['comment'] = 'Executing commands'
if context:
ret['comment'] += ' in file "{0}":\n'.format(context)
ret['comment'] += "\n".join(changes)
return ret
old_file = []
if filename is not None and os.path.isfile(filename):
with salt.utils.files.fopen(filename, 'r') as file_:
old_file = [salt.utils.stringutils.to_unicode(x)
for x in file_.readlines()]
result = __salt__['augeas.execute'](
context=context, lens=lens,
commands=changes, load_path=load_path)
ret['result'] = result['retval']
if ret['result'] is False:
ret['comment'] = 'Error: {0}'.format(result['error'])
return ret
if filename is not None and os.path.isfile(filename):
with salt.utils.files.fopen(filename, 'r') as file_:
new_file = [salt.utils.stringutils.to_unicode(x)
for x in file_.readlines()]
diff = ''.join(
difflib.unified_diff(old_file, new_file, n=0))
if diff:
ret['comment'] = 'Changes have been saved'
ret['changes'] = {'diff': diff}
else:
ret['comment'] = 'No changes made'
else:
ret['comment'] = 'Changes have been saved'
ret['changes'] = {'updates': changes}
return ret
|
.. versionadded:: 2014.7.0
This state replaces :py:func:`~salt.states.augeas.setvalue`.
Issue changes to Augeas, optionally for a specific context, with a
specific lens.
name
State name
context
A file path, prefixed by ``/files``. Should resolve to an actual file
(not an arbitrary augeas path). This is used to avoid duplicating the
file name for each item in the changes list (for example, ``set bind 0.0.0.0``
in the example below operates on the file specified by ``context``). If
``context`` is not specified, a file path prefixed by ``/files`` should be
included with the ``set`` command.
The file path is examined to determine if the
specified changes are already present.
.. code-block:: yaml
redis-conf:
augeas.change:
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
- set maxmemory 1G
changes
List of changes that are issued to Augeas. Available commands are
``set``, ``setm``, ``mv``/``move``, ``ins``/``insert``, and
``rm``/``remove``.
lens
The lens to use, needs to be suffixed with `.lns`, e.g.: `Nginx.lns`.
See the `list of stock lenses <http://augeas.net/stock_lenses.html>`_
shipped with Augeas.
.. versionadded:: 2016.3.0
load_path
A list of directories that modules should be searched in. This is in
addition to the standard load path and the directories in
AUGEAS_LENS_LIB.
Usage examples:
Set the ``bind`` parameter in ``/etc/redis/redis.conf``:
.. code-block:: yaml
redis-conf:
augeas.change:
- changes:
- set /files/etc/redis/redis.conf/bind 0.0.0.0
.. note::
Use the ``context`` parameter to specify the file you want to
manipulate. This way you don't have to include this in the changes
every time:
.. code-block:: yaml
redis-conf:
augeas.change:
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
- set databases 4
- set maxmemory 1G
Augeas is aware of a lot of common configuration files and their syntax.
It knows the difference between for example ini and yaml files, but also
files with very specific syntax, like the hosts file. This is done with
*lenses*, which provide mappings between the Augeas tree and the file.
There are many `preconfigured lenses`_ that come with Augeas by default,
and they specify the common locations for configuration files. So most
of the time Augeas will know how to manipulate a file. In the event that
you need to manipulate a file that Augeas doesn't know about, you can
specify the lens to use like this:
.. code-block:: yaml
redis-conf:
augeas.change:
- lens: redis.lns
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
.. note::
Even though Augeas knows that ``/etc/redis/redis.conf`` is a Redis
configuration file and knows how to parse it, it is recommended to
specify the lens anyway. This is because by default, Augeas loads all
known lenses and their associated file paths. All these files are
parsed when Augeas is loaded, which can take some time. When specifying
a lens, Augeas is loaded with only that lens, which speeds things up
quite a bit.
.. _preconfigured lenses: http://augeas.net/stock_lenses.html
A more complex example, this adds an entry to the services file for Zabbix,
and removes an obsolete service:
.. code-block:: yaml
zabbix-service:
augeas.change:
- lens: services.lns
- context: /files/etc/services
- changes:
- ins service-name after service-name[last()]
- set service-name[last()] "zabbix-agent"
- set "service-name[. = 'zabbix-agent']/port" 10050
- set "service-name[. = 'zabbix-agent']/protocol" tcp
- set "service-name[. = 'zabbix-agent']/#comment" "Zabbix Agent service"
- rm "service-name[. = 'im-obsolete']"
- unless: grep "zabbix-agent" /etc/services
.. warning::
Don't forget the ``unless`` here, otherwise it will fail on next runs
because the service is already defined. Additionally you have to quote
lines containing ``service-name[. = 'zabbix-agent']`` otherwise
:mod:`augeas_cfg <salt.modules.augeas_cfg>` execute will fail because
it will receive more parameters than expected.
.. note::
Order is important when defining a service with Augeas, in this case
it's ``port``, ``protocol`` and ``#comment``. For more info about
the lens check `services lens documentation`_.
.. _services lens documentation:
http://augeas.net/docs/references/lenses/files/services-aug.html#Services.record
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/augeas.py#L113-L323
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def _check_filepath(changes):\n '''\n Ensure all changes are fully qualified and affect only one file.\n This ensures that the diff output works and a state change is not\n incorrectly reported.\n '''\n filename = None\n for change_ in changes:\n try:\n cmd, arg = change_.split(' ', 1)\n\n if cmd not in METHOD_MAP:\n error = 'Command {0} is not supported (yet)'.format(cmd)\n raise ValueError(error)\n method = METHOD_MAP[cmd]\n parts = salt.utils.args.shlex_split(arg)\n if method in ['set', 'setm', 'move', 'remove']:\n filename_ = parts[0]\n else:\n _, _, filename_ = parts\n if not filename_.startswith('/files'):\n error = 'Changes should be prefixed with ' \\\n '/files if no context is provided,' \\\n ' change: {0}'.format(change_)\n raise ValueError(error)\n filename_ = re.sub('^/files|/$', '', filename_)\n if filename is not None:\n if filename != filename_:\n error = 'Changes should be made to one ' \\\n 'file at a time, detected changes ' \\\n 'to {0} and {1}'.format(filename, filename_)\n raise ValueError(error)\n filename = filename_\n except (ValueError, IndexError) as err:\n log.error(err)\n if 'error' not in locals():\n error = 'Invalid formatted command, ' \\\n 'see debug log for details: {0}' \\\n .format(change_)\n else:\n error = six.text_type(err)\n raise ValueError(error)\n\n filename = _workout_filename(filename)\n\n return filename\n"
] |
# -*- coding: utf-8 -*-
'''
Configuration management using Augeas
.. versionadded:: 0.17.0
This state requires the ``augeas`` Python module.
.. _Augeas: http://augeas.net/
Augeas_ can be used to manage configuration files.
.. warning::
Minimal installations of Debian and Ubuntu have been seen to have packaging
bugs with python-augeas, causing the augeas module to fail to import. If
the minion has the augeas module installed, and the state fails with a
comment saying that the state is unavailable, first restart the salt-minion
service. If the problem persists past that, the following command can be
run from the master to determine what is causing the import to fail:
.. code-block:: bash
salt minion-id cmd.run 'python -c "from augeas import Augeas"'
For affected Debian/Ubuntu hosts, installing ``libpython2.7`` has been
known to resolve the issue.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import re
import os.path
import logging
import difflib
# Import Salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from salt.modules.augeas_cfg import METHOD_MAP
log = logging.getLogger(__name__)
def __virtual__():
return 'augeas' if 'augeas.execute' in __salt__ else False
def _workout_filename(filename):
'''
Recursively workout the file name from an augeas change
'''
if os.path.isfile(filename) or filename == '/':
if filename == '/':
filename = None
return filename
else:
return _workout_filename(os.path.dirname(filename))
def _check_filepath(changes):
'''
Ensure all changes are fully qualified and affect only one file.
This ensures that the diff output works and a state change is not
incorrectly reported.
'''
filename = None
for change_ in changes:
try:
cmd, arg = change_.split(' ', 1)
if cmd not in METHOD_MAP:
error = 'Command {0} is not supported (yet)'.format(cmd)
raise ValueError(error)
method = METHOD_MAP[cmd]
parts = salt.utils.args.shlex_split(arg)
if method in ['set', 'setm', 'move', 'remove']:
filename_ = parts[0]
else:
_, _, filename_ = parts
if not filename_.startswith('/files'):
error = 'Changes should be prefixed with ' \
'/files if no context is provided,' \
' change: {0}'.format(change_)
raise ValueError(error)
filename_ = re.sub('^/files|/$', '', filename_)
if filename is not None:
if filename != filename_:
error = 'Changes should be made to one ' \
'file at a time, detected changes ' \
'to {0} and {1}'.format(filename, filename_)
raise ValueError(error)
filename = filename_
except (ValueError, IndexError) as err:
log.error(err)
if 'error' not in locals():
error = 'Invalid formatted command, ' \
'see debug log for details: {0}' \
.format(change_)
else:
error = six.text_type(err)
raise ValueError(error)
filename = _workout_filename(filename)
return filename
|
saltstack/salt
|
salt/modules/redismod.py
|
_connect
|
python
|
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
|
Returns an instance of the redis client
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L45-L58
| null |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
_sconnect
|
python
|
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
|
Returns an instance of the redis client
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L61-L72
| null |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
bgrewriteaof
|
python
|
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
|
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L75-L86
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
bgsave
|
python
|
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
|
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L89-L100
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
config_get
|
python
|
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
|
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L103-L115
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
config_set
|
python
|
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
|
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L118-L129
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
dbsize
|
python
|
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
|
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L132-L143
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
delete
|
python
|
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
|
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L146-L163
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
exists
|
python
|
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
|
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L166-L177
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
expire
|
python
|
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
|
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L180-L191
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
expireat
|
python
|
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
|
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L194-L205
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
flushall
|
python
|
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
|
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L208-L219
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
flushdb
|
python
|
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
|
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L222-L233
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
get_key
|
python
|
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
|
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L236-L247
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
hexists
|
python
|
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
|
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L270-L283
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
hgetall
|
python
|
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
|
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L300-L311
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
hincrby
|
python
|
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
|
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L314-L327
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
hlen
|
python
|
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
|
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L346-L359
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
hmget
|
python
|
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
|
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L362-L379
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
hmset
|
python
|
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
|
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L382-L399
|
[
"def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n",
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
hset
|
python
|
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
|
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L402-L415
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
hvals
|
python
|
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
|
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L434-L447
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
hscan
|
python
|
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
|
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L450-L463
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
info
|
python
|
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
|
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L466-L477
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
keys
|
python
|
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
|
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L480-L492
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
key_type
|
python
|
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
|
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L495-L506
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
lastsave
|
python
|
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
|
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L509-L526
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
saltstack/salt
|
salt/modules/redismod.py
|
llen
|
python
|
def llen(key, host=None, port=None, db=None, password=None):
'''
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
'''
server = _connect(host, port, db, password)
return server.llen(key)
|
Get the length of a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.llen foo_list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L529-L540
|
[
"def _connect(host=None, port=None, db=None, password=None):\n '''\n Returns an instance of the redis client\n '''\n if not host:\n host = __salt__['config.option']('redis.host')\n if not port:\n port = __salt__['config.option']('redis.port')\n if not db:\n db = __salt__['config.option']('redis.db')\n if not password:\n password = __salt__['config.option']('redis.password')\n\n return redis.StrictRedis(host, port, db, password, decode_responses=True)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide redis functionality to Salt
.. versionadded:: 2014.7.0
:configuration: This module requires the redis python module and uses the
following defaults which may be overridden in the minion configuration:
.. code-block:: yaml
redis.host: 'salt'
redis.port: 6379
redis.db: 0
redis.password: None
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
from salt.ext.six.moves import zip
from salt.ext import six
from datetime import datetime
import salt.utils.args
# Import third party libs
try:
import redis
HAS_REDIS = True
except ImportError:
HAS_REDIS = False
__virtualname__ = 'redis'
def __virtual__():
'''
Only load this module if redis python module is installed
'''
if HAS_REDIS:
return __virtualname__
else:
return (False, 'The redis execution module failed to load: the redis python library is not available.')
def _connect(host=None, port=None, db=None, password=None):
'''
Returns an instance of the redis client
'''
if not host:
host = __salt__['config.option']('redis.host')
if not port:
port = __salt__['config.option']('redis.port')
if not db:
db = __salt__['config.option']('redis.db')
if not password:
password = __salt__['config.option']('redis.password')
return redis.StrictRedis(host, port, db, password, decode_responses=True)
def _sconnect(host=None, port=None, password=None):
'''
Returns an instance of the redis client
'''
if host is None:
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if port is None:
port = __salt__['config.option']('redis_sentinel.port', 26379)
if password is None:
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password, decode_responses=True)
def bgrewriteaof(host=None, port=None, db=None, password=None):
'''
Asynchronously rewrite the append-only file
CLI Example:
.. code-block:: bash
salt '*' redis.bgrewriteaof
'''
server = _connect(host, port, db, password)
return server.bgrewriteaof()
def bgsave(host=None, port=None, db=None, password=None):
'''
Asynchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.bgsave
'''
server = _connect(host, port, db, password)
return server.bgsave()
def config_get(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_get
salt '*' redis.config_get port
'''
server = _connect(host, port, db, password)
return server.config_get(pattern)
def config_set(name, value, host=None, port=None, db=None, password=None):
'''
Set redis server configuration values
CLI Example:
.. code-block:: bash
salt '*' redis.config_set masterauth luv_kittens
'''
server = _connect(host, port, db, password)
return server.config_set(name, value)
def dbsize(host=None, port=None, db=None, password=None):
'''
Return the number of keys in the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.dbsize
'''
server = _connect(host, port, db, password)
return server.dbsize()
def delete(*keys, **connection_args):
'''
Deletes the keys from redis, returns number of keys deleted
CLI Example:
.. code-block:: bash
salt '*' redis.delete foo
'''
# Get connection args from keywords if set
conn_args = {}
for arg in ['host', 'port', 'db', 'password']:
if arg in connection_args:
conn_args[arg] = connection_args[arg]
server = _connect(**conn_args)
return server.delete(*keys)
def exists(key, host=None, port=None, db=None, password=None):
'''
Return true if the key exists in redis
CLI Example:
.. code-block:: bash
salt '*' redis.exists foo
'''
server = _connect(host, port, db, password)
return server.exists(key)
def expire(key, seconds, host=None, port=None, db=None, password=None):
'''
Set a keys time to live in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.expire foo 300
'''
server = _connect(host, port, db, password)
return server.expire(key, seconds)
def expireat(key, timestamp, host=None, port=None, db=None, password=None):
'''
Set a keys expire at given UNIX time
CLI Example:
.. code-block:: bash
salt '*' redis.expireat foo 1400000000
'''
server = _connect(host, port, db, password)
return server.expireat(key, timestamp)
def flushall(host=None, port=None, db=None, password=None):
'''
Remove all keys from all databases
CLI Example:
.. code-block:: bash
salt '*' redis.flushall
'''
server = _connect(host, port, db, password)
return server.flushall()
def flushdb(host=None, port=None, db=None, password=None):
'''
Remove all keys from the selected database
CLI Example:
.. code-block:: bash
salt '*' redis.flushdb
'''
server = _connect(host, port, db, password)
return server.flushdb()
def get_key(key, host=None, port=None, db=None, password=None):
'''
Get redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.get_key foo
'''
server = _connect(host, port, db, password)
return server.get(key)
def hdel(key, *fields, **options):
'''
Delete one of more hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hdel foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hdel(key, *fields)
def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hexists(key, field)
def hget(key, field, host=None, port=None, db=None, password=None):
'''
Get specific field value from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hget foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.hget(key, field)
def hgetall(key, host=None, port=None, db=None, password=None):
'''
Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash
'''
server = _connect(host, port, db, password)
return server.hgetall(key)
def hincrby(key, field, increment=1, host=None, port=None, db=None, password=None):
'''
Increment the integer value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrby foo_hash bar_field 5
'''
server = _connect(host, port, db, password)
return server.hincrby(key, field, amount=increment)
def hincrbyfloat(key, field, increment=1.0, host=None, port=None, db=None, password=None):
'''
Increment the float value of a hash field by the given number.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hincrbyfloat foo_hash bar_field 5.17
'''
server = _connect(host, port, db, password)
return server.hincrbyfloat(key, field, amount=increment)
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key)
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
database = options.get('db', None)
password = options.get('password', None)
server = _connect(host, port, database, password)
return server.hmget(key, *fields)
def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop('port', None)
database = fieldsvals.pop('db', None)
password = fieldsvals.pop('password', None)
server = _connect(host, port, database, password)
return server.hmset(key, salt.utils.args.clean_kwargs(**fieldsvals))
def hset(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hset foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hset(key, field, value)
def hsetnx(key, field, value, host=None, port=None, db=None, password=None):
'''
Set the value of a hash field only if the field does not exist.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hsetnx foo_hash bar_field bar_value
'''
server = _connect(host, port, db, password)
return server.hsetnx(key, field, value)
def hvals(key, host=None, port=None, db=None, password=None):
'''
Return all the values in a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hvals foo_hash bar_field1 bar_value1
'''
server = _connect(host, port, db, password)
return server.hvals(key)
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None):
'''
Incrementally iterate hash fields and associated values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hscan foo_hash match='field_prefix_*' count=1
'''
server = _connect(host, port, db, password)
return server.hscan(key, cursor=cursor, match=match, count=count)
def info(host=None, port=None, db=None, password=None):
'''
Get information and statistics about the server
CLI Example:
.. code-block:: bash
salt '*' redis.info
'''
server = _connect(host, port, db, password)
return server.info()
def keys(pattern='*', host=None, port=None, db=None, password=None):
'''
Get redis keys, supports glob style patterns
CLI Example:
.. code-block:: bash
salt '*' redis.keys
salt '*' redis.keys test*
'''
server = _connect(host, port, db, password)
return server.keys(pattern)
def key_type(key, host=None, port=None, db=None, password=None):
'''
Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo
'''
server = _connect(host, port, db, password)
return server.type(key)
def lastsave(host=None, port=None, db=None, password=None):
'''
Get the UNIX time in seconds of the last successful save to disk
CLI Example:
.. code-block:: bash
salt '*' redis.lastsave
'''
# Use of %s to get the timestamp is not supported by Python. The reason it
# works is because it's passed to the system strftime which may not support
# it. See: https://stackoverflow.com/a/11743262
server = _connect(host, port, db, password)
if six.PY2:
return int((server.lastsave() - datetime(1970, 1, 1)).total_seconds())
else:
return int(server.lastsave().timestamp())
def lrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a list in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.lrange foo_list 0 10
'''
server = _connect(host, port, db, password)
return server.lrange(key, start, stop)
def ping(host=None, port=None, db=None, password=None):
'''
Ping the server, returns False on connection errors
CLI Example:
.. code-block:: bash
salt '*' redis.ping
'''
server = _connect(host, port, db, password)
try:
return server.ping()
except redis.ConnectionError:
return False
def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save()
def set_key(key, value, host=None, port=None, db=None, password=None):
'''
Set redis key value
CLI Example:
.. code-block:: bash
salt '*' redis.set_key foo bar
'''
server = _connect(host, port, db, password)
return server.set(key, value)
def shutdown(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk and then shut down the server
CLI Example:
.. code-block:: bash
salt '*' redis.shutdown
'''
server = _connect(host, port, db, password)
try:
# Return false if unable to ping server
server.ping()
except redis.ConnectionError:
return False
server.shutdown()
try:
# This should fail now if the server is shutdown, which we want
server.ping()
except redis.ConnectionError:
return True
return False
def slaveof(master_host=None, master_port=None, host=None, port=None, db=None,
password=None):
'''
Make the server a slave of another instance, or promote it as master
CLI Example:
.. code-block:: bash
# Become slave of redis-n01.example.com:6379
salt '*' redis.slaveof redis-n01.example.com 6379
salt '*' redis.slaveof redis-n01.example.com
# Become master
salt '*' redis.slaveof
'''
if master_host and not master_port:
master_port = 6379
server = _connect(host, port, db, password)
return server.slaveof(master_host, master_port)
def smembers(key, host=None, port=None, db=None, password=None):
'''
Get members in a Redis set
CLI Example:
.. code-block:: bash
salt '*' redis.smembers foo_set
'''
server = _connect(host, port, db, password)
return list(server.smembers(key))
def time(host=None, port=None, db=None, password=None):
'''
Return the current server UNIX time in seconds
CLI Example:
.. code-block:: bash
salt '*' redis.time
'''
server = _connect(host, port, db, password)
return server.time()[0]
def zcard(key, host=None, port=None, db=None, password=None):
'''
Get the length of a sorted set in Redis
CLI Example:
.. code-block:: bash
salt '*' redis.zcard foo_sorted
'''
server = _connect(host, port, db, password)
return server.zcard(key)
def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(key, start, stop)
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.sentinel_get_master_addr_by_name(master)
return dict(list(zip(('master_host', 'master_port'), ret)))
def get_master_ip(host=None, port=None, password=None):
'''
Get host information about slave
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.get_master_ip
'''
server = _connect(host, port, password)
srv_info = server.info()
ret = (srv_info.get('master_host', ''), srv_info.get('master_port', ''))
return dict(list(zip(('master_host', 'master_port'), ret)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.