INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Only succeed if the value in the given register location contains the given value | def contains(name,
value,
count_lt=None,
count_lte=None,
count_eq=None,
count_gte=None,
count_gt=None,
count_ne=None):
'''
Only succeed if the value in the given register location contains
the given value
USAGE:
... |
Chekcs for a specific event match and returns result True if the match happens | def event(name):
'''
Chekcs for a specific event match and returns result True if the match
happens
USAGE:
.. code-block:: yaml
salt/foo/*/bar:
check.event
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
... |
Only succeed if length of the given register location is greater than the given value. | def len_gt(name, value):
'''
Only succeed if length of the given register location is greater than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test... |
Configures users on network devices. | def set_users(users, test=False, commit=True, **kwargs): # pylint: disable=unused-argument
'''
Configures users on network devices.
:param users: Dictionary formatted as the output of the function config()
:param test: Dry run? If set as True, will apply the config, discard and
return the ch... |
Convert the virtualbox config file values for clone_mode into the integers the API requires | def map_clonemode(vm_info):
"""
Convert the virtualbox config file values for clone_mode into the integers the API requires
"""
mode_map = {
'state': 0,
'child': 1,
'all': 2
}
if not vm_info:
return DEFAULT_CLONE_MODE
if 'clonemode' not in vm_info:
retur... |
Creates a virtual machine from the given VM information | def create(vm_info):
'''
Creates a virtual machine from the given VM information
This is what is used to request a virtual machine to be created by the
cloud provider, wait for it to become available, and then (optionally) log
in and install Salt on it.
Events fired:
This function fires t... |
All information available about all nodes should be returned in this function. The fields in the list_nodes () function should also be returned even if they would not normally be provided by the cloud provider. | def list_nodes_full(kwargs=None, call=None):
"""
All information available about all nodes should be returned in this function.
The fields in the list_nodes() function should also be returned,
even if they would not normally be provided by the cloud provider.
This is because some functions both wit... |
This function returns a list of nodes available on this cloud provider using the following fields: | def list_nodes(kwargs=None, call=None):
"""
This function returns a list of nodes available on this cloud provider, using the following fields:
id (str)
image (str)
size (str)
state (str)
private_ips (list)
public_ips (list)
No other fields should be returned in this function, and ... |
This function irreversibly destroys a virtual machine on the cloud provider. Before doing so it should fire an event on the Salt event bus. | def destroy(name, call=None):
"""
This function irreversibly destroys a virtual machine on the cloud provider.
Before doing so, it should fire an event on the Salt event bus.
The tag for this event is `salt/cloud/<vm name>/destroying`.
Once the virtual machine has been destroyed, another event is f... |
Start a machine. | def start(name, call=None):
'''
Start a machine.
@param name: Machine to start
@type name: str
@param call: Must be "action"
@type call: str
'''
if call != 'action':
raise SaltCloudSystemExit(
'The instance action must be called with -a or --action.'
)
lo... |
Stop a running machine. | def stop(name, call=None):
"""
Stop a running machine.
@param name: Machine to stop
@type name: str
@param call: Must be "action"
@type call: str
"""
if call != 'action':
raise SaltCloudSystemExit(
'The instance action must be called with -a or --action.'
)
... |
Show the details of an image | def show_image(kwargs, call=None):
"""
Show the details of an image
"""
if call != 'function':
raise SaltCloudSystemExit(
'The show_image action must be called with -f or --function.'
)
name = kwargs['image']
log.info("Showing image %s", name)
machine = vb_get_ma... |
Verify that a device is mapped | def mapped(name,
device,
keyfile=None,
opts=None,
config='/etc/crypttab',
persist=True,
immediate=False,
match_on='name'):
'''
Verify that a device is mapped
name
The name under which the device is to be mapped
device... |
Ensure that a device is unmapped | def unmapped(name,
config='/etc/crypttab',
persist=True,
immediate=False):
'''
Ensure that a device is unmapped
name
The name to ensure is not mapped
config
Set an alternative location for the crypttab, if the map is persistent,
Default is... |
Returns the compiled top data for pillar for a specific minion. If no minion is specified we use the first minion we find. | def show_top(minion=None, saltenv='base'):
'''
Returns the compiled top data for pillar for a specific minion. If no
minion is specified, we use the first minion we find.
CLI Example:
.. code-block:: bash
salt-run pillar.show_top
'''
id_, grains, _ = salt.utils.minions.get_minion... |
Returns the compiled pillar either of a specific minion or just the global available pillars. This function assumes that no minion has the id *. Function also accepts pillarenv as attribute in order to limit to a specific pillar branch of git | def show_pillar(minion='*', **kwargs):
'''
Returns the compiled pillar either of a specific minion
or just the global available pillars. This function assumes
that no minion has the id ``*``.
Function also accepts pillarenv as attribute in order to limit to a specific pillar branch of git
CLI E... |
Install RVM system - wide | def install(runas=None):
'''
Install RVM system-wide
runas
The user under which to run the rvm installer script. If not specified,
then it be run as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.install
'''
# RVM dependencies... |
Install a ruby implementation. | def install_ruby(ruby, runas=None, opts=None, env=None):
'''
Install a ruby implementation.
ruby
The version of ruby to install
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
env
Environment to... |
Reinstall a ruby implementation | def reinstall_ruby(ruby, runas=None, env=None):
'''
Reinstall a ruby implementation
ruby
The version of ruby to reinstall
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:... |
List all rvm - installed rubies | def list_(runas=None):
'''
List all rvm-installed rubies
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
.. code-block:: bash
salt '*' rvm.list
'''
rubies = []
output = _rvm(['... |
Install RVM wrapper scripts | def wrapper(ruby_string, wrapper_prefix, runas=None, *binaries):
'''
Install RVM wrapper scripts
ruby_string
Ruby/gemset to install wrappers for
wrapper_prefix
What to prepend to the name of the generated wrapper binaries
runas
The user under which to run rvm. If not speci... |
List all gemsets for the given ruby. | def gemset_list(ruby='default', runas=None):
'''
List all gemsets for the given ruby.
ruby : default
The ruby version for which to list the gemsets
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Ex... |
List all gemsets for all installed rubies. | def gemset_list_all(runas=None):
'''
List all gemsets for all installed rubies.
Note that you must have set a default ruby before this can work.
runas
The user under which to run rvm. If not specified, then rvm will be run
as the user under which Salt is running.
CLI Example:
... |
Execute a command in an RVM controlled environment. | def do(ruby, command, runas=None, cwd=None, env=None): # pylint: disable=C0103
'''
Execute a command in an RVM controlled environment.
ruby
Which ruby to use
command
The rvm command to execute
runas
The user under which to run rvm. If not specified, then rvm will be run
... |
Read a file on the file system ( relative to salt s base project dir ) | def parse_file(self, fpath):
'''
Read a file on the file system (relative to salt's base project dir)
:returns: A file-like object.
:raises IOError: If the file cannot be found or read.
'''
sdir = os.path.abspath(os.path.join(os.path.dirname(salt.__file__),
... |
Parse a string line - by - line delineating comments and code | def parse_lit(self, lines):
'''
Parse a string line-by-line delineating comments and code
:returns: An tuple of boolean/list-of-string pairs. True designates a
comment; False designates code.
'''
comment_char = '#' # TODO: move this into a directive option
co... |
Given a typical Salt SLS path ( e. g.: apache. vhosts. standard ) find the file on the file system and parse it | def parse_file(self, sls_path):
'''
Given a typical Salt SLS path (e.g.: apache.vhosts.standard), find the
file on the file system and parse it
'''
config = self.state.document.settings.env.config
formulas_dirs = config.formulas_dirs
fpath = sls_path.replace('.', ... |
Return the minions found by looking via pillar | def mmatch(expr, delimiter, greedy, opts=None):
'''
Return the minions found by looking via pillar
'''
if not opts:
opts = __opts__
ckminions = salt.utils.minions.CkMinions(opts)
return ckminions._check_compound_minions(expr, delimiter, greedy,
... |
Access/ write a SysFS attribute. If the attribute is a symlink it s destination is returned | def attr(key, value=None):
'''
Access/write a SysFS attribute.
If the attribute is a symlink, it's destination is returned
:return: value or bool
CLI example:
.. code-block:: bash
salt '*' sysfs.attr block/sda/queue/logical_block_size
'''
key = target(key)
if key is Fals... |
Write a SysFS attribute/ action | def write(key, value):
'''
Write a SysFS attribute/action
CLI example:
.. code-block:: bash
salt '*' sysfs.write devices/system/cpu/cpu0/cpufreq/scaling_governor 'performance'
'''
try:
key = target(key)
log.trace('Writing %s to %s', value, key)
with salt.utils.... |
Read from SysFS | def read(key, root=''):
'''
Read from SysFS
:param key: file or path in SysFS; if key is a list then root will be prefixed on each key
:return: the full (tree of) SysFS attributes under key
CLI example:
.. code-block:: bash
salt '*' sysfs.read class/net/em1/statistics
'''
i... |
Return the basename of a SysFS key path | def target(key, full=True):
'''
Return the basename of a SysFS key path
:param key: the location to resolve within SysFS
:param full: full path instead of basename
:return: fullpath or basename of path
CLI example:
.. code-block:: bash
salt '*' sysfs.read class/ttyS0
'''
... |
Generate a dictionary with all available interfaces relative to root. Symlinks are not followed. | def interfaces(root):
'''
Generate a dictionary with all available interfaces relative to root.
Symlinks are not followed.
CLI example:
.. code-block:: bash
salt '*' sysfs.interfaces block/bcache0/bcache
Output example:
.. code-block:: json
{
"r": [
... |
Return a Librato connection object. | def _get_librato(ret=None):
'''
Return a Librato connection object.
'''
_options = _get_options(ret)
conn = librato.connect(
_options.get('email'),
_options.get('api_token'),
sanitizer=librato.sanitize_metric_name,
hostname=_options.get('api_url'))
log.info("Conn... |
Parse the return data and return metrics to Librato. | def returner(ret):
'''
Parse the return data and return metrics to Librato.
'''
librato_conn = _get_librato(ret)
q = librato_conn.new_queue()
if ret['fun'] == 'state.highstate':
log.debug('Found returned Highstate data.')
# Calculate the runtimes and number of failed states.
... |
Returns: tuple whose first element is a bool indicating success or failure and the second element is either a ret dict for salt or an object | def _common(ret, name, service_name, kwargs):
'''
Returns: tuple whose first element is a bool indicating success or failure
and the second element is either a ret dict for salt or an object
'''
if 'interface' not in kwargs and 'public_url' not in kwargs:
kwargs['interface'] = name
... |
Ensure an endpoint exists and is up - to - date | def present(name, service_name, auth=None, **kwargs):
'''
Ensure an endpoint exists and is up-to-date
name
Interface name
url
URL of the endpoint
service_name
Service name or ID
region
The region name to assign the endpoint
enabled
Boolean to cont... |
Ensure an endpoint does not exists | def absent(name, service_name, auth=None, **kwargs):
'''
Ensure an endpoint does not exists
name
Interface name
url
URL of the endpoint
service_name
Service name or ID
region
The region name to assign the endpoint
'''
ret = {'name': name,
'c... |
Return the bgp runner options. | def _get_bgp_runner_opts():
'''
Return the bgp runner options.
'''
runner_opts = __opts__.get('runners', {}).get('bgp', {})
return {
'tgt': runner_opts.get('tgt', _DEFAULT_TARGET),
'tgt_type': runner_opts.get('tgt_type', _DEFAULT_EXPR_FORM),
'display': runner_opts.get('displa... |
Compare two dictionaries and return a boolean value if their values match. | def _compare_match(dict1, dict2):
'''
Compare two dictionaries and return a boolean value if their values match.
'''
for karg, warg in six.iteritems(dict1):
if karg in dict2 and dict2[karg] != warg:
return False
return True |
Display or return the rows. | def _display_runner(rows,
labels,
title,
display=_DEFAULT_DISPLAY,
outputter=_DEFAULT_OUTPUTTER):
'''
Display or return the rows.
'''
if display:
if outputter == 'table':
ret = salt.output.out_format({'ro... |
Search for BGP neighbors details in the mines of the bgp. neighbors function. | def neighbors(*asns, **kwargs):
'''
Search for BGP neighbors details in the mines of the ``bgp.neighbors`` function.
Arguments:
asns
A list of AS numbers to search for.
The runner will return only the neighbors of these AS numbers.
device
Filter by device name (minion ID).... |
Return a mongodb connection object | def _get_conn(ret):
'''
Return a mongodb connection object
'''
_options = _get_options(ret)
host = _options.get('host')
port = _options.get('port')
uri = _options.get('uri')
db_ = _options.get('db')
user = _options.get('user')
password = _options.get('password')
indexes = _o... |
Return data to a mongodb server | def returner(ret):
'''
Return data to a mongodb server
'''
conn, mdb = _get_conn(ret)
if isinstance(ret['return'], dict):
back = _remove_dots(ret['return'])
else:
back = ret['return']
if isinstance(ret, dict):
full_ret = _remove_dots(ret)
else:
full_ret ... |
mongodb doesn t allow. in keys but does allow unicode equivs. Apparently the docs suggest using escaped unicode full - width encodings. * sigh * | def _safe_copy(dat):
''' mongodb doesn't allow '.' in keys, but does allow unicode equivs.
Apparently the docs suggest using escaped unicode full-width
encodings. *sigh*
\\ --> \\\\
$ --> \\\\u0024
. --> \\\\u002e
Personally, I prefer URL encoding... |
Save the load for a given job id | def save_load(jid, load, minions=None):
'''
Save the load for a given job id
'''
conn, mdb = _get_conn(ret=None)
to_save = _safe_copy(load)
if PYMONGO_VERSION > _LooseVersion('2.3'):
#using .copy() to ensure original data for load is unchanged
mdb.jobs.insert_one(to_save)
el... |
Return the load associated with a given job id | def get_load(jid):
'''
Return the load associated with a given job id
'''
conn, mdb = _get_conn(ret=None)
return mdb.jobs.find_one({'jid': jid}, {'_id': 0}) |
Return a list of minions | def get_minions():
'''
Return a list of minions
'''
conn, mdb = _get_conn(ret=None)
ret = []
name = mdb.saltReturns.distinct('minion')
ret.append(name)
return ret |
Return a list of job ids | def get_jids():
'''
Return a list of job ids
'''
conn, mdb = _get_conn(ret=None)
map = "function() { emit(this.jid, this); }"
reduce = "function (key, values) { return values[0]; }"
result = mdb.jobs.inline_map_reduce(map, reduce)
ret = {}
for r in result:
jid = r['_id']
... |
Return events to Mongodb server | def event_return(events):
'''
Return events to Mongodb server
'''
conn, mdb = _get_conn(ret=None)
if isinstance(events, list):
events = events[0]
if isinstance(events, dict):
log.debug(events)
if PYMONGO_VERSION > _LooseVersion('2.3'):
mdb.events.insert_one... |
Create a list of file ref objects to reconcile | def lowstate_file_refs(chunks):
'''
Create a list of file ref objects to reconcile
'''
refs = {}
for chunk in chunks:
saltenv = 'base'
crefs = []
for state in chunk:
if state == '__env__':
saltenv = chunk[state]
elif state == 'saltenv':... |
Pull salt file references out of the states | def salt_refs(data):
'''
Pull salt file references out of the states
'''
proto = 'salt://'
ret = []
if isinstance(data, six.string_types):
if data.startswith(proto):
return [data]
if isinstance(data, list):
for comp in data:
if isinstance(comp, six.str... |
Generate the module arguments for the shim data | def mod_data(fsclient):
'''
Generate the module arguments for the shim data
'''
# TODO, change out for a fileserver backend
sync_refs = [
'modules',
'states',
'grains',
'renderers',
'returners',
]
ret = {}
envs = fsclien... |
Returns the version of the installed ssh command | def ssh_version():
'''
Returns the version of the installed ssh command
'''
# This function needs more granular checks and to be validated against
# older versions of ssh
ret = subprocess.Popen(
['ssh', '-V'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).co... |
Take a list of args and convert any dicts inside the list to keyword args in the form of key = value ready to be passed to salt - ssh | def _convert_args(args):
'''
Take a list of args, and convert any dicts inside the list to keyword
args in the form of `key=value`, ready to be passed to salt-ssh
'''
converted = []
for arg in args:
if isinstance(arg, dict):
for key in list(arg.keys()):
if key... |
Read roster filename as a key to the data.: return: | def _get_roster(self):
'''
Read roster filename as a key to the data.
:return:
'''
roster_file = salt.roster.get_roster_file(self.opts)
if roster_file not in self.__parsed_rosters:
roster_data = compile_template(roster_file, salt.loader.render(self.opts, {}),
... |
Figures out if the target is a reachable host without wildcards expands if any.: return: | def _expand_target(self):
'''
Figures out if the target is a reachable host without wildcards, expands if any.
:return:
'''
# TODO: Support -L
target = self.opts['tgt']
if isinstance(target, list):
return
hostname = self.opts['tgt'].split('@')... |
Update default flat roster with the passed in information.: return: | def _update_roster(self):
'''
Update default flat roster with the passed in information.
:return:
'''
roster_file = self._get_roster()
if os.access(roster_file, os.W_OK):
if self.__parsed_rosters[self.ROSTER_UPDATE_FLAG]:
with salt.utils.files.... |
Uptade targets in case hostname was directly passed without the roster.: return: | def _update_targets(self):
'''
Uptade targets in case hostname was directly passed without the roster.
:return:
'''
hostname = self.opts.get('tgt', '')
if '@' in hostname:
user, hostname = hostname.split('@', 1)
else:
user = self.opts.get(... |
Return the key string for the SSH public key | def get_pubkey(self):
'''
Return the key string for the SSH public key
'''
if '__master_opts__' in self.opts and \
self.opts['__master_opts__'].get('ssh_use_home_key') and \
os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
priv = os.path.ex... |
Deploy the SSH key if the minions don t auth | def key_deploy(self, host, ret):
'''
Deploy the SSH key if the minions don't auth
'''
if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'):
target = self.targets[host]
if target.get('passwd', False) or self.opts['ssh_passwd']:
self... |
The ssh - copy - id routine | def _key_deploy_run(self, host, target, re_run=True):
'''
The ssh-copy-id routine
'''
argv = [
'ssh.set_auth_key',
target.get('user', 'root'),
self.get_pubkey(),
]
single = Single(
self.opts,
argv,
... |
Run the routine in a Thread put a dict on the queue | def handle_routine(self, que, opts, host, target, mine=False):
'''
Run the routine in a "Thread", put a dict on the queue
'''
opts = copy.deepcopy(opts)
single = Single(
opts,
opts['argv'],
host,
mods=self.mods,
... |
Spin up the needed threads or processes and execute the subsequent routines | def handle_ssh(self, mine=False):
'''
Spin up the needed threads or processes and execute the subsequent
routines
'''
que = multiprocessing.Queue()
running = {}
target_iter = self.targets.__iter__()
returned = set()
rets = set()
init = Fals... |
Execute and yield returns as they come in do not print to the display | def run_iter(self, mine=False, jid=None):
'''
Execute and yield returns as they come in, do not print to the display
mine
The Single objects will use mine_functions defined in the roster,
pillar, or master config (they will be checked in that order) and
will ... |
Cache the job information | def cache_job(self, jid, id_, ret, fun):
'''
Cache the job information
'''
self.returners['{0}.returner'.format(self.opts['master_job_cache'])]({'jid': jid,
'id': id_,
... |
Execute the overall routine print results via outputters | def run(self, jid=None):
'''
Execute the overall routine, print results via outputters
'''
if self.opts.get('list_hosts'):
self._get_roster()
ret = {}
for roster_file in self.__parsed_rosters:
if roster_file.startswith('#'):
... |
Return the function name and the arg list | def __arg_comps(self):
'''
Return the function name and the arg list
'''
fun = self.argv[0] if self.argv else ''
parsed = salt.utils.args.parse_input(
self.argv[1:],
condition=False,
no_parse=self.opts.get('no_parse', []))
args = parsed... |
Properly escape argument to protect special characters from shell interpretation. This avoids having to do tricky argument quoting. | def _escape_arg(self, arg):
'''
Properly escape argument to protect special characters from shell
interpretation. This avoids having to do tricky argument quoting.
Effectively just escape all characters in the argument that are not
alphanumeric!
'''
if self.winr... |
Deploy salt - thin | def deploy(self):
'''
Deploy salt-thin
'''
self.shell.send(
self.thin,
os.path.join(self.thin_dir, 'salt-thin.tgz'),
)
self.deploy_ext()
return True |
Deploy the ext_mods tarball | def deploy_ext(self):
'''
Deploy the ext_mods tarball
'''
if self.mods.get('file'):
self.shell.send(
self.mods['file'],
os.path.join(self.thin_dir, 'salt-ext_mods.tgz'),
)
return True |
Execute the routine the routine can be either: 1. Execute a raw shell command 2. Execute a wrapper func 3. Execute a remote Salt command | def run(self, deploy_attempted=False):
'''
Execute the routine, the routine can be either:
1. Execute a raw shell command
2. Execute a wrapper func
3. Execute a remote Salt command
If a (re)deploy is needed, then retry the operation after a deploy
attempt
... |
Execute a wrapper function | def run_wfunc(self):
'''
Execute a wrapper function
Returns tuple of (json_data, '')
'''
# Ensure that opts/grains are up to date
# Execute routine
data_cache = False
data = None
cdir = os.path.join(self.opts['cachedir'], 'minions', self.id)
... |
Prepare the command string | def _cmd_str(self):
'''
Prepare the command string
'''
sudo = 'sudo' if self.target['sudo'] else ''
sudo_user = self.target['sudo_user']
if '_caller_cachedir' in self.opts:
cachedir = self.opts['_caller_cachedir']
else:
cachedir = self.opts... |
Run a shim command. | def shim_cmd(self, cmd_str, extension='py'):
'''
Run a shim command.
If tty is enabled, we must scp the shim to the target system and
execute it there
'''
if not self.tty and not self.winrm:
return self.shell.exec_cmd(cmd_str)
# Write the shim to a t... |
Prepare the pre - check command to send to the subsystem | def cmd_block(self, is_retry=False):
'''
Prepare the pre-check command to send to the subsystem
1. execute SHIM + command
2. check if SHIM returns a master request or if it completed
3. handle any master request
4. re-execute SHIM + command
5. split SHIM results ... |
Lookup style by either element name or the list of classes | def _lookup_style(element, names):
'''
Lookup style by either element name or the list of classes
'''
return _STYLES.get('_'+element, '') + \
''.join([_STYLES.get(name, '') for name in names]) |
Generate a single table of data | def _generate_html_table(data, out, level=0, extra_style=''):
'''
Generate a single table of data
'''
print('<table style="{0}">'.format(
_lookup_style('table', ['table' + six.text_type(level)])), file=out)
firstone = True
row_style = 'row' + six.text_type(level)
cell_style = 'cell... |
Generate report data as HTML | def _generate_html(data, out):
'''
Generate report data as HTML
'''
print('<html>', file=out)
print('<body>', file=out)
_generate_html_table(data, out, 0)
print('</body>', file=out)
print('</html>', file=out) |
Convert a dictionary to a list of dictionaries to facilitate ordering | def _dict_to_name_value(data):
'''
Convert a dictionary to a list of dictionaries to facilitate ordering
'''
if isinstance(data, dict):
sorted_data = sorted(data.items(), key=lambda s: s[0])
result = []
for name, value in sorted_data:
if isinstance(value, dict):
... |
Generate states report | def _generate_states_report(sorted_data):
'''
Generate states report
'''
states = []
for state, data in sorted_data:
module, stateid, name, function = state.split('_|-')
module_function = '.'.join((module, function))
result = data.get('result', '')
single = [
... |
Generate report dictionary | def _generate_report(ret, setup):
'''
Generate report dictionary
'''
retdata = ret.get('return', {})
sorted_data = sorted(
retdata.items(),
key=lambda s: s[1].get('__run_num__', 0)
)
total = 0
failed = 0
changed = 0
duration = 0.0
# gather stats
for _,... |
Produce output from the report dictionary generated by _generate_report | def _produce_output(report, failed, setup):
'''
Produce output from the report dictionary generated by _generate_report
'''
report_format = setup.get('report_format', 'yaml')
log.debug('highstate output format: %s', report_format)
if report_format == 'json':
report_text = salt.utils.js... |
Check highstate return information and possibly fire off an email or save a file. | def returner(ret):
'''
Check highstate return information and possibly fire off an email
or save a file.
'''
setup = _get_options(ret)
log.debug('highstate setup %s', setup)
report, failed = _generate_report(ret, setup)
if report:
_produce_output(report, failed, setup) |
Return the formatted outputter string for the Python object. | def out_format(data, out='nested', opts=None, **kwargs):
'''
Return the formatted outputter string for the Python object.
data
The JSON serializable object.
out: ``nested``
The name of the output to use to transform the data. Default: ``nested``.
opts
Dictionary of configu... |
Return the outputter formatted string removing the ANSI escape sequences. | def string_format(data, out='nested', opts=None, **kwargs):
'''
Return the outputter formatted string, removing the ANSI escape sequences.
data
The JSON serializable object.
out: ``nested``
The name of the output to use to transform the data. Default: ``nested``.
opts
Dict... |
Return the formatted string as HTML. | def html_format(data, out='nested', opts=None, **kwargs):
'''
Return the formatted string as HTML.
data
The JSON serializable object.
out: ``nested``
The name of the output to use to transform the data. Default: ``nested``.
opts
Dictionary of configuration options. Default... |
Install buildout in a specific directory | def installed(name,
config='buildout.cfg',
quiet=False,
parts=None,
user=None,
env=(),
buildout_ver=None,
test_release=False,
distribute=None,
new_st=None,
offline=False,
... |
Returns a string representing the package version or an empty string if not installed. If more than one package name is specified a dict of name/ version pairs is returned. | def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
... |
Set an object permission for the given user sid | def set_user_perm(obj, perm, sid):
'''
Set an object permission for the given user sid
'''
info = (
win32security.OWNER_SECURITY_INFORMATION |
win32security.GROUP_SECURITY_INFORMATION |
win32security.DACL_SECURITY_INFORMATION
)
sd = win32security.GetUserObjectSecurity(obj... |
Grant the token s user access to the current process s window station and desktop. | def grant_winsta_and_desktop(th):
'''
Grant the token's user access to the current process's window station and
desktop.
'''
current_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]
# Add permissions for the sid to the current windows station and thread id.
# This prev... |
Enumerate tokens from any existing processes that can be accessed. Optionally filter by sid. | def enumerate_tokens(sid=None, session_id=None, privs=None):
'''
Enumerate tokens from any existing processes that can be accessed.
Optionally filter by sid.
'''
for p in psutil.process_iter():
if p.pid == 0:
continue
try:
ph = win32api.OpenProcess(win32con.PR... |
Find an existing process token for the given sid and impersonate the token. | def impersonate_sid(sid, session_id=None, privs=None):
'''
Find an existing process token for the given sid and impersonate the token.
'''
for tok in enumerate_tokens(sid, session_id, privs):
tok = dup_token(tok)
elevate_token(tok)
if win32security.ImpersonateLoggedOnUser(tok) ==... |
duplicate the access token | def dup_token(th):
'''
duplicate the access token
'''
# TODO: is `duplicate_token` the same?
sec_attr = win32security.SECURITY_ATTRIBUTES()
sec_attr.bInheritHandle = True
return win32security.DuplicateTokenEx(
th,
win32security.SecurityImpersonation,
win32con.MAXIMUM_ALL... |
Set all token priviledges to enabled | def elevate_token(th):
'''
Set all token priviledges to enabled
'''
# Get list of privileges this token contains
privileges = win32security.GetTokenInformation(
th, win32security.TokenPrivileges)
# Create a set of all privileges to be enabled
enable_privs = set()
for luid, flags... |
Create an inheritable handle | def make_inheritable(token):
'''Create an inheritable handle'''
return win32api.DuplicateHandle(
win32api.GetCurrentProcess(),
token,
win32api.GetCurrentProcess(),
0,
1,
win32con.DUPLICATE_SAME_ACCESS
) |
Ensure the CloudFront distribution is present. | def present(
name,
config,
tags,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Ensure the CloudFront distribution is present.
name (string)
Name of the CloudFront distribution
config (dict)
Configuration for the distribution
tags (dict)
... |
Stupidly simple function to fix any Items/ Quantity disparities inside a DistributionConfig block before use. Since AWS only accepts JSON - encodable data types this implementation is good enough for our purposes. | def _fix_quantities(tree):
'''
Stupidly simple function to fix any Items/Quantity disparities inside a
DistributionConfig block before use. Since AWS only accepts JSON-encodable
data types, this implementation is "good enough" for our purposes.
'''
if isinstance(tree, dict):
tree = {k: _... |
Ensure the given CloudFront distribution exists in the described state. | def distribution_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure the given CloudFront distribution exists in the described state.
The implementation of this function, and all those following, is orthagonal
to that of :py:mod:`boto_cloudfront.present
<salt.states... |
Ensure the given policy exists on an S3 bucket granting access for the given origin access identity to do the things specified in the policy. | def oai_bucket_policy_present(name, Bucket, OAI, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Ensure the given policy exists on an S3 bucket, granting access for the given origin access
identity to do the things specified in the policy.
name
The na... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.