desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Merge managed keys with local keys'
def all_keys(self):
keys = self.list_keys() keys.update(self.local_keys()) return keys
'Return a dict of managed keys under a named status'
def list_status(self, match):
(acc, pre, rej, den) = self._check_minions_directories() ret = {} if match.startswith(u'acc'): ret[os.path.basename(acc)] = [] for fn_ in salt.utils.isorted(os.listdir(acc)): if (not fn_.startswith(u'.')): if os.path.isfile(os.path.join(acc, fn_)): ...
'Return the specified public key or keys based on a glob'
def key_str(self, match):
ret = {} for (status, keys) in six.iteritems(self.name_match(match)): ret[status] = {} for key in salt.utils.isorted(keys): path = os.path.join(self.opts[u'pki_dir'], status, key) with salt.utils.files.fopen(path, u'r') as fp_: ret[status][key] = fp_.read(...
'Return all managed key strings'
def key_str_all(self):
ret = {} for (status, keys) in six.iteritems(self.list_keys()): ret[status] = {} for key in salt.utils.isorted(keys): path = os.path.join(self.opts[u'pki_dir'], status, key) with salt.utils.files.fopen(path, u'r') as fp_: ret[status][key] = fp_.read() ...
'Accept public keys. If "match" is passed, it is evaluated as a glob. Pre-gathered matches can also be passed via "match_dict".'
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
if (match is not None): matches = self.name_match(match) elif ((match_dict is not None) and isinstance(match_dict, dict)): matches = match_dict else: matches = {} keydirs = [self.PEND] if include_rejected: keydirs.append(self.REJ) if include_denied: keydir...
'Accept all keys in pre'
def accept_all(self):
keys = self.list_keys() for key in keys[self.PEND]: try: shutil.move(os.path.join(self.opts[u'pki_dir'], self.PEND, key), os.path.join(self.opts[u'pki_dir'], self.ACC, key)) eload = {u'result': True, u'act': u'accept', u'id': key} self.event.fire_event(eload, salt.uti...
'Delete public keys. If "match" is passed, it is evaluated as a glob. Pre-gathered matches can also be passed via "match_dict". To preserve the master caches of minions who are matched, set preserve_minions'
def delete_key(self, match=None, match_dict=None, preserve_minions=False, revoke_auth=False):
if (match is not None): matches = self.name_match(match) elif ((match_dict is not None) and isinstance(match_dict, dict)): matches = match_dict else: matches = {} for (status, keys) in six.iteritems(matches): for key in keys: try: if revoke_aut...
'Delete all denied keys'
def delete_den(self):
keys = self.list_keys() for (status, keys) in six.iteritems(self.list_keys()): for key in keys[self.DEN]: try: os.remove(os.path.join(self.opts[u'pki_dir'], status, key)) eload = {u'result': True, u'act': u'delete', u'id': key} self.event.fire_...
'Delete all keys'
def delete_all(self):
for (status, keys) in six.iteritems(self.list_keys()): for key in keys: try: os.remove(os.path.join(self.opts[u'pki_dir'], status, key)) eload = {u'result': True, u'act': u'delete', u'id': key} self.event.fire_event(eload, salt.utils.event.tagify(p...
'Reject public keys. If "match" is passed, it is evaluated as a glob. Pre-gathered matches can also be passed via "match_dict".'
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
if (match is not None): matches = self.name_match(match) elif ((match_dict is not None) and isinstance(match_dict, dict)): matches = match_dict else: matches = {} keydirs = [self.PEND] if include_accepted: keydirs.append(self.ACC) if include_denied: keydir...
'Reject all keys in pre'
def reject_all(self):
keys = self.list_keys() for key in keys[self.PEND]: try: shutil.move(os.path.join(self.opts[u'pki_dir'], self.PEND, key), os.path.join(self.opts[u'pki_dir'], self.REJ, key)) eload = {u'result': True, u'act': u'reject', u'id': key} self.event.fire_event(eload, salt.uti...
'Return the fingerprint for a specified key'
def finger(self, match, hash_type=None):
if (hash_type is None): hash_type = __opts__[u'hash_type'] matches = self.name_match(match, True) ret = {} for (status, keys) in six.iteritems(matches): ret[status] = {} for key in keys: if (status == u'local'): path = os.path.join(self.opts[u'pki_dir'...
'Return fingerprints for all keys'
def finger_all(self, hash_type=None):
if (hash_type is None): hash_type = __opts__[u'hash_type'] ret = {} for (status, keys) in six.iteritems(self.all_keys()): ret[status] = {} for key in keys: if (status == u'local'): path = os.path.join(self.opts[u'pki_dir'], key) else: ...
'Return the minion keys directory paths'
def _check_minions_directories(self):
accepted = os.path.join(self.opts[u'pki_dir'], self.ACC) pre = os.path.join(self.opts[u'pki_dir'], self.PEND) rejected = os.path.join(self.opts[u'pki_dir'], self.REJ) return (accepted, pre, rejected, None)
'Check the minion cache to make sure that old minion data is cleared'
def check_minion_cache(self, preserve_minions=False):
keys = self.list_keys() minions = [] for (key, val) in six.iteritems(keys): minions.extend(val) m_cache = os.path.join(self.opts[u'cachedir'], u'minions') if os.path.isdir(m_cache): for minion in os.listdir(m_cache): if (minion not in minions): shutil.rmtr...
'Use libnacl to generate and safely save a private key'
def gen_keys(self, keydir=None, keyname=None, keysize=None, user=None):
import libnacl.dual d_key = libnacl.dual.DualSecret() (keydir, keyname, _, _) = self._get_key_attrs(keydir, keyname, keysize, user) path = u'{0}.key'.format(os.path.join(keydir, keyname)) d_key.save(path, u'msgpack')
'Log if the master is not running NOT YET IMPLEMENTED'
def check_master(self):
return True
'Return a dict of local keys'
def local_keys(self):
ret = {u'local': []} fn_ = os.path.join(self.opts[u'pki_dir'], u'local.key') if os.path.isfile(fn_): ret[u'local'].append(fn_) return ret
'Accepts the minion id, device id, curve public and verify keys. If the key is not present, put it in pending and return "pending", If the key has been accepted return "accepted" if the key should be rejected, return "rejected"'
def status(self, minion_id, pub, verify):
(acc, pre, rej, _) = self._check_minions_directories() acc_path = os.path.join(acc, minion_id) pre_path = os.path.join(pre, minion_id) rej_path = os.path.join(rej, minion_id) keydata = {u'minion_id': minion_id, u'pub': pub, u'verify': verify} if self.opts[u'open_mode']: with salt.utils.f...
'Return the key string in the form of: pub: <pub> verify: <verify>'
def _get_key_str(self, minion_id, status):
path = os.path.join(self.opts[u'pki_dir'], status, minion_id) with salt.utils.files.fopen(path, u'r') as fp_: keydata = self.serial.loads(fp_.read()) return u'pub: {0}\nverify: {1}'.format(keydata[u'pub'], keydata[u'verify'])
'Return a sha256 kingerprint for the key'
def _get_key_finger(self, path):
with salt.utils.files.fopen(path, u'r') as fp_: keydata = self.serial.loads(fp_.read()) key = u'pub: {0}\nverify: {1}'.format(keydata[u'pub'], keydata[u'verify']) return hashlib.sha256(key).hexdigest()
'Return the specified public key or keys based on a glob'
def key_str(self, match):
ret = {} for (status, keys) in six.iteritems(self.name_match(match)): ret[status] = {} for key in salt.utils.isorted(keys): ret[status][key] = self._get_key_str(key, status) return ret
'Return all managed key strings'
def key_str_all(self):
ret = {} for (status, keys) in six.iteritems(self.list_keys()): ret[status] = {} for key in salt.utils.isorted(keys): ret[status][key] = self._get_key_str(key, status) return ret
'Accept public keys. If "match" is passed, it is evaluated as a glob. Pre-gathered matches can also be passed via "match_dict".'
def accept(self, match=None, match_dict=None, include_rejected=False, include_denied=False):
if (match is not None): matches = self.name_match(match) elif ((match_dict is not None) and isinstance(match_dict, dict)): matches = match_dict else: matches = {} keydirs = [self.PEND] if include_rejected: keydirs.append(self.REJ) if include_denied: keydir...
'Accept all keys in pre'
def accept_all(self):
keys = self.list_keys() for key in keys[self.PEND]: try: shutil.move(os.path.join(self.opts[u'pki_dir'], self.PEND, key), os.path.join(self.opts[u'pki_dir'], self.ACC, key)) except (IOError, OSError): pass return self.list_keys()
'Delete public keys. If "match" is passed, it is evaluated as a glob. Pre-gathered matches can also be passed via "match_dict".'
def delete_key(self, match=None, match_dict=None, preserve_minions=False, revoke_auth=False):
if (match is not None): matches = self.name_match(match) elif ((match_dict is not None) and isinstance(match_dict, dict)): matches = match_dict else: matches = {} for (status, keys) in six.iteritems(matches): for key in keys: if revoke_auth: if...
'Delete all keys'
def delete_all(self):
for (status, keys) in six.iteritems(self.list_keys()): for key in keys: try: os.remove(os.path.join(self.opts[u'pki_dir'], status, key)) except (OSError, IOError): pass self.check_minion_cache() return self.list_keys()
'Reject public keys. If "match" is passed, it is evaluated as a glob. Pre-gathered matches can also be passed via "match_dict".'
def reject(self, match=None, match_dict=None, include_accepted=False, include_denied=False):
if (match is not None): matches = self.name_match(match) elif ((match_dict is not None) and isinstance(match_dict, dict)): matches = match_dict else: matches = {} keydirs = [self.PEND] if include_accepted: keydirs.append(self.ACC) if include_denied: keydir...
'Reject all keys in pre'
def reject_all(self):
keys = self.list_keys() for key in keys[self.PEND]: try: shutil.move(os.path.join(self.opts[u'pki_dir'], self.PEND, key), os.path.join(self.opts[u'pki_dir'], self.REJ, key)) except (IOError, OSError): pass self.check_minion_cache() return self.list_keys()
'Return the fingerprint for a specified key'
def finger(self, match, hash_type=None):
if (hash_type is None): hash_type = __opts__[u'hash_type'] matches = self.name_match(match, True) ret = {} for (status, keys) in six.iteritems(matches): ret[status] = {} for key in keys: if (status == u'local'): path = os.path.join(self.opts[u'pki_dir'...
'Return fingerprints for all keys'
def finger_all(self, hash_type=None):
if (hash_type is None): hash_type = __opts__[u'hash_type'] ret = {} for (status, keys) in six.iteritems(self.list_keys()): ret[status] = {} for key in keys: if (status == u'local'): path = os.path.join(self.opts[u'pki_dir'], key) else: ...
'Return a dict of all remote key data'
def read_all_remote(self):
data = {} for (status, mids) in six.iteritems(self.list_keys()): for mid in mids: keydata = self.read_remote(mid, status) if keydata: keydata[u'acceptance'] = status data[mid] = keydata return data
'Read in a remote key of status'
def read_remote(self, minion_id, status=ACC):
path = os.path.join(self.opts[u'pki_dir'], status, minion_id) if (not os.path.isfile(path)): return {} with salt.utils.files.fopen(path, u'rb') as fp_: return self.serial.loads(fp_.read())
'Read in the local private keys, return an empy dict if the keys do not exist'
def read_local(self):
path = os.path.join(self.opts[u'pki_dir'], u'local.key') if (not os.path.isfile(path)): return {} with salt.utils.files.fopen(path, u'rb') as fp_: return self.serial.loads(fp_.read())
'Write the private key and the signing key to a file on disk'
def write_local(self, priv, sign):
keydata = {u'priv': priv, u'sign': sign} path = os.path.join(self.opts[u'pki_dir'], u'local.key') c_umask = os.umask(191) if os.path.exists(path): os.chmod(path, (stat.S_IWUSR | stat.S_IRUSR)) with salt.utils.files.fopen(path, u'w+') as fp_: fp_.write(self.serial.dumps(keydata)) ...
'Delete the local private key file'
def delete_local(self):
path = os.path.join(self.opts[u'pki_dir'], u'local.key') if os.path.isfile(path): os.remove(path)
'Delete the private key directory'
def delete_pki_dir(self):
path = self.opts[u'pki_dir'] if os.path.exists(path): shutil.rmtree(path)
'Return a list of loaded roster backends'
def _gen_back(self):
back = set() if self.backends: for backend in self.backends: fun = '{0}.targets'.format(backend) if (fun in self.rosters): back.add(backend) return back return sorted(back)
'Return a dict of {\'id\': {\'ipv4\': <ipaddr>}} data sets to be used as targets given the passed tgt and tgt_type'
def targets(self, tgt, tgt_type):
targets = {} for back in self._gen_back(): f_str = '{0}.targets'.format(back) if (f_str not in self.rosters): continue try: targets.update(self.rosters[f_str](tgt, tgt_type)) except salt.exceptions.SaltRenderError as exc: log.error('Unable t...
'Execute the correct tgt_type routine and return'
def targets(self):
try: routine = getattr(self, 'get_{0}'.format(self.tgt_type)) except AttributeError: return {} return routine()
'Return minions that match via glob'
def get_glob(self):
ret = dict() for (key, value) in six.iteritems(self.groups): for (host, info) in six.iteritems(value): if fnmatch.fnmatch(host, self.tgt): ret[host] = info for nodegroup in self.groups: if fnmatch.fnmatch(nodegroup, self.tgt): ret.update(self.groups[no...
'Recursively resolve all [*:children] group blocks'
def _get_parent(self, parent_nodegroup):
ret = dict() for nodegroup in self.parents[parent_nodegroup]: if (nodegroup in self.parents): ret.update(self._get_parent(nodegroup)) elif (nodegroup in self.groups): ret.update(self.groups[nodegroup]) return ret
'Parse lines in the inventory file that are under the same group block'
def _parse_group_line(self, line, varname):
line_args = salt.utils.args.shlex_split(line) name = line_args[0] host = {line_args[0]: dict()} for arg in line_args[1:]: (key, value) = arg.split('=') host[name][CONVERSION[key]] = value if ('sudo' in host[name]): (host[name]['passwd'], host[name]['sudo']) = (host[name]['sud...
'Parse lines in the inventory file that are under the same [*:vars] block'
def _parse_hostvars_line(self, line, varname):
(key, value) = line.split('=') if (varname not in self.hostvars): self.hostvars[varname] = dict() self.hostvars[varname][key] = value
'Parse lines in the inventory file that are under the same [*:children] block'
def _parse_parents_line(self, line, varname):
if (varname not in self.parents): self.parents[varname] = [] self.parents[varname].append(line)
'Parse group data from inventory_file'
def _parse_groups(self, key, value):
host = dict() if (key not in self.groups): self.groups[key] = dict() for server in value: tmp = self.meta.get('hostvars', {}).get(server, False) if (tmp is not False): if (server not in host): host[server] = dict() for (tmpkey, tmpval) in six.i...
'Parse hostvars data from inventory_file'
def _parse_hostvars(self, key, value):
if (key not in self.hostvars): self.hostvars[key] = dict() self.hostvars[key] = value
'Parse children data from inventory_file'
def _parse_parents(self, key, value):
if (key not in self.parents): self.parents[key] = [] self.parents[key].extend(value)
'Return ip addrs based on netmask, sitting in the "glob" spot because it is the default'
def targets(self):
addrs = () ret = {} ports = __opts__['ssh_scan_ports'] if (not isinstance(ports, list)): ports = list(map(int, str(ports).split(','))) try: addrs = [ipaddress.ip_address(self.tgt)] except ValueError: try: addrs = ipaddress.ip_network(self.tgt).hosts() ...
'Execute the correct tgt_type routine and return'
def targets(self):
try: return getattr(self, 'ret_{0}_minions'.format(self.tgt_type))() except AttributeError: return {}
'Return minions that match via glob'
def ret_glob_minions(self):
minions = {} for minion in self.raw: if fnmatch.fnmatch(minion, self.tgt): data = self.get_data(minion) if data: minions[minion] = data return minions
'Return minions that match via pcre'
def ret_pcre_minions(self):
minions = {} for minion in self.raw: if re.match(self.tgt, minion): data = self.get_data(minion) if data: minions[minion] = data return minions
'Return minions that match via list'
def ret_list_minions(self):
minions = {} if (not isinstance(self.tgt, list)): self.tgt = self.tgt.split(',') for minion in self.raw: if (minion in self.tgt): data = self.get_data(minion) if data: minions[minion] = data return minions
'Return minions which match the special list-only groups defined by ssh_list_nodegroups'
def ret_nodegroup_minions(self):
minions = {} nodegroup = __opts__.get('ssh_list_nodegroups', {}).get(self.tgt, []) if (not isinstance(nodegroup, list)): nodegroup = nodegroup.split(',') for minion in self.raw: if (minion in nodegroup): data = self.get_data(minion) if data: minion...
'Return minions that are returned by a range query'
def ret_range_minions(self):
if (HAS_RANGE is False): raise RuntimeError("Python lib 'seco.range' is not available") minions = {} range_hosts = _convert_range_to_list(self.tgt, __opts__['range_server']) for minion in self.raw: if (minion in range_hosts): data = self.get_data(minion) ...
'Return the configured ip'
def get_data(self, minion):
ret = __opts__.get('roster_defaults', {}) if isinstance(self.raw[minion], string_types): ret.update({'host': self.raw[minion]}) return ret elif isinstance(self.raw[minion], dict): ret.update(self.raw[minion]) return ret return False
'Enforce the states in a template'
def render_template(self, template, **kwargs):
high = compile_template(template, self.rend, self.opts[u'renderer'], self.opts[u'renderer_blacklist'], self.opts[u'renderer_whitelist'], **kwargs) if (not high): return high return self.pad_funcs(high)
'Turns dot delimited function refs into function strings'
def pad_funcs(self, high):
for name in high: if (not isinstance(high[name], dict)): if isinstance(high[name], six.string_types): if (u'.' in high[name]): comps = high[name].split(u'.') if (len(comps) >= 2): comps[1] = u'.'.join(comps[1:len(com...
'Verify that the high data is viable and follows the data structure'
def verify_high(self, high):
errors = [] if (not isinstance(high, dict)): errors.append(u'High data is not a dictionary and is invalid') reqs = OrderedDict() for (name, body) in six.iteritems(high): if name.startswith(u'__'): continue if (not isinstance(name, six.string_ty...
'Sort the chunk list verifying that the chunks follow the order specified in the order options.'
def order_chunks(self, chunks):
cap = 1 for chunk in chunks: if (u'order' in chunk): if (not isinstance(chunk[u'order'], int)): continue chunk_order = chunk[u'order'] if ((chunk_order > (cap - 1)) and (chunk_order > 0)): cap = (chunk_order + 100) for chunk in chun...
'"Compile" the high data as it is retrieved from the CLI or YAML into the individual state executor structures'
def compile_high_data(self, high):
chunks = [] for (name, body) in six.iteritems(high): if name.startswith(u'__'): continue for (state, run) in six.iteritems(body): funcs = set() names = [] if state.startswith(u'__'): continue chunk = {u'state': state, u'...
'Read in the __exclude__ list and remove all excluded objects from the high data'
def apply_exclude(self, high):
if (u'__exclude__' not in high): return high ex_sls = set() ex_id = set() exclude = high.pop(u'__exclude__') for exc in exclude: if isinstance(exc, six.string_types): ex_sls.add(exc) if isinstance(exc, dict): if (len(exc) != 1): continu...
'Whenever a state run starts, gather the pillar data fresh'
def _gather_pillar(self):
if self._pillar_override: if self._pillar_enc: try: self._pillar_override = salt.utils.crypt.decrypt(self._pillar_override, self._pillar_enc, translate_newlines=True, renderers=getattr(self, u'rend', None), opts=self.opts, valid_rend=self.opts[u'decrypt_pillar_renderers']) ...
'Check the module initialization function, if this is the first run of a state package that has a mod_init function, then execute the mod_init function in the state module.'
def _mod_init(self, low):
try: self.states[u'{0}.{1}'.format(low[u'state'], low[u'fun'])] except KeyError: return minit = u'{0}.mod_init'.format(low[u'state']) if (low[u'state'] not in self.mod_init): if (minit in self.states._dict): mret = self.states[minit](low) if (not mret): ...
'Execute the aggregation systems to runtime modify the low chunk'
def _mod_aggregate(self, low, running, chunks):
agg_opt = self.functions[u'config.option'](u'state_aggregate') if (u'aggregate' in low): agg_opt = low[u'aggregate'] if (agg_opt is True): agg_opt = [low[u'state']] elif (not isinstance(agg_opt, list)): return low if ((low[u'state'] in agg_opt) and (not low.get(u'__agg__'))):...
'Check that unless doesn\'t return 0, and that onlyif returns a 0.'
def _run_check(self, low_data):
ret = {u'result': False} cmd_opts = {} if (u'shell' in self.opts[u'grains']): cmd_opts[u'shell'] = self.opts[u'grains'].get(u'shell') if (u'onlyif' in low_data): if (not isinstance(low_data[u'onlyif'], list)): low_data_onlyif = [low_data[u'onlyif']] else: ...
'Alter the way a successful state run is determined'
def _run_check_cmd(self, low_data):
ret = {u'result': False} cmd_opts = {} if (u'shell' in self.opts[u'grains']): cmd_opts[u'shell'] = self.opts[u'grains'].get(u'shell') for entry in low_data[u'check_cmd']: cmd = self.functions[u'cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts) log.debug(u'L...
'Rest the run_num value to 0'
def reset_run_num(self):
self.__run_num = 0
'Read the state loader value and loadup the correct states subsystem'
def _load_states(self):
if (self.states_loader == u'thorium'): self.states = salt.loader.thorium(self.opts, self.functions, {}) else: self.states = salt.loader.states(self.opts, self.functions, self.utils, self.serializers, proxy=self.proxy)
'Load the modules into the state'
def load_modules(self, data=None, proxy=None):
log.info(u'Loading fresh modules for state activity') self.utils = salt.loader.utils(self.opts) self.functions = salt.loader.minion_mods(self.opts, self.state_con, utils=self.utils, proxy=self.proxy) if isinstance(data, dict): if data.get(u'provider', False): if isinst...
'Refresh all the modules'
def module_refresh(self):
log.debug(u'Refreshing modules...') if (self.opts[u'grains'].get(u'os') != u'MacOS'): try: reload_module(site) except RuntimeError: log.error(u'Error encountered during module reload. Modules were not reloaded.') except TypeError: ...
'Check to see if the modules for this state instance need to be updated, only update if the state is a file or a package and if it changed something. If the file function is managed check to see if the file is a possible module type, e.g. a python, pyx, or .so. Always refresh if the function is recurse, since that can ...
def check_refresh(self, data, ret):
_reload_modules = False if data.get(u'reload_grains', False): log.debug(u'Refreshing grains...') self.opts[u'grains'] = salt.loader.grains(self.opts) _reload_modules = True if data.get(u'reload_pillar', False): log.debug(u'Refreshing pillar...') self.opts[u'pill...
'Verify the state return data'
def verify_ret(self, ret):
if (not isinstance(ret, dict)): raise SaltException(u'Malformed state return, return must be a dict') bad = [] for val in [u'name', u'result', u'changes', u'comment']: if (val not in ret): bad.append(val) if bad: raise SaltException(u'The follo...
'Verify the data, return an error statement if something is wrong'
def verify_data(self, data):
errors = [] if (u'state' not in data): errors.append(u'Missing "state" data') if (u'fun' not in data): errors.append(u'Missing "fun" data') if (u'name' not in data): errors.append(u'Missing "name" data') if (data[u'name'] and (not isinstance(data[u'name'], s...
'Verify that the high data is viable and follows the data structure'
def verify_high(self, high):
errors = [] if (not isinstance(high, dict)): errors.append(u'High data is not a dictionary and is invalid') reqs = OrderedDict() for (name, body) in six.iteritems(high): try: if name.startswith(u'__'): continue except AttributeE...
'Verify the chunks in a list of low data structures'
def verify_chunks(self, chunks):
err = [] for chunk in chunks: err += self.verify_data(chunk) return err
'Sort the chunk list verifying that the chunks follow the order specified in the order options.'
def order_chunks(self, chunks):
cap = 1 for chunk in chunks: if (u'order' in chunk): if (not isinstance(chunk[u'order'], int)): continue chunk_order = chunk[u'order'] if ((chunk_order > (cap - 1)) and (chunk_order > 0)): cap = (chunk_order + 100) for chunk in chun...
'"Compile" the high data as it is retrieved from the CLI or YAML into the individual state executor structures'
def compile_high_data(self, high, orchestration_jid=None):
chunks = [] for (name, body) in six.iteritems(high): if name.startswith(u'__'): continue for (state, run) in six.iteritems(body): funcs = set() names = [] if state.startswith(u'__'): continue chunk = {u'state': state, u'...
'Pull the extend data and add it to the respective high data'
def reconcile_extend(self, high):
errors = [] if (u'__extend__' not in high): return (high, errors) ext = high.pop(u'__extend__') for ext_chunk in ext: for (name, body) in six.iteritems(ext_chunk): if (name not in high): state_type = next((x for x in body if (not x.startswith(u'__')))) ...
'Read in the __exclude__ list and remove all excluded objects from the high data'
def apply_exclude(self, high):
if (u'__exclude__' not in high): return high ex_sls = set() ex_id = set() exclude = high.pop(u'__exclude__') for exc in exclude: if isinstance(exc, six.string_types): ex_sls.add(exc) if isinstance(exc, dict): if (len(exc) != 1): continu...
'Extend the data reference with requisite_in arguments'
def requisite_in(self, high):
req_in = set([u'require_in', u'watch_in', u'onfail_in', u'onchanges_in', u'use', u'use_in', u'prereq', u'prereq_in']) req_in_all = req_in.union(set([u'require', u'watch', u'onfail', u'onfail_stop', u'onchanges'])) extend = {} errors = [] for (id_, body) in six.iteritems(high): if (not isinst...
'The target function to call that will create the parallel thread/process'
def _call_parallel_target(self, cdata, low):
tag = _gen_tag(low) try: ret = self.states[cdata[u'full']](*cdata[u'args'], **cdata[u'kwargs']) except Exception: trb = traceback.format_exc() if (len(cdata[u'args']) > 0): name = cdata[u'args'][0] elif (u'name' in cdata[u'kwargs']): name = cdata[u'kwa...
'Call the state defined in the given cdata in parallel'
def call_parallel(self, cdata, low):
proc = salt.utils.process.MultiprocessingProcess(target=self._call_parallel_target, args=(cdata, low)) proc.start() ret = {u'name': cdata[u'args'][0], u'result': None, u'changes': {}, u'comment': u'Started in a seperate process', u'proc': proc} return ret
'Call a state directly with the low data structure, verify data before processing.'
def call(self, low, chunks=None, running=None, retries=1):
utc_start_time = datetime.datetime.utcnow() local_start_time = (utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())) log.info(u'Running state [%s] at time %s', (low[u'name'].strip() if isinstance(low[u'name'], six.string_types) else low[u'name']), local_start_time.time().i...
'verifies the specified retry data'
def verify_retry_data(self, retry_data):
retry_defaults = {u'until': True, u'attempts': 2, u'splay': 0, u'interval': 30} expected_data = {u'until': bool, u'attempts': int, u'interval': int, u'splay': int} validated_retry_data = {} if isinstance(retry_data, dict): for (expected_key, value_type) in six.iteritems(expected_data): ...
'Iterate over a list of chunks and call them, checking for requires.'
def call_chunks(self, chunks):
disabled = {} if (u'state_runs_disabled' in self.opts[u'grains']): for low in chunks[:]: state_ = u'{0}.{1}'.format(low[u'state'], low[u'fun']) for pat in self.opts[u'grains'][u'state_runs_disabled']: if fnmatch.fnmatch(state_, pat): comment = ...
'Check if the low data chunk should send a failhard signal'
def check_failhard(self, low, running):
tag = _gen_tag(low) if self.opts.get(u'test', False): return False if ((low.get(u'failhard', False) or self.opts[u'failhard']) and (tag in running)): if (running[tag][u'result'] is None): return False return (not running[tag][u'result']) return False
'Check the running dict for processes and resolve them'
def reconcile_procs(self, running):
retset = set() for tag in running: proc = running[tag].get(u'proc') if proc: if (not proc.is_alive()): ret_cache = os.path.join(self.opts[u'cachedir'], self.jid, tag) if (not os.path.isfile(ret_cache)): ret = {u'result': False, u'co...
'Look into the running data to check the status of all requisite states'
def check_requisite(self, low, running, chunks, pre=False):
present = False if (u'watch' in low): if (u'{0}.mod_watch'.format(low[u'state']) not in self.states): if (u'require' in low): low[u'require'].extend(low.pop(u'watch')) else: low[u'require'] = low.pop(u'watch') else: present = Tr...
'Fire an event on the master bus If `fire_event` is set to True an event will be sent with the chunk name in the tag and the chunk result in the event data. If `fire_event` is set to a string such as `mystate/is/finished`, an event will be sent with the string added to the tag and the chunk result in the event data. If...
def event(self, chunk_ret, length, fire_event=False):
if ((not self.opts.get(u'local')) and (self.opts.get(u'state_events', True) or fire_event)): if (not self.opts.get(u'master_uri')): ev_func = (lambda ret, tag, preload=None: salt.utils.event.get_master_event(self.opts, self.opts[u'sock_dir'], listen=False).fire_event(ret, tag)) else: ...
'Check if a chunk has any requires, execute the requires and then the chunk'
def call_chunk(self, low, running, chunks):
low = self._mod_aggregate(low, running, chunks) self._mod_init(low) tag = _gen_tag(low) if (not low.get(u'prerequired')): self.active.add(tag) requisites = [u'require', u'watch', u'prereq', u'onfail', u'onchanges'] if (not low.get(u'__prereq__')): requisites.append(u'prerequired'...
'Find all of the listen routines and call the associated mod_watch runs'
def call_listen(self, chunks, running):
listeners = [] crefs = {} for chunk in chunks: crefs[(chunk[u'state'], chunk[u'name'])] = chunk crefs[(chunk[u'state'], chunk[u'__id__'])] = chunk if (u'listen' in chunk): listeners.append({(chunk[u'state'], chunk[u'__id__']): chunk[u'listen']}) if (u'listen_in' i...
'Process a high data call and ensure the defined states.'
def call_high(self, high, orchestration_jid=None):
errors = [] (high, ext_errors) = self.reconcile_extend(high) errors += ext_errors errors += self.verify_high(high) if errors: return errors (high, req_in_errors) = self.requisite_in(high) errors += req_in_errors high = self.apply_exclude(high) if errors: return errors...
'Enforce the states in a template'
def call_template(self, template):
high = compile_template(template, self.rend, self.opts[u'renderer'], self.opts[u'renderer_blacklist'], self.opts[u'renderer_whitelist']) if (not high): return high (high, errors) = self.render_template(high, template) if errors: return errors return self.call_high(high)
'Enforce the states in a template, pass the template as a string'
def call_template_str(self, template):
high = compile_template_str(template, self.rend, self.opts[u'renderer'], self.opts[u'renderer_blacklist'], self.opts[u'renderer_whitelist']) if (not high): return high (high, errors) = self.render_template(high, u'<template-str>') if errors: return errors return self.call_high(high)
'Gather the lists of available sls data from the master'
def __gather_avail(self):
avail = {} for saltenv in self._get_envs(): avail[saltenv] = self.client.list_states(saltenv) return avail
'The options used by the High State object are derived from options on the minion and the master, or just the minion if the high state call is entirely local.'
def __gen_opts(self, opts):
if (u'local_state' in opts): if opts[u'local_state']: return opts mopts = self.client.master_opts() if (not isinstance(mopts, dict)): opts[u'renderer'] = u'yaml_jinja' opts[u'failhard'] = False opts[u'state_top'] = salt.utils.url.create(u'top.sls') opts[u'...
'Pull the file server environments out of the master options'
def _get_envs(self):
envs = [u'base'] if (u'file_roots' in self.opts): envs.extend([x for x in list(self.opts[u'file_roots']) if (x not in envs)]) env_order = self.opts.get(u'env_order', []) members = set() env_order = [env for env in env_order if (not ((env in members) or members.add(env)))] client_envs = s...
'Gather the top files'
def get_tops(self):
tops = DefaultOrderedDict(list) include = DefaultOrderedDict(list) done = DefaultOrderedDict(list) found = 0 merging_strategy = self.opts[u'top_file_merging_strategy'] if ((merging_strategy == u'same') and (not self.opts[u'environment'])): if (not self.opts[u'default_top']): ...
'Cleanly merge the top files'
def merge_tops(self, tops):
merging_strategy = self.opts[u'top_file_merging_strategy'] try: merge_attr = u'_merge_tops_{0}'.format(merging_strategy) merge_func = getattr(self, merge_attr) if (not hasattr(merge_func, u'__call__')): msg = u"'{0}' is not callable".format(merge_attr) lo...