desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Tear down the syndic minion'
| def destroy(self):
| super(Syndic, self).destroy()
if hasattr(self, u'local'):
del self.local
if hasattr(self, u'forward_events'):
self.forward_events.stop()
|
'Spawn all the coroutines which will sign in the syndics'
| def _spawn_syndics(self):
| self._syndics = OrderedDict()
masters = self.opts[u'master']
if (not isinstance(masters, list)):
masters = [masters]
for master in masters:
s_opts = copy.copy(self.opts)
s_opts[u'master'] = master
self._syndics[master] = self._connect_syndic(s_opts)
|
'Create a syndic, and asynchronously connect it to a master'
| @tornado.gen.coroutine
def _connect_syndic(self, opts):
| last = 0
auth_wait = opts[u'acceptance_wait_time']
failed = False
while True:
log.debug(u'Syndic attempting to connect to %s', opts[u'master'])
try:
syndic = Syndic(opts, timeout=self.SYNDIC_CONNECT_TIMEOUT, safe=False, io_loop=self.io_loop)
(yield ... |
'Mark a master as dead. This will start the sign-in routine'
| def _mark_master_dead(self, master):
| if self._syndics[master].done():
syndic = self._syndics[master].result()
self._syndics[master] = syndic.reconnect()
else:
log.info(u'Attempting to mark %s as dead, although it is already marked dead', master)
|
'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):
| if (kwargs is None):
kwargs = {}
for (master, syndic_future) in self.iter_master_options(master_id):
if ((not syndic_future.done()) or syndic_future.exception()):
log.error(u'Unable to call %s on %s, that syndic is not connected', func, master)
... |
'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):
| func = u'_return_pub_multi'
for (master, syndic_future) in self.iter_master_options(master_id):
if ((not syndic_future.done()) or syndic_future.exception()):
log.error(u'Unable to call %s on %s, that syndic is not connected', func, master)
continue
... |
'Iterate (in order) over your options for master'
| def iter_master_options(self, master_id=None):
| masters = list(self._syndics.keys())
if (self.opts[u'syndic_failover'] == u'random'):
shuffle(masters)
if (master_id not in self._syndics):
master_id = masters.pop(0)
else:
masters.remove(master_id)
while True:
(yield (master_id, self._syndics[master_id]))
if ... |
'Lock onto the publisher. This is the main event loop for the syndic'
| def tune_in(self):
| self._spawn_syndics()
self.local = salt.client.get_local_client(self.opts[u'_minion_conf_file'], io_loop=self.io_loop)
self.local.event.subscribe(u'')
log.debug(u"SyndicManager '%s' trying to tune in", self.opts[u'id'])
self.job_rets = {}
self.raw_events = []
self._reset_event... |
'Takes the data passed to a top file environment and determines if the
data matches this minion'
| def confirm_top(self, match, data, nodegroups=None):
| matcher = u'compound'
if (not data):
log.error(u'Received bad data when setting the match from the top file')
return False
for item in data:
if isinstance(item, dict):
if (u'match' in item):
matcher = item[u'match']
if has... |
'Returns true if the passed glob matches the id'
| def glob_match(self, tgt):
| if (not isinstance(tgt, six.string_types)):
return False
return fnmatch.fnmatch(self.opts[u'id'], tgt)
|
'Returns true if the passed pcre regex matches'
| def pcre_match(self, tgt):
| return bool(re.match(tgt, self.opts[u'id']))
|
'Determines if this host is on the list'
| def list_match(self, tgt):
| if isinstance(tgt, six.string_types):
tgt = tgt.split(u',')
return bool((self.opts[u'id'] in tgt))
|
'Reads in the grains glob match'
| def grain_match(self, tgt, delimiter=DEFAULT_TARGET_DELIM):
| log.debug(u'grains target: %s', tgt)
if (delimiter not in tgt):
log.error(u'Got insufficient arguments for grains match statement from master')
return False
return salt.utils.subdict_match(self.opts[u'grains'], tgt, delimiter=delimiter)
|
'Matches a grain based on regex'
| def grain_pcre_match(self, tgt, delimiter=DEFAULT_TARGET_DELIM):
| log.debug(u'grains pcre target: %s', tgt)
if (delimiter not in tgt):
log.error(u'Got insufficient arguments for grains pcre match statement from master')
return False
return salt.utils.subdict_match(self.opts[u'grains'], tgt, delimiter=delimiter, regex_mat... |
'Match based on the local data store on the minion'
| def data_match(self, tgt):
| if (self.functions is None):
utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, utils=utils)
comps = tgt.split(u':')
if (len(comps) < 2):
return False
val = self.functions[u'data.getval'](comps[0])
if (val is None):
return False
... |
'Reads in the pillar glob match'
| def pillar_match(self, tgt, delimiter=DEFAULT_TARGET_DELIM):
| log.debug(u'pillar target: %s', tgt)
if (delimiter not in tgt):
log.error(u'Got insufficient arguments for pillar match statement from master')
return False
return salt.utils.subdict_match(self.opts[u'pillar'], tgt, delimiter=delimiter)
|
'Reads in the pillar pcre match'
| def pillar_pcre_match(self, tgt, delimiter=DEFAULT_TARGET_DELIM):
| log.debug(u'pillar PCRE target: %s', tgt)
if (delimiter not in tgt):
log.error(u'Got insufficient arguments for pillar PCRE match statement from master')
return False
return salt.utils.subdict_match(self.opts[u'pillar'], tgt, delimiter=delimiter, regex_mat... |
'Reads in the pillar match, no globbing, no PCRE'
| def pillar_exact_match(self, tgt, delimiter=u':'):
| log.debug(u'pillar target: %s', tgt)
if (delimiter not in tgt):
log.error(u'Got insufficient arguments for pillar match statement from master')
return False
return salt.utils.subdict_match(self.opts[u'pillar'], tgt, delimiter=delimiter, exact_match=True)
|
'Matches based on IP address or CIDR notation'
| def ipcidr_match(self, tgt):
| try:
tgt = ipaddress.ip_address(tgt)
except:
try:
tgt = ipaddress.ip_network(tgt)
except:
log.error(u'Invalid IP/CIDR target: %s', tgt)
return []
proto = u'ipv{0}'.format(tgt.version)
grains = self.opts[u'grains']
if (proto not in ... |
'Matches based on range cluster'
| def range_match(self, tgt):
| if HAS_RANGE:
range_ = seco.range.Range(self.opts[u'range_server'])
try:
return (self.opts[u'grains'][u'fqdn'] in range_.expand(tgt))
except seco.range.RangeException as exc:
log.debug(u'Range exception in compound match: %s', exc)
return Fa... |
'Runs the compound target check'
| def compound_match(self, tgt):
| if ((not isinstance(tgt, six.string_types)) and (not isinstance(tgt, (list, tuple)))):
log.error(u'Compound target received that is neither string, list nor tuple')
return False
log.debug(u'compound_match: %s ? %s', self.opts[u'id'], tgt)
ref = {u'G': u'gr... |
'This is a compatibility matcher and is NOT called when using
nodegroups for remote execution, but is called when the nodegroups
matcher is used in states'
| def nodegroup_match(self, tgt, nodegroups):
| if (tgt in nodegroups):
return self.compound_match(salt.utils.minions.nodegroup_comp(tgt, nodegroups))
return False
|
'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):
| return ProxyMinion(opts, timeout, safe, io_loop=io_loop, loaded_base_name=loaded_base_name, jid_queue=jid_queue)
|
'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.
ProxyMinions need a significantly different po... | @tornado.gen.coroutine
def _post_master_init(self, master):
| log.debug(u'subclassed _post_master_init')
if self.connected:
self.opts[u'master'] = master
self.opts[u'pillar'] = (yield salt.pillar.get_async_pillar(self.opts, self.opts[u'grains'], self.opts[u'id'], saltenv=self.opts[u'environment'], pillarenv=self.opts.get(u'pillarenv')).compile_pillar())... |
'Execute salt-cp'
| def run(self):
| self.parse_args()
self.setup_logfile_logger()
verify_log(self.config)
cp_ = SaltCP(self.config)
cp_.run()
|
'Get a list of all specified files'
| def _recurse(self, path):
| files = {}
empty_dirs = []
try:
sub_paths = os.listdir(path)
except OSError as exc:
if (exc.errno == errno.ENOENT):
sys.stderr.write('{0} does not exist\n'.format(path))
sys.exit(42)
elif (exc.errno in (errno.EINVAL, errno.ENOTDIR)):
f... |
'Make the salt client call'
| def run(self):
| (files, empty_dirs) = self._list_files()
dest = self.opts['dest']
gzip = self.opts['gzip']
tgt = self.opts['tgt']
timeout = self.opts['timeout']
selected_target_option = self.opts.get('selected_target_option')
dest_is_dir = (bool(empty_dirs) or (len(files) > 1) or bool(re.search('[\\\\/]$', ... |
'Return a list of minions to use for the batch run'
| def __gather_minions(self):
| args = [self.opts['tgt'], 'test.ping', [], self.opts['timeout']]
selected_target_option = self.opts.get('selected_target_option', None)
if (selected_target_option is not None):
args.append(selected_target_option)
else:
args.append(self.opts.get('tgt_type', 'glob'))
self.pub_kwargs['y... |
'Return the active number of minions to maintain'
| def get_bnum(self):
| partition = (lambda x: ((float(x) / 100.0) * len(self.minions)))
try:
if ('%' in self.opts['batch']):
res = partition(float(self.opts['batch'].strip('%')))
if (res < 1):
return int(math.ceil(res))
else:
return int(res)
else:
... |
'Execute the batch run'
| def run(self):
| args = [[], self.opts['fun'], self.opts['arg'], self.opts['timeout'], 'list']
bnum = self.get_bnum()
if (not self.minions):
return
to_run = copy.deepcopy(self.minions)
active = []
ret = {}
iters = []
bwait = self.opts.get('batch_wait', 0)
wait = []
if self.options:
... |
'Execute salt-run'
| def run(self):
| import salt.runner
self.parse_args()
self.setup_logfile_logger()
verify_log(self.config)
profiling_enabled = self.options.profiling_enabled
runner = salt.runner.Runner(self.config)
if self.options.doc:
runner.print_docs()
self.exit(salt.defaults.exitcodes.EX_OK)
try:
... |
'Execute the salt command line'
| def run(self):
| import salt.client
self.parse_args()
self.setup_logfile_logger()
verify_log(self.config)
try:
skip_perm_errors = (self.options.eauth != '')
self.local_client = salt.client.get_local_client(self.get_config_file_path(), skip_perm_errors=skip_perm_errors, auto_reconnect=True)
except... |
'Return a list of minions from a given target'
| def _preview_target(self):
| return self.local_client.gather_minions(self.config['tgt'], (self.selected_target_option or 'glob'))
|
'Display returns summary'
| def _print_returns_summary(self, ret):
| return_counter = 0
not_return_counter = 0
not_return_minions = []
not_response_minions = []
not_connected_minions = []
failed_minions = []
for each_minion in ret:
minion_ret = ret[each_minion]
if (isinstance(minion_ret, dict) and ('ret' in minion_ret)):
minion_ret... |
'Print progress events'
| def _progress_ret(self, progress, out):
| import salt.output
if (not hasattr(self, 'progress_bar')):
try:
self.progress_bar = salt.output.get_progress(self.config, out, progress)
except Exception as exc:
raise salt.exceptions.LoaderError('\nWARNING: Install the `progressbar` python package. Requ... |
'Print the output from a single return to the terminal'
| def _output_ret(self, ret, out):
| import salt.output
if ((self.config['fun'] == 'sys.doc') and (not isinstance(ret, Exception))):
self._print_docs(ret)
else:
salt.output.display_output(ret, out, self.config)
if (not ret):
sys.stderr.write('ERROR: No return received\n')
sys.exit(2)
|
'Take the full return data and format it to simple output'
| def _format_ret(self, full_ret):
| ret = {}
out = ''
retcode = 0
for (key, data) in six.iteritems(full_ret):
ret[key] = data['ret']
if ('out' in data):
out = data['out']
ret_retcode = self._get_retcode(data)
if (ret_retcode > retcode):
retcode = ret_retcode
return (ret, out, ret... |
'Determine a retcode for a given return'
| def _get_retcode(self, ret):
| retcode = 0
if (isinstance(ret, dict) and (ret.get('retcode', 0) != 0)):
return ret['retcode']
elif (isinstance(ret, bool) and (not ret)):
return 1
return retcode
|
'Print out the docstrings for all of the functions on the minions'
| def _print_docs(self, ret):
| import salt.output
docs = {}
if (not ret):
self.exit(2, 'No minions found to gather docs from\n')
if isinstance(ret, six.string_types):
self.exit(2, '{0}\n'.format(ret))
for host in ret:
if (isinstance(ret[host], six.string_types) and (ret[host].startswith('... |
'Execute salt-key'
| def run(self):
| import salt.key
self.parse_args()
multi = False
if (self.config.get('zmq_behavior') and (self.config.get('transport') == 'raet')):
multi = True
self.setup_logfile_logger()
verify_log(self.config)
if multi:
key = salt.key.MultiKeyCLI(self.config)
else:
key = salt.k... |
'Verify and display a nag-messsage to the log if vulnerable hash-type is used.
:return:'
| def verify_hash_type(self):
| if (self.config['hash_type'].lower() in ['md5', 'sha1']):
log.warning('IMPORTANT: Do not use {h_type} hashing algorithm! Please set "hash_type" to sha256 in Salt {d_name} config!'.format(h_type=self.config['hash_type'], d_name=self.__class__.__name__))
|
'Say daemon starting.
:param action
:return:'
| def action_log_info(self, action):
| log.info('{action} the Salt {d_name}'.format(d_name=self.__class__.__name__, action=action))
|
'Say daemon starting.
:return:'
| def start_log_info(self):
| log.info('The Salt {d_name} is starting up'.format(d_name=self.__class__.__name__))
|
'Say daemon shutting down.
:return:'
| def shutdown_log_info(self):
| log.info('The Salt {d_name} is shut down'.format(d_name=self.__class__.__name__))
|
'Log environment failure for the daemon and exit with the error code.
:param error:
:return:'
| def environment_failure(self, error):
| log.exception('Failed to create environment for {d_name}: {reason}'.format(d_name=self.__class__.__name__, reason=get_error_message(error)))
self.shutdown(error)
|
'Run the preparation sequence required to start a salt master server.
If sub-classed, don\'t **ever** forget to run:
super(YourSubClass, self).prepare()'
| def prepare(self):
| super(Master, self).prepare()
try:
if self.config['verify_env']:
v_dirs = [self.config['pki_dir'], os.path.join(self.config['pki_dir'], 'minions'), os.path.join(self.config['pki_dir'], 'minions_pre'), os.path.join(self.config['pki_dir'], 'minions_denied'), os.path.join(self.config['pki_dir']... |
'Start the actual master.
If sub-classed, don\'t **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`.'
| def start(self):
| super(Master, self).start()
if check_user(self.config['user']):
self.action_log_info('Starting up')
self.verify_hash_type()
self.master.start()
|
'If sub-classed, run any shutdown operations on this method.'
| def shutdown(self, exitcode=0, exitmsg=None):
| self.shutdown_log_info()
msg = 'The salt master is shutdown. '
if (exitmsg is not None):
exitmsg = (msg + exitmsg)
else:
exitmsg = msg.strip()
super(Master, self).shutdown(exitcode, exitmsg)
|
'Run the preparation sequence required to start a salt minion.
If sub-classed, don\'t **ever** forget to run:
super(YourSubClass, self).prepare()'
| def prepare(self):
| super(Minion, self).prepare()
try:
if self.config['verify_env']:
confd = self.config.get('default_include')
if confd:
if ('*' in confd):
confd = os.path.dirname(confd)
if (not os.path.isabs(confd)):
confd = o... |
'Start the actual minion.
If sub-classed, don\'t **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`.'
| def start(self):
| super(Minion, self).start()
try:
if check_user(self.config['user']):
self.action_log_info('Starting up')
self.verify_hash_type()
self.minion.tune_in()
if self.minion.restart:
raise SaltClientError('Minion could not connect to... |
'Start the actual minion as a caller minion.
cleanup_protecteds is list of yard host addresses that should not be
cleaned up this is to fix race condition when salt-caller minion starts up
If sub-classed, don\'t **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super(... | def call(self, cleanup_protecteds):
| try:
self.prepare()
if check_user(self.config['user']):
self.minion.opts['__role'] = kinds.APPL_KIND_NAMES[kinds.applKinds.caller]
self.minion.opts['raet_cleanup_protecteds'] = cleanup_protecteds
self.minion.call_in()
except (KeyboardInterrupt, SaltSystemExit)... |
'If sub-classed, run any shutdown operations on this method.
:param exitcode
:param exitmsg'
| def shutdown(self, exitcode=0, exitmsg=None):
| self.action_log_info('Shutting down')
if hasattr(self, 'minion'):
self.minion.destroy()
super(Minion, self).shutdown(exitcode, 'The Salt {0} is shutdown. {1}'.format(self.__class__.__name__, (exitmsg or '')).strip())
|
'Run the preparation sequence required to start a salt proxy minion.
If sub-classed, don\'t **ever** forget to run:
super(YourSubClass, self).prepare()'
| def prepare(self):
| super(ProxyMinion, self).prepare()
if (not self.values.proxyid):
self.error('salt-proxy requires --proxyid')
try:
if self.config['verify_env']:
confd = self.config.get('default_include')
if confd:
if ('*' in confd):
confd = os... |
'Start the actual proxy minion.
If sub-classed, don\'t **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`.'
| def start(self):
| super(ProxyMinion, self).start()
try:
if check_user(self.config['user']):
self.action_log_info('The Proxy Minion is starting up')
self.verify_hash_type()
self.minion.tune_in()
if self.minion.restart:
raise SaltClientError('Pr... |
'If sub-classed, run any shutdown operations on this method.
:param exitcode
:param exitmsg'
| def shutdown(self, exitcode=0, exitmsg=None):
| if (hasattr(self, 'minion') and ('proxymodule' in self.minion.opts)):
proxy_fn = (self.minion.opts['proxymodule'].loaded_base_name + '.shutdown')
self.minion.opts['proxymodule'][proxy_fn](self.minion.opts)
self.action_log_info('Shutting down')
super(ProxyMinion, self).shutdown(exitcode, '... |
'Run the preparation sequence required to start a salt syndic minion.
If sub-classed, don\'t **ever** forget to run:
super(YourSubClass, self).prepare()'
| def prepare(self):
| super(Syndic, self).prepare()
try:
if self.config['verify_env']:
verify_env([self.config['pki_dir'], self.config['cachedir'], self.config['sock_dir'], self.config['extension_modules']], self.config['user'], permissive=self.config['permissive_pki_access'], pki_dir=self.config['pki_dir'])
... |
'Start the actual syndic.
If sub-classed, don\'t **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`.'
| def start(self):
| super(Syndic, self).start()
if check_user(self.config['user']):
self.action_log_info('Starting up')
self.verify_hash_type()
try:
self.syndic.tune_in()
except KeyboardInterrupt:
self.action_log_info('Stopping')
self.shutdown()
|
'If sub-classed, run any shutdown operations on this method.
:param exitcode
:param exitmsg'
| def shutdown(self, exitcode=0, exitmsg=None):
| self.action_log_info('Shutting down')
super(Syndic, self).shutdown(exitcode, 'The Salt {0} is shutdown. {1}'.format(self.__class__.__name__, (exitmsg or '')).strip())
|
'Run the preparation sequence required to start a salt-api daemon.
If sub-classed, don\'t **ever** forget to run:
super(YourSubClass, self).prepare()'
| def prepare(self):
| super(SaltAPI, self).prepare()
try:
if self.config['verify_env']:
logfile = self.config['log_file']
if ((logfile is not None) and (not logfile.startswith(('tcp://', 'udp://', 'file://')))):
current_umask = os.umask(23)
verify_files([logfile], self.... |
'Start the actual master.
If sub-classed, don\'t **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`.'
| def start(self):
| super(SaltAPI, self).start()
if check_user(self.config['user']):
log.info('The salt-api is starting up')
self.api.run()
|
'If sub-classed, run any shutdown operations on this method.'
| def shutdown(self, exitcode=0, exitmsg=None):
| log.info('The salt-api is shutting down..')
msg = 'The salt-api is shutdown. '
if (exitmsg is not None):
exitmsg = (msg + exitmsg)
else:
exitmsg = msg.strip()
super(SaltAPI, self).shutdown(exitcode, exitmsg)
|
'Run the api'
| def run(self):
| ui = salt.spm.SPMCmdlineInterface()
self.parse_args()
self.setup_logfile_logger()
verify_log(self.config)
client = salt.spm.SPMClient(ui, self.config)
client.run(self.args)
|
'Execute the salt call!'
| def run(self):
| self.parse_args()
if self.options.file_root:
file_root = os.path.abspath(self.options.file_root)
self.config['file_roots'] = {'base': _expand_glob_path([file_root])}
if self.options.pillar_root:
pillar_root = os.path.abspath(self.options.pillar_root)
self.config['pillar_roots... |
'Pass in command line opts'
| def __init__(self, opts):
| self.opts = opts
self.opts['caller'] = True
self.serial = salt.payload.Serial(self.opts)
try:
self.minion = salt.minion.SMinion(opts)
except SaltClientError as exc:
raise SystemExit(str(exc))
|
'Pick up the documentation for all of the modules and print it out.'
| def print_docs(self):
| docs = {}
for (name, func) in six.iteritems(self.minion.functions):
if (name not in docs):
if func.__doc__:
docs[name] = func.__doc__
for name in sorted(docs):
if name.startswith(self.opts.get('fun', '')):
salt.utils.print_cli('{0}:\n{1}\n'.format(name... |
'Print out the grains'
| def print_grains(self):
| grains = salt.loader.grains(self.opts)
salt.output.display_output({'local': grains}, 'grains', self.opts)
|
'Execute the salt call logic'
| def run(self):
| profiling_enabled = self.opts.get('profiling_enabled', False)
try:
pr = salt.utils.activate_profile(profiling_enabled)
try:
ret = self.call()
finally:
salt.utils.output_profile(pr, stats_path=self.opts.get('profiling_path', '/tmp/stats'), stop=True)
out = ... |
'Call the module'
| def call(self):
| ret = {}
fun = self.opts['fun']
ret['jid'] = salt.utils.jid.gen_jid()
proc_fn = os.path.join(salt.minion.get_proc_dir(self.opts['cachedir']), ret['jid'])
if (fun not in self.minion.functions):
docs = self.minion.functions['sys.doc']('{0}*'.format(fun))
if docs:
docs[fun] ... |
'Pass in the command line options'
| def __init__(self, opts):
| super(ZeroMQCaller, self).__init__(opts)
|
'Return the data up to the master'
| def return_pub(self, ret):
| channel = salt.transport.Channel.factory(self.opts, usage='salt_call')
load = {'cmd': '_return', 'id': self.opts['id']}
for (key, value) in six.iteritems(ret):
load[key] = value
channel.send(load)
|
'Pass in the command line options'
| def __init__(self, opts):
| self.process = None
if (not opts['local']):
self.stack = self._setup_caller_stack(opts)
salt.transport.jobber_stack = self.stack
if (opts.get('__role') == kinds.APPL_KIND_NAMES[kinds.applKinds.caller]):
self.process = MultiprocessingProcess(target=raet_minion_run, kwargs={'cl... |
'Execute the salt call logic'
| def run(self):
| try:
ret = self.call()
if (not self.opts['local']):
self.stack.server.close()
salt.transport.jobber_stack = None
if self.opts['print_metadata']:
print_ret = ret
else:
print_ret = ret.get('return', {})
if self.process:
... |
'Setup and return the LaneStack and Yard used by by channel when global
not already setup such as in salt-call to communicate to-from the minion'
| def _setup_caller_stack(self, opts):
| role = opts.get('id')
if (not role):
emsg = 'Missing role required to setup RAETChannel.'
log.error((emsg + '\n'))
raise ValueError(emsg)
kind = opts.get('__role')
if (kind not in kinds.APPL_KINDS):
emsg = "Invalid application kind = '{0}' fo... |
'Returns when RAET Minion Yard is available'
| def _wait_caller(self, opts):
| yardname = 'manor'
dirpath = opts['sock_dir']
role = opts.get('id')
if (not role):
emsg = 'Missing role required to setup RAET SaltCaller.'
log.error((emsg + '\n'))
raise ValueError(emsg)
kind = opts.get('__role')
if (kind not in kinds.APPL_KINDS):
... |
'Format the low data for RunnerClient()\'s master_call() function
This also normalizes the following low data formats to a single, common
low data structure.
Old-style low: ``{\'fun\': \'jobs.lookup_jid\', \'jid\': \'1234\'}``
New-style: ``{\'fun\': \'jobs.lookup_jid\', \'kwarg\': {\'jid\': \'1234\'}}``
CLI-style: ``{\... | def _reformat_low(self, low):
| fun = low.pop(u'fun')
verify_fun(self.functions, fun)
eauth_creds = dict([(i, low.pop(i)) for i in [u'username', u'password', u'eauth', u'token', u'client', u'user', u'key'] if (i in low)])
(_arg, _kwarg) = salt.utils.args.parse_input(low.pop(u'arg', []), condition=False)
_kwarg.update(low.pop(u'kwa... |
'Execute a runner function asynchronously; eauth is respected
This function requires that :conf_master:`external_auth` is configured
and the user is authorized to execute runner functions: (``@runner``).
.. code-block:: python
runner.eauth_async({
\'fun\': \'jobs.list_jobs\',
\'username\': \'saltdev\',
\'password\': \'... | def cmd_async(self, low):
| reformatted_low = self._reformat_low(low)
return mixins.AsyncClientMixin.cmd_async(self, reformatted_low)
|
'Execute a runner function synchronously; eauth is respected
This function requires that :conf_master:`external_auth` is configured
and the user is authorized to execute runner functions: (``@runner``).
.. code-block:: python
runner.eauth_sync({
\'fun\': \'jobs.list_jobs\',
\'username\': \'saltdev\',
\'password\': \'sa... | def cmd_sync(self, low, timeout=None, full_return=False):
| reformatted_low = self._reformat_low(low)
return mixins.SyncClientMixin.cmd_sync(self, reformatted_low, timeout, full_return)
|
'Execute a function'
| def cmd(self, fun, arg=None, pub_data=None, kwarg=None, print_event=True, full_return=False):
| return super(RunnerClient, self).cmd(fun, arg, pub_data, kwarg, print_event, full_return)
|
'Print out the documentation!'
| def print_docs(self):
| arg = self.opts.get(u'fun', None)
docs = super(Runner, self).get_docs(arg)
for fun in sorted(docs):
display_output(u'{0}:'.format(fun), u'text', self.opts)
print(docs[fun])
|
'Execute the runner sequence'
| def run(self):
| import salt.minion
ret = {}
if self.opts.get(u'doc', False):
self.print_docs()
else:
low = {u'fun': self.opts[u'fun']}
try:
async_pub = self._gen_async_pub()
self.jid = async_pub[u'jid']
fun_args = salt.utils.args.parse_input(self.opts[u'arg'],... |
'Pack this exception into a serializable dictionary that is safe for
transport via msgpack'
| def pack(self):
| if six.PY3:
return {u'message': str(self), u'args': self.args}
return dict(message=self.__unicode__(), args=self.args)
|
'Recursively iterate down through data structures to determine output'
| def display(self, ret, indent, prefix, out):
| if isinstance(ret, six.string_types):
lines = ret.split(u'\n')
for line in lines:
out += u'{0}{1}{2}{3}{4}\n'.format(self.colors[u'RED'], (u' ' * indent), prefix, line, self.colors[u'ENDC'])
elif isinstance(ret, dict):
for key in sorted(ret):
val = ret[key]
... |
'Build the unicode string to be displayed.'
| def ustring(self, indent, color, msg, prefix='', suffix='', endc=None):
| if (endc is None):
endc = self.ENDC
indent *= ' '
fmt = u'{0}{1}{2}{3}{4}{5}'
try:
return fmt.format(indent, color, prefix, msg, endc, suffix)
except UnicodeDecodeError:
return fmt.format(indent, color, prefix, salt.utils.locales.sdecode(msg), endc, suffix)
|
'When the text inside the column is longer then the width, will split by space and continue on the next line.'
| def wrap_onspace(self, text):
| def _truncate(line, word):
return '{line}{part}{word}'.format(line=line, part=' \n'[((len(line[(line.rfind('\n') + 1):]) + len(word.split('\n', 1)[0])) >= self.width)], word=word)
return reduce(_truncate, text.split(' '))
|
'Prepare rows content to be displayed.'
| def prepare_rows(self, rows, indent, has_header):
| out = []
def row_wrapper(row):
new_rows = [self.wrapfunc(item).split('\n') for item in row]
rows = []
for item in map(None, *new_rows):
if isinstance(item, (tuple, list)):
rows.append([(substr or '') for substr in item])
else:
rows.... |
'Prepares row content and displays.'
| def display_rows(self, rows, labels, indent):
| out = []
if (not rows):
return out
first_row_type = type(rows[0])
consistent = True
for row in rows[1:]:
if (type(row) != first_row_type):
consistent = False
if (not consistent):
return out
if isinstance(labels, dict):
labels_temp = []
for ... |
'Display table(s).'
| def display(self, ret, indent, out, rows_key=None, labels_key=None):
| rows = []
labels = None
if isinstance(ret, dict):
if ((not rows_key) or (rows_key and (rows_key in list(ret.keys())))):
for key in sorted(ret):
if (rows_key and (key != rows_key)):
continue
val = ret[key]
if (not rows_ke... |
'Recursively iterate down through data structures to determine output'
| def display(self, ret, indent, prefix, out):
| if ((ret is None) or (ret is True) or (ret is False)):
out.append(self.ustring(indent, self.LIGHT_YELLOW, ret, prefix=prefix))
elif isinstance(ret, Number):
out.append(self.ustring(indent, self.LIGHT_YELLOW, ret, prefix=prefix))
elif isinstance(ret, string_types):
first_line = True
... |
':param attrs: are the attribute names of any format codes in `codes`
:param kwargs: may contain
`x`, an integer in the range [0-255] that selects the corresponding
color from the extended ANSI 256 color space for foreground text
`rgb`, an iterable of 3 integers in the range [0-255] that select the
corresponding colors... | def __init__(self, *attrs, **kwargs):
| self.codes = [codes[attr.lower()] for attr in attrs if isinstance(attr, six.string_types)]
if kwargs.get(u'reset', True):
self.codes[:0] = [codes[u'reset']]
def qualify_int(i):
if isinstance(i, int):
return (i % 256)
def qualify_triple_int(t):
if (isinstance(t, (list,... |
'Format :param text: by prefixing `self.sequence` and suffixing the
reset sequence if :param reset: is `True`.
Examples:
.. code-block:: python
green_blink_text = TextFormat(\'blink\', \'green\')
\'The answer is: {0}\'.format(green_blink_text(42))'
| def __call__(self, text, reset=True):
| end = (TextFormat(u'reset') if reset else u'')
return (u'%s%s%s' % (self.sequence, text, end))
|
'Gather the specified data from the minion data cache'
| def gather_cache(self):
| cache = {'grains': {}, 'pillar': {}}
if (self.grains or self.pillar):
if self.opts.get('minion_data_cache'):
minions = self.cache.ls('minions')
if (not minions):
return cache
for minion in minions:
total = self.cache.fetch('minions/{0}'... |
'Start the system!'
| def start_runtime(self):
| while True:
try:
self.call_runtime()
except Exception:
log.error('Exception in Thorium: ', exc_info=True)
time.sleep(self.opts['thorium_interval'])
|
'Compile the top file and return the lowstate for the thorium runtime
to iterate over'
| def get_chunks(self, exclude=None, whitelist=None):
| ret = {}
err = []
try:
top = self.get_top()
except SaltRenderError as err:
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if (not matches):
m... |
'iterate over the available events and return a list of events'
| def get_events(self):
| ret = []
while True:
event = self.event.get_event(wait=1, full=True)
if (event is None):
return ret
ret.append(event)
|
'Execute the runtime'
| def call_runtime(self):
| cache = self.gather_cache()
chunks = self.get_chunks()
interval = self.opts['thorium_interval']
recompile = self.opts.get('thorium_recompile', 300)
r_start = time.time()
while True:
events = self.get_events()
if (not events):
time.sleep(interval)
continue
... |
'Set the opts dict to defaults and allow for opts to be overridden in
the kwargs'
| def _opts_defaults(self, **kwargs):
| opts = salt.config.DEFAULT_CLOUD_OPTS.copy()
opts.update(self.opts.copy())
opts['parallel'] = False
opts['keep_tmp'] = False
opts['deploy'] = True
opts['update_bootstrap'] = False
opts['show_deploy_args'] = False
opts['script_args'] = ''
if ('kwargs' in kwargs):
opts.update(k... |
'Pass the cloud function and low data structure to run'
| def low(self, fun, low):
| l_fun = getattr(self, fun)
f_call = salt.utils.format_call(l_fun, low)
return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {}))
|
'List all available sizes in configured cloud systems'
| def list_sizes(self, provider=None):
| mapper = salt.cloud.Map(self._opts_defaults())
return salt.utils.simple_types_filter(mapper.size_list(provider))
|
'List all available images in configured cloud systems'
| def list_images(self, provider=None):
| mapper = salt.cloud.Map(self._opts_defaults())
return salt.utils.simple_types_filter(mapper.image_list(provider))
|
'List all available locations in configured cloud systems'
| def list_locations(self, provider=None):
| mapper = salt.cloud.Map(self._opts_defaults())
return salt.utils.simple_types_filter(mapper.location_list(provider))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.