text stringlengths 81 112k |
|---|
Given the cache directory, return the directory that process data is
stored in, creating it if it doesn't exist.
The following optional Keyword Arguments are handled:
mode: which is anything os.makedir would accept as mode.
uid: the uid to set, if not set, or it is None or -1 no changes are
m... |
Detect the args and kwargs that need to be passed to a function call, and
check them against what was passed.
def load_args_and_kwargs(func, args, data=None, ignore_invalid=False):
'''
Detect the args and kwargs that need to be passed to a function call, and
check them against what was passed.
'''
... |
Evaluate master function if master type is 'func'
and save it result in opts['master']
def eval_master_func(opts):
'''
Evaluate master function if master type is 'func'
and save it result in opts['master']
'''
if '__master_func_evaluated' not in opts:
# split module and function and try... |
Centralized master event function which will return event type based on event_map
def master_event(type, master=None):
'''
Centralized master event function which will return event type based on event_map
'''
event_map = {'connected': '__master_connected',
'disconnected': '__master_dis... |
Evaluate all of the configured beacons, grab the config again in case
the pillar or grains changed
def process_beacons(self, functions):
'''
Evaluate all of the configured beacons, grab the config again in case
the pillar or grains changed
'''
if 'config.merge' in functi... |
Evaluates and returns a tuple of the current master address and the pub_channel.
In standard mode, just creates a pub_channel with the given master address.
With master_type=func evaluates the current master address from the given
module and then creates a pub_channel.
With master_typ... |
Discover master(s) and decide where to connect, if SSDP is around.
This modifies the configuration on the fly.
:return:
def _discover_masters(self):
'''
Discover master(s) and decide where to connect, if SSDP is around.
This modifies the configuration on the fly.
:return... |
Based on the minion configuration, either return a randomized timer or
just return the value of the return_retry_timer.
def _return_retry_timer(self):
'''
Based on the minion configuration, either return a randomized timer or
just return the value of the return_retry_timer.
'''
... |
Tell the minion to reload the execution modules
CLI Example:
.. code-block:: bash
salt '*' sys.reload_modules
def gen_modules(self, initial_load=False):
'''
Tell the minion to reload the execution modules
CLI Example:
.. code-block:: bash
sa... |
Tell the minion to reload the execution modules
CLI Example:
.. code-block:: bash
salt '*' sys.reload_modules
def gen_modules(self, initial_load=False):
'''
Tell the minion to reload the execution modules
CLI Example:
.. code-block:: bash
sa... |
Helper function to return the correct type of object
def _create_minion_object(self, opts, timeout, safe,
io_loop=None, loaded_base_name=None,
jid_queue=None):
'''
Helper function to return the correct type of object
'''
return... |
Spawn all the coroutines which will sign in to masters
def _spawn_minions(self, timeout=60):
'''
Spawn all the coroutines which will sign in to masters
'''
# Run masters discovery over SSDP. This may modify the whole configuration,
# depending of the networking and sets of maste... |
Create a minion, and asynchronously connect it to a master
def _connect_minion(self, minion):
'''
Create a minion, and asynchronously connect it to a master
'''
auth_wait = minion.opts['acceptance_wait_time']
failed = False
while True:
if failed:
... |
Block until we are connected to a master
def sync_connect_master(self, timeout=None, failed=False):
'''
Block until we are connected to a master
'''
self._sync_connect_master_success = False
log.debug("sync_connect_master")
def on_connect_master_future_done(future):
... |
Return a future which will complete when you are connected to a master
def connect_master(self, failed=False):
'''
Return a future which will complete when you are connected to a master
'''
master, self.pub_channel = yield self.eval_master(self.opts, self.timeout, self.safe, failed)
... |
Function to finish init after connecting to a master
This is primarily loading modules, pillars, etc. (since they need
to know which master they connected to)
If this function is changed, please check ProxyMinion._post_master_init
to see if those changes need to be propagated.
... |
Returns a copy of the opts with key bits stripped out
def _prep_mod_opts(self):
'''
Returns a copy of the opts with key bits stripped out
'''
mod_opts = {}
for key, val in six.iteritems(self.opts):
if key == 'logger':
continue
mod_opts[key... |
Return the functions and the returners loaded up from the loader
module
def _load_modules(self, force_refresh=False, notify=False, grains=None, opts=None):
'''
Return the functions and the returners loaded up from the loader
module
'''
opt_in = True
if not opts:
... |
Fire an event on the master, or drop message if unable to send.
def _fire_master(self, data=None, tag=None, events=None, pretag=None, timeout=60, sync=True, timeout_handler=None):
'''
Fire an event on the master, or drop message if unable to send.
'''
load = {'id': self.opts['id'],
... |
Return a single context manager for the minion's data
def ctx(self):
'''
Return a single context manager for the minion's data
'''
if six.PY2:
return contextlib.nested(
self.functions.context_dict.clone(),
self.returners.context_dict.clone(),
... |
This method should be used as a threading target, start the actual
minion side execution.
def _thread_return(cls, minion_instance, opts, data):
'''
This method should be used as a threading target, start the actual
minion side execution.
'''
fn_ = os.path.join(minion_ins... |
This method should be used as a threading target, start the actual
minion side execution.
def _thread_multi_return(cls, minion_instance, opts, data):
'''
This method should be used as a threading target, start the actual
minion side execution.
'''
fn_ = os.path.join(mini... |
Return the data from the executed command to the master server
def _return_pub_multi(self, rets, ret_cmd='_return', timeout=60, sync=True):
'''
Return the data from the executed command to the master server
'''
if not isinstance(rets, list):
rets = [rets]
jids = {}
... |
Execute a state run based on information set in the minion config file
def _state_run(self):
'''
Execute a state run based on information set in the minion config file
'''
if self.opts['startup_states']:
if self.opts.get('master_type', 'str') == 'disable' and \
... |
Create a loop that will fire a pillar refresh to inform a master about a change in the grains of this minion
:param refresh_interval_in_minutes:
:return: None
def _refresh_grains_watcher(self, refresh_interval_in_minutes):
'''
Create a loop that will fire a pillar refresh to inform a ma... |
Refresh the functions and returners.
def module_refresh(self, force_refresh=False, notify=False):
'''
Refresh the functions and returners.
'''
log.debug('Refreshing modules. Notify=%s', notify)
self.functions, self.returners, _, self.executors = self._load_modules(force_refresh,... |
Refresh the functions and returners.
def beacons_refresh(self):
'''
Refresh the functions and returners.
'''
log.debug('Refreshing beacons.')
self.beacons = salt.beacons.Beacon(self.opts, self.functions) |
Refresh the matchers
def matchers_refresh(self):
'''
Refresh the matchers
'''
log.debug('Refreshing matchers.')
self.matchers = salt.loader.matchers(self.opts) |
Refresh the pillar
def pillar_refresh(self, force_refresh=False, notify=False):
'''
Refresh the pillar
'''
if self.connected:
log.debug('Refreshing pillar. Notify: %s', notify)
async_pillar = salt.pillar.get_async_pillar(
self.opts,
... |
Refresh the functions and returners.
def manage_schedule(self, tag, data):
'''
Refresh the functions and returners.
'''
func = data.get('func', None)
name = data.get('name', None)
schedule = data.get('schedule', None)
where = data.get('where', None)
persi... |
Manage Beacons
def manage_beacons(self, tag, data):
'''
Manage Beacons
'''
func = data.get('func', None)
name = data.get('name', None)
beacon_data = data.get('beacon_data', None)
include_pillar = data.get('include_pillar', None)
include_opts = data.get('i... |
Set the salt-minion main process environment according to
the data contained in the minion event data
def environ_setenv(self, tag, data):
'''
Set the salt-minion main process environment according to
the data contained in the minion event data
'''
environ = data.get('en... |
Set the minion running flag and issue the appropriate warnings if
the minion cannot be started or is already running
def _pre_tune(self):
'''
Set the minion running flag and issue the appropriate warnings if
the minion cannot be started or is already running
'''
if self.... |
Send mine data to the master
def _mine_send(self, tag, data):
'''
Send mine data to the master
'''
channel = salt.transport.client.ReqChannel.factory(self.opts)
data['tok'] = self.tok
try:
ret = channel.send(data)
return ret
except SaltReq... |
Handle a module_refresh event
def _handle_tag_module_refresh(self, tag, data):
'''
Handle a module_refresh event
'''
self.module_refresh(
force_refresh=data.get('force_refresh', False),
notify=data.get('notify', False)
) |
Handle a pillar_refresh event
def _handle_tag_pillar_refresh(self, tag, data):
'''
Handle a pillar_refresh event
'''
yield self.pillar_refresh(
force_refresh=data.get('force_refresh', False),
notify=data.get('notify', False)
) |
Handle a grains_refresh event
def _handle_tag_grains_refresh(self, tag, data):
'''
Handle a grains_refresh event
'''
if (data.get('force_refresh', False) or
self.grains_cache != self.opts['grains']):
self.pillar_refresh(force_refresh=True)
self.gr... |
Handle a fire_master event
def _handle_tag_fire_master(self, tag, data):
'''
Handle a fire_master event
'''
if self.connected:
log.debug('Forwarding master event tag=%s', data['tag'])
self._fire_master(data['data'], data['tag'], data['events'], data['pretag']) |
Handle a master_disconnected_failback event
def _handle_tag_master_disconnected_failback(self, tag, data):
'''
Handle a master_disconnected_failback event
'''
# if the master disconnect event is for a different master, raise an exception
if tag.startswith(master_event(type='disc... |
Handle a master_connected event
def _handle_tag_master_connected(self, tag, data):
'''
Handle a master_connected event
'''
# handle this event only once. otherwise it will pollute the log
# also if master type is failover all the reconnection work is done
# by `disconnec... |
Handle a _schedule_return event
def _handle_tag_schedule_return(self, tag, data):
'''
Handle a _schedule_return event
'''
# reporting current connection with master
if data['schedule'].startswith(master_event(type='alive', master='')):
if data['return']:
... |
Handle a _salt_error event
def _handle_tag_salt_error(self, tag, data):
'''
Handle a _salt_error event
'''
if self.connected:
log.debug('Forwarding salt error event tag=%s', tag)
self._fire_master(data, tag) |
Handle a salt_auth_creds event
def _handle_tag_salt_auth_creds(self, tag, data):
'''
Handle a salt_auth_creds event
'''
key = tuple(data['key'])
log.debug(
'Updating auth data for %s: %s -> %s',
key, salt.crypt.AsyncAuth.creds_map.get(key), data['creds']
... |
Handle an event from the epull_sock (all local minion events)
def handle_event(self, package):
'''
Handle an event from the epull_sock (all local minion events)
'''
if not self.ready:
raise tornado.gen.Return()
tag, data = salt.utils.event.SaltEvent.unpack(package)
... |
Fallback cleanup routines, attempting to fix leaked processes, threads, etc.
def _fallback_cleanups(self):
'''
Fallback cleanup routines, attempting to fix leaked processes, threads, etc.
'''
# Add an extra fallback in case a forked process leaks through
multiprocessing.active_c... |
Set up the core minion attributes.
This is safe to call multiple times.
def _setup_core(self):
'''
Set up the core minion attributes.
This is safe to call multiple times.
'''
if not self.ready:
# First call. Initialize.
self.functions, self.return... |
Set up the beacons.
This is safe to call multiple times.
def setup_beacons(self, before_connect=False):
'''
Set up the beacons.
This is safe to call multiple times.
'''
self._setup_core()
loop_interval = self.opts['loop_interval']
new_periodic_callbacks ... |
Set up the scheduler.
This is safe to call multiple times.
def setup_scheduler(self, before_connect=False):
'''
Set up the scheduler.
This is safe to call multiple times.
'''
self._setup_core()
loop_interval = self.opts['loop_interval']
new_periodic_call... |
Lock onto the publisher. This is the main event loop for the minion
:rtype : None
def tune_in(self, start=True):
'''
Lock onto the publisher. This is the main event loop for the minion
:rtype : None
'''
self._pre_tune()
log.debug('Minion \'%s\' trying to tune in... |
Tear down the minion
def destroy(self):
'''
Tear down the minion
'''
if self._running is False:
return
self._running = False
if hasattr(self, 'schedule'):
del self.schedule
if hasattr(self, 'pub_channel') and self.pub_channel is not None:... |
Override this method if you wish to handle the decoded data
differently.
def _handle_decoded_payload(self, data):
'''
Override this method if you wish to handle the decoded data
differently.
'''
# TODO: even do this??
data['to'] = int(data.get('to', self.opts['ti... |
Take the now clear load and forward it on to the client cmd
def syndic_cmd(self, data):
'''
Take the now clear load and forward it on to the client cmd
'''
# Set up default tgt_type
if 'tgt_type' not in data:
data['tgt_type'] = 'glob'
kwargs = {}
# o... |
Executes the tune_in sequence but omits extra logging and the
management of the event bus assuming that these are handled outside
the tune_in sequence
def tune_in_no_block(self):
'''
Executes the tune_in sequence but omits extra logging and the
management of the event bus assumi... |
Tear down the syndic minion
def destroy(self):
'''
Tear down the syndic minion
'''
# We borrowed the local clients poller so give it back before
# it's destroyed. Reset the local poller reference.
super(Syndic, self).destroy()
if hasattr(self, 'local'):
... |
Spawn all the coroutines which will sign in the syndics
def _spawn_syndics(self):
'''
Spawn all the coroutines which will sign in the syndics
'''
self._syndics = OrderedDict() # mapping of opts['master'] -> syndic
masters = self.opts['master']
if not isinstance(masters,... |
Create a syndic, and asynchronously connect it to a master
def _connect_syndic(self, opts):
'''
Create a syndic, and asynchronously connect it to a master
'''
auth_wait = opts['acceptance_wait_time']
failed = False
while True:
if failed:
if au... |
Mark a master as dead. This will start the sign-in routine
def _mark_master_dead(self, master):
'''
Mark a master as dead. This will start the sign-in routine
'''
# if its connected, mark it dead
if self._syndics[master].done():
syndic = self._syndics[master].result(... |
Wrapper to call a given func on a syndic, best effort to get the one you asked for
def _call_syndic(self, func, args=(), kwargs=None, master_id=None):
'''
Wrapper to call a given func on a syndic, best effort to get the one you asked for
'''
if kwargs is None:
kwargs = {}
... |
Wrapper to call the '_return_pub_multi' a syndic, best effort to get the one you asked for
def _return_pub_syndic(self, values, master_id=None):
'''
Wrapper to call the '_return_pub_multi' a syndic, best effort to get the one you asked for
'''
func = '_return_pub_multi'
for mast... |
Iterate (in order) over your options for master
def iter_master_options(self, master_id=None):
'''
Iterate (in order) over your options for master
'''
masters = list(self._syndics.keys())
if self.opts['syndic_failover'] == 'random':
shuffle(masters)
if master... |
Lock onto the publisher. This is the main event loop for the syndic
def tune_in(self):
'''
Lock onto the publisher. This is the main event loop for the syndic
'''
self._spawn_syndics()
# Instantiate the local client
self.local = salt.client.get_local_client(
... |
Function to finish init after connecting to a master
This is primarily loading modules, pillars, etc. (since they need
to know which master they connected to)
If this function is changed, please check Minion._post_master_init
to see if those changes need to be propagated.
Prox... |
Verify that the publication is valid and applies to this minion
def _target_load(self, load):
'''
Verify that the publication is valid and applies to this minion
'''
mp_call = _metaproxy_call(self.opts, 'target_load')
return mp_call(self, load) |
Tell the minion to reload the execution modules
CLI Example:
.. code-block:: bash
salt '*' sys.reload_modules
def gen_modules(self, initial_load=False):
'''
Tell the minion to reload the execution modules
CLI Example:
.. code-block:: bash
sa... |
Return a tuple containing the comparison operator and the version. If no
comparison operator was passed, the comparison is assumed to be an "equals"
comparison, and "==" will be the operator returned.
def _get_comparison_spec(pkgver):
'''
Return a tuple containing the comparison operator and the versio... |
Returns a list of two-tuples containing (operator, version).
def _parse_version_string(version_conditions_string):
'''
Returns a list of two-tuples containing (operator, version).
'''
result = []
version_conditions_string = version_conditions_string.strip()
if not version_conditions_string:
... |
Returns True if any of the installed versions match the specified version conditions,
otherwise returns False.
installed_versions
The installed versions
version_conditions_string
The string containing all version conditions. E.G.
1.2.3-4
>=1.2.3-4
>=1.2.3-4, <2.3.4-... |
Returns True if any of the installed versions match the specified version,
otherwise returns False
def _fulfills_version_spec(versions, oper, desired_version,
ignore_epoch=False):
'''
Returns True if any of the installed versions match the specified version,
otherwise returns... |
Find packages which are marked to be purged but can't yet be removed
because they are dependencies for other installed packages. These are the
packages which will need to be 'unpurged' because they are part of
pkg.installed states. This really just applies to Debian-based Linuxes.
def _find_unpurge_targets... |
Inspect the arguments to pkg.downloaded and discover what packages need to
be downloaded. Return a dict of packages to download.
def _find_download_targets(name=None,
version=None,
pkgs=None,
normalize=True,
... |
Inspect the arguments to pkg.patch_installed and discover what advisory
patches need to be installed. Return a dict of advisory patches to install.
def _find_advisory_targets(name=None,
advisory_ids=None,
**kwargs):
'''
Inspect the arguments to pkg.patc... |
Inspect the arguments to pkg.removed and discover what packages need to
be removed. Return a dict of packages to remove.
def _find_remove_targets(name=None,
version=None,
pkgs=None,
normalize=True,
ignore_epoch=Fals... |
Inspect the arguments to pkg.installed and discover what packages need to
be installed. Return a dict of desired packages
def _find_install_targets(name=None,
version=None,
pkgs=None,
sources=None,
skip_suggesti... |
Determine whether or not the installed packages match what was requested in
the SLS file.
def _verify_install(desired, new_pkgs, ignore_epoch=False, new_caps=None):
'''
Determine whether or not the installed packages match what was requested in
the SLS file.
'''
ok = []
failed = []
if n... |
Helper function that retrieves and nicely formats the desired pkg (and
version if specified) so that helpful information can be printed in the
comment for the state.
def _get_desired_pkg(name, desired):
'''
Helper function that retrieves and nicely formats the desired pkg (and
version if specified)... |
Perform platform-specific checks on desired packages
def _preflight_check(desired, fromrepo, **kwargs):
'''
Perform platform-specific checks on desired packages
'''
if 'pkg.check_db' not in __salt__:
return {}
ret = {'suggest': {}, 'no_suggest': []}
pkginfo = __salt__['pkg.check_db'](
... |
Serialize obj and format for output
def _nested_output(obj):
'''
Serialize obj and format for output
'''
nested.__opts__ = __opts__
ret = nested.output(obj).rstrip()
return ret |
Resolve capabilities in ``pkgs`` and exchange them with real package
names, when the result is distinct.
This feature can be turned on while setting the paramter
``resolve_capabilities`` to True.
Return the input dictionary with replaced capability names and as
second return value a bool which say ... |
Ensure that the package is installed, and that it is the correct version
(if specified).
:param str name:
The name of the package to be installed. This parameter is ignored if
either "pkgs" or "sources" is used. Additionally, please note that this
option can only be used to install pack... |
.. versionadded:: 2017.7.0
Ensure that the package is downloaded, and that it is the correct version
(if specified).
Currently supported for the following pkg providers:
:mod:`yumpkg <salt.modules.yumpkg>` and :mod:`zypper <salt.modules.zypper>`
:param str name:
The name of the package to... |
.. versionadded:: 2017.7.0
Ensure that packages related to certain advisory ids are installed.
Currently supported for the following pkg providers:
:mod:`yumpkg <salt.modules.yumpkg>` and :mod:`zypper <salt.modules.zypper>`
CLI Example:
.. code-block:: yaml
issue-foo-fixed:
pk... |
.. versionadded:: 2017.7.0
Ensure that packages related to certain advisory ids are downloaded.
Currently supported for the following pkg providers:
:mod:`yumpkg <salt.modules.yumpkg>` and :mod:`zypper <salt.modules.zypper>`
CLI Example:
.. code-block:: yaml
preparing-to-fix-issues:
... |
Common function for package removal
def _uninstall(
action='remove',
name=None,
version=None,
pkgs=None,
normalize=True,
ignore_epoch=False,
**kwargs):
'''
Common function for package removal
'''
if action not in ('remove', 'purge'):
return {'name': name,
... |
Verify that a package is not installed, calling ``pkg.purge`` if necessary
to purge the package. All configuration files are also removed.
name
The name of the package to be purged.
version
The version of the package that should be removed. Don't do anything if
the package is insta... |
.. versionadded:: 2014.7.0
.. versionchanged:: 2018.3.0
Added support for the ``pkgin`` provider.
Verify that the system is completely up to date.
name
The name has no functional value and is only used as a tracking
reference
refresh
refresh the package database befor... |
.. versionadded:: 2015.8.0
.. versionchanged:: 2016.11.0
Added support in :mod:`pacman <salt.modules.pacman>`
Ensure that an entire package group is installed. This state is currently
only supported for the :mod:`yum <salt.modules.yumpkg>` and :mod:`pacman <salt.modules.pacman>`
package manage... |
Set a flag to tell the install functions to refresh the package database.
This ensures that the package database is refreshed only once during
a state run significantly improving the speed of package management
during a state run.
It sets a flag for a number of reasons, primarily due to timeline logic.... |
Install/reinstall a package based on a watch requisite
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
def mod_watch(name, **k... |
Ensures that the named port exists on bridge, eventually creates it.
Args:
name: The name of the port.
bridge: The name of the bridge.
tunnel_type: Optional type of interface to create, currently supports: vlan, vxlan and gre.
id: Optional tunnel's key.
remote: Remote endpoi... |
Ensures that the named port exists on bridge, eventually deletes it.
If bridge is not set, port is removed from whatever bridge contains it.
Args:
name: The name of the port.
bridge: The name of the bridge.
def absent(name, bridge=None):
'''
Ensures that the named port exists on bridg... |
Call out to system_profiler. Return a dictionary
of the stuff we are interested in.
def _call_system_profiler(datatype):
'''
Call out to system_profiler. Return a dictionary
of the stuff we are interested in.
'''
p = subprocess.Popen(
[PROFILER_BINARY, '-detailLevel', 'full',
... |
Return the results of a call to
``system_profiler -xml -detail full SPInstallHistoryDataType``
as a dictionary. Top-level keys of the dictionary
are the names of each set of install receipts, since
there can be multiple receipts with the same name.
Contents of each key are a list of dictionaries.
... |
Create alias and enforce collection list.
Use the solrcloud module to get alias members and set them.
You can pass additional arguments that will be forwarded to http.query
name
The collection name
collections
list of collections to include in the alias
def alias(name, collections, *... |
Create collection and enforce options.
Use the solrcloud module to get collection parameters.
You can pass additional arguments that will be forwarded to http.query
name
The collection name
options : {}
options to ensure
def collection(name, options=None, **kwargs):
'''
Creat... |
Consul object method function to construct and execute on the API URL.
:param api_url: The Consul api url.
:param api_version The Consul api version
:param function: The Consul api function to perform.
:param method: The HTTP method, e.g. GET or POST.
:param data: The data to be... |
List keys in Consul
:param consul_url: The Consul server URL.
:param key: The key to use as the starting point for the list.
:return: The list of keys.
CLI Example:
.. code-block:: bash
salt '*' consul.list
salt '*' consul.list key='web'
def list_(consul_url=None, token=None, ke... |
Get key from Consul
:param consul_url: The Consul server URL.
:param key: The key to use as the starting point for the list.
:param recurse: Return values recursively beginning at the value of key.
:param decode: By default values are stored as Base64 encoded values,
decode will retu... |
Put values into Consul
:param consul_url: The Consul server URL.
:param key: The key to use as the starting point for the list.
:param value: The value to set the key to.
:param flags: This can be used to specify an unsigned value
between 0 and 2^64-1. Clients can choose to use
... |
Delete values from Consul
:param consul_url: The Consul server URL.
:param key: The key to use as the starting point for the list.
:param recurse: Delete values recursively beginning at the value of key.
:param cas: This flag is used to turn the DELETE into
a Check-And-Set operation.
... |
Returns the checks the local agent is managing
:param consul_url: The Consul server URL.
:return: Returns the checks the local agent is managing
CLI Example:
.. code-block:: bash
salt '*' consul.agent_checks
def agent_checks(consul_url=None, token=None):
'''
Returns the checks the l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.