repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/state.py | RemoteHighState.compile_master | def compile_master(self):
'''
Return the state data from the master
'''
load = {'grains': self.grains,
'opts': self.opts,
'cmd': '_master_state'}
try:
return self.channel.send(load, tries=3, timeout=72000)
except SaltReqTimeoutError:
return {} | python | def compile_master(self):
'''
Return the state data from the master
'''
load = {'grains': self.grains,
'opts': self.opts,
'cmd': '_master_state'}
try:
return self.channel.send(load, tries=3, timeout=72000)
except SaltReqTimeoutError:
return {} | [
"def",
"compile_master",
"(",
"self",
")",
":",
"load",
"=",
"{",
"'grains'",
":",
"self",
".",
"grains",
",",
"'opts'",
":",
"self",
".",
"opts",
",",
"'cmd'",
":",
"'_master_state'",
"}",
"try",
":",
"return",
"self",
".",
"channel",
".",
"send",
"... | Return the state data from the master | [
"Return",
"the",
"state",
"data",
"from",
"the",
"master"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L4348-L4358 | train |
saltstack/salt | salt/output/txt.py | output | def output(data, **kwargs): # pylint: disable=unused-argument
'''
Output the data in lines, very nice for running commands
'''
ret = ''
if hasattr(data, 'keys'):
for key in data:
value = data[key]
# Don't blow up on non-strings
try:
for line in value.splitlines():
ret += '{0}: {1}\n'.format(key, line)
except AttributeError:
ret += '{0}: {1}\n'.format(key, value)
else:
try:
ret += data + '\n'
except TypeError:
# For non-dictionary, non-string data, just use print
ret += '{0}\n'.format(pprint.pformat(data))
return ret | python | def output(data, **kwargs): # pylint: disable=unused-argument
'''
Output the data in lines, very nice for running commands
'''
ret = ''
if hasattr(data, 'keys'):
for key in data:
value = data[key]
# Don't blow up on non-strings
try:
for line in value.splitlines():
ret += '{0}: {1}\n'.format(key, line)
except AttributeError:
ret += '{0}: {1}\n'.format(key, value)
else:
try:
ret += data + '\n'
except TypeError:
# For non-dictionary, non-string data, just use print
ret += '{0}\n'.format(pprint.pformat(data))
return ret | [
"def",
"output",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"ret",
"=",
"''",
"if",
"hasattr",
"(",
"data",
",",
"'keys'",
")",
":",
"for",
"key",
"in",
"data",
":",
"value",
"=",
"data",
"[",
"key",
"]",
"# ... | Output the data in lines, very nice for running commands | [
"Output",
"the",
"data",
"in",
"lines",
"very",
"nice",
"for",
"running",
"commands"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/txt.py#L16-L37 | train |
saltstack/salt | salt/utils/configcomparer.py | compare_and_update_config | def compare_and_update_config(config, update_config, changes, namespace=''):
'''
Recursively compare two configs, writing any needed changes to the
update_config and capturing changes in the changes dict.
'''
if isinstance(config, dict):
if not update_config:
if config:
# the updated config is more valid--report that we are using it
changes[namespace] = {
'new': config,
'old': update_config,
}
return config
elif not isinstance(update_config, dict):
# new config is a dict, other isn't--new one wins
changes[namespace] = {
'new': config,
'old': update_config,
}
return config
else:
# compare each key in the base config with the values in the
# update_config, overwriting the values that are different but
# keeping any that are not defined in config
for key, value in six.iteritems(config):
_namespace = key
if namespace:
_namespace = '{0}.{1}'.format(namespace, _namespace)
update_config[key] = compare_and_update_config(
value,
update_config.get(key, None),
changes,
namespace=_namespace,
)
return update_config
elif isinstance(config, list):
if not update_config:
if config:
# the updated config is more valid--report that we are using it
changes[namespace] = {
'new': config,
'old': update_config,
}
return config
elif not isinstance(update_config, list):
# new config is a list, other isn't--new one wins
changes[namespace] = {
'new': config,
'old': update_config,
}
return config
else:
# iterate through config list, ensuring that each index in the
# update_config list is the same
for idx, item in enumerate(config):
_namespace = '[{0}]'.format(idx)
if namespace:
_namespace = '{0}{1}'.format(namespace, _namespace)
_update = None
if len(update_config) > idx:
_update = update_config[idx]
if _update:
update_config[idx] = compare_and_update_config(
config[idx],
_update,
changes,
namespace=_namespace,
)
else:
changes[_namespace] = {
'new': config[idx],
'old': _update,
}
update_config.append(config[idx])
if len(update_config) > len(config):
# trim any items in update_config that are not in config
for idx, old_item in enumerate(update_config):
if idx < len(config):
continue
_namespace = '[{0}]'.format(idx)
if namespace:
_namespace = '{0}{1}'.format(namespace, _namespace)
changes[_namespace] = {
'new': None,
'old': old_item,
}
del update_config[len(config):]
return update_config
else:
if config != update_config:
changes[namespace] = {
'new': config,
'old': update_config,
}
return config | python | def compare_and_update_config(config, update_config, changes, namespace=''):
'''
Recursively compare two configs, writing any needed changes to the
update_config and capturing changes in the changes dict.
'''
if isinstance(config, dict):
if not update_config:
if config:
# the updated config is more valid--report that we are using it
changes[namespace] = {
'new': config,
'old': update_config,
}
return config
elif not isinstance(update_config, dict):
# new config is a dict, other isn't--new one wins
changes[namespace] = {
'new': config,
'old': update_config,
}
return config
else:
# compare each key in the base config with the values in the
# update_config, overwriting the values that are different but
# keeping any that are not defined in config
for key, value in six.iteritems(config):
_namespace = key
if namespace:
_namespace = '{0}.{1}'.format(namespace, _namespace)
update_config[key] = compare_and_update_config(
value,
update_config.get(key, None),
changes,
namespace=_namespace,
)
return update_config
elif isinstance(config, list):
if not update_config:
if config:
# the updated config is more valid--report that we are using it
changes[namespace] = {
'new': config,
'old': update_config,
}
return config
elif not isinstance(update_config, list):
# new config is a list, other isn't--new one wins
changes[namespace] = {
'new': config,
'old': update_config,
}
return config
else:
# iterate through config list, ensuring that each index in the
# update_config list is the same
for idx, item in enumerate(config):
_namespace = '[{0}]'.format(idx)
if namespace:
_namespace = '{0}{1}'.format(namespace, _namespace)
_update = None
if len(update_config) > idx:
_update = update_config[idx]
if _update:
update_config[idx] = compare_and_update_config(
config[idx],
_update,
changes,
namespace=_namespace,
)
else:
changes[_namespace] = {
'new': config[idx],
'old': _update,
}
update_config.append(config[idx])
if len(update_config) > len(config):
# trim any items in update_config that are not in config
for idx, old_item in enumerate(update_config):
if idx < len(config):
continue
_namespace = '[{0}]'.format(idx)
if namespace:
_namespace = '{0}{1}'.format(namespace, _namespace)
changes[_namespace] = {
'new': None,
'old': old_item,
}
del update_config[len(config):]
return update_config
else:
if config != update_config:
changes[namespace] = {
'new': config,
'old': update_config,
}
return config | [
"def",
"compare_and_update_config",
"(",
"config",
",",
"update_config",
",",
"changes",
",",
"namespace",
"=",
"''",
")",
":",
"if",
"isinstance",
"(",
"config",
",",
"dict",
")",
":",
"if",
"not",
"update_config",
":",
"if",
"config",
":",
"# the updated c... | Recursively compare two configs, writing any needed changes to the
update_config and capturing changes in the changes dict. | [
"Recursively",
"compare",
"two",
"configs",
"writing",
"any",
"needed",
"changes",
"to",
"the",
"update_config",
"and",
"capturing",
"changes",
"in",
"the",
"changes",
"dict",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/configcomparer.py#L14-L112 | train |
saltstack/salt | salt/states/memcached.py | managed | def managed(name,
value=None,
host=DEFAULT_HOST,
port=DEFAULT_PORT,
time=DEFAULT_TIME,
min_compress_len=DEFAULT_MIN_COMPRESS_LEN):
'''
Manage a memcached key.
name
The key to manage
value
The value to set for that key
host
The memcached server IP address
port
The memcached server port
.. code-block:: yaml
foo:
memcached.managed:
- value: bar
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
try:
cur = __salt__['memcached.get'](name, host, port)
except CommandExecutionError as exc:
ret['comment'] = six.text_type(exc)
return ret
if cur == value:
ret['result'] = True
ret['comment'] = 'Key \'{0}\' does not need to be updated'.format(name)
return ret
if __opts__['test']:
ret['result'] = None
if cur is None:
ret['comment'] = 'Key \'{0}\' would be added'.format(name)
else:
ret['comment'] = 'Value of key \'{0}\' would be changed'.format(name)
return ret
try:
ret['result'] = __salt__['memcached.set'](
name, value, host, port, time, min_compress_len
)
except (CommandExecutionError, SaltInvocationError) as exc:
ret['comment'] = six.text_type(exc)
else:
if ret['result']:
ret['comment'] = 'Successfully set key \'{0}\''.format(name)
if cur is not None:
ret['changes'] = {'old': cur, 'new': value}
else:
ret['changes'] = {'key added': name, 'value': value}
else:
ret['comment'] = 'Failed to set key \'{0}\''.format(name)
return ret | python | def managed(name,
value=None,
host=DEFAULT_HOST,
port=DEFAULT_PORT,
time=DEFAULT_TIME,
min_compress_len=DEFAULT_MIN_COMPRESS_LEN):
'''
Manage a memcached key.
name
The key to manage
value
The value to set for that key
host
The memcached server IP address
port
The memcached server port
.. code-block:: yaml
foo:
memcached.managed:
- value: bar
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
try:
cur = __salt__['memcached.get'](name, host, port)
except CommandExecutionError as exc:
ret['comment'] = six.text_type(exc)
return ret
if cur == value:
ret['result'] = True
ret['comment'] = 'Key \'{0}\' does not need to be updated'.format(name)
return ret
if __opts__['test']:
ret['result'] = None
if cur is None:
ret['comment'] = 'Key \'{0}\' would be added'.format(name)
else:
ret['comment'] = 'Value of key \'{0}\' would be changed'.format(name)
return ret
try:
ret['result'] = __salt__['memcached.set'](
name, value, host, port, time, min_compress_len
)
except (CommandExecutionError, SaltInvocationError) as exc:
ret['comment'] = six.text_type(exc)
else:
if ret['result']:
ret['comment'] = 'Successfully set key \'{0}\''.format(name)
if cur is not None:
ret['changes'] = {'old': cur, 'new': value}
else:
ret['changes'] = {'key added': name, 'value': value}
else:
ret['comment'] = 'Failed to set key \'{0}\''.format(name)
return ret | [
"def",
"managed",
"(",
"name",
",",
"value",
"=",
"None",
",",
"host",
"=",
"DEFAULT_HOST",
",",
"port",
"=",
"DEFAULT_PORT",
",",
"time",
"=",
"DEFAULT_TIME",
",",
"min_compress_len",
"=",
"DEFAULT_MIN_COMPRESS_LEN",
")",
":",
"ret",
"=",
"{",
"'name'",
"... | Manage a memcached key.
name
The key to manage
value
The value to set for that key
host
The memcached server IP address
port
The memcached server port
.. code-block:: yaml
foo:
memcached.managed:
- value: bar | [
"Manage",
"a",
"memcached",
"key",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/memcached.py#L34-L101 | train |
saltstack/salt | salt/modules/dnsutil.py | parse_hosts | def parse_hosts(hostsfile='/etc/hosts', hosts=None):
'''
Parse /etc/hosts file.
CLI Example:
.. code-block:: bash
salt '*' dnsutil.parse_hosts
'''
if not hosts:
try:
with salt.utils.files.fopen(hostsfile, 'r') as fp_:
hosts = salt.utils.stringutils.to_unicode(fp_.read())
except Exception:
return 'Error: hosts data was not found'
hostsdict = {}
for line in hosts.splitlines():
if not line:
continue
if line.startswith('#'):
continue
comps = line.split()
ip = comps[0]
aliases = comps[1:]
hostsdict.setdefault(ip, []).extend(aliases)
return hostsdict | python | def parse_hosts(hostsfile='/etc/hosts', hosts=None):
'''
Parse /etc/hosts file.
CLI Example:
.. code-block:: bash
salt '*' dnsutil.parse_hosts
'''
if not hosts:
try:
with salt.utils.files.fopen(hostsfile, 'r') as fp_:
hosts = salt.utils.stringutils.to_unicode(fp_.read())
except Exception:
return 'Error: hosts data was not found'
hostsdict = {}
for line in hosts.splitlines():
if not line:
continue
if line.startswith('#'):
continue
comps = line.split()
ip = comps[0]
aliases = comps[1:]
hostsdict.setdefault(ip, []).extend(aliases)
return hostsdict | [
"def",
"parse_hosts",
"(",
"hostsfile",
"=",
"'/etc/hosts'",
",",
"hosts",
"=",
"None",
")",
":",
"if",
"not",
"hosts",
":",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"hostsfile",
",",
"'r'",
")",
"as",
"fp_",
":",
... | Parse /etc/hosts file.
CLI Example:
.. code-block:: bash
salt '*' dnsutil.parse_hosts | [
"Parse",
"/",
"etc",
"/",
"hosts",
"file",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dnsutil.py#L32-L60 | train |
saltstack/salt | salt/modules/dnsutil.py | hosts_append | def hosts_append(hostsfile='/etc/hosts', ip_addr=None, entries=None):
'''
Append a single line to the /etc/hosts file.
CLI Example:
.. code-block:: bash
salt '*' dnsutil.hosts_append /etc/hosts 127.0.0.1 ad1.yuk.co,ad2.yuk.co
'''
host_list = entries.split(',')
hosts = parse_hosts(hostsfile=hostsfile)
if ip_addr in hosts:
for host in host_list:
if host in hosts[ip_addr]:
host_list.remove(host)
if not host_list:
return 'No additional hosts were added to {0}'.format(hostsfile)
append_line = '\n{0} {1}'.format(ip_addr, ' '.join(host_list))
with salt.utils.files.fopen(hostsfile, 'a') as fp_:
fp_.write(salt.utils.stringutils.to_str(append_line))
return 'The following line was added to {0}:{1}'.format(hostsfile,
append_line) | python | def hosts_append(hostsfile='/etc/hosts', ip_addr=None, entries=None):
'''
Append a single line to the /etc/hosts file.
CLI Example:
.. code-block:: bash
salt '*' dnsutil.hosts_append /etc/hosts 127.0.0.1 ad1.yuk.co,ad2.yuk.co
'''
host_list = entries.split(',')
hosts = parse_hosts(hostsfile=hostsfile)
if ip_addr in hosts:
for host in host_list:
if host in hosts[ip_addr]:
host_list.remove(host)
if not host_list:
return 'No additional hosts were added to {0}'.format(hostsfile)
append_line = '\n{0} {1}'.format(ip_addr, ' '.join(host_list))
with salt.utils.files.fopen(hostsfile, 'a') as fp_:
fp_.write(salt.utils.stringutils.to_str(append_line))
return 'The following line was added to {0}:{1}'.format(hostsfile,
append_line) | [
"def",
"hosts_append",
"(",
"hostsfile",
"=",
"'/etc/hosts'",
",",
"ip_addr",
"=",
"None",
",",
"entries",
"=",
"None",
")",
":",
"host_list",
"=",
"entries",
".",
"split",
"(",
"','",
")",
"hosts",
"=",
"parse_hosts",
"(",
"hostsfile",
"=",
"hostsfile",
... | Append a single line to the /etc/hosts file.
CLI Example:
.. code-block:: bash
salt '*' dnsutil.hosts_append /etc/hosts 127.0.0.1 ad1.yuk.co,ad2.yuk.co | [
"Append",
"a",
"single",
"line",
"to",
"the",
"/",
"etc",
"/",
"hosts",
"file",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dnsutil.py#L63-L88 | train |
saltstack/salt | salt/modules/dnsutil.py | hosts_remove | def hosts_remove(hostsfile='/etc/hosts', entries=None):
'''
Remove a host from the /etc/hosts file. If doing so will leave a line
containing only an IP address, then the line will be deleted. This function
will leave comments and blank lines intact.
CLI Examples:
.. code-block:: bash
salt '*' dnsutil.hosts_remove /etc/hosts ad1.yuk.co
salt '*' dnsutil.hosts_remove /etc/hosts ad2.yuk.co,ad1.yuk.co
'''
with salt.utils.files.fopen(hostsfile, 'r') as fp_:
hosts = salt.utils.stringutils.to_unicode(fp_.read())
host_list = entries.split(',')
with salt.utils.files.fopen(hostsfile, 'w') as out_file:
for line in hosts.splitlines():
if not line or line.strip().startswith('#'):
out_file.write(salt.utils.stringutils.to_str('{0}\n'.format(line)))
continue
comps = line.split()
for host in host_list:
if host in comps[1:]:
comps.remove(host)
if len(comps) > 1:
out_file.write(salt.utils.stringutils.to_str(' '.join(comps)))
out_file.write(salt.utils.stringutils.to_str('\n')) | python | def hosts_remove(hostsfile='/etc/hosts', entries=None):
'''
Remove a host from the /etc/hosts file. If doing so will leave a line
containing only an IP address, then the line will be deleted. This function
will leave comments and blank lines intact.
CLI Examples:
.. code-block:: bash
salt '*' dnsutil.hosts_remove /etc/hosts ad1.yuk.co
salt '*' dnsutil.hosts_remove /etc/hosts ad2.yuk.co,ad1.yuk.co
'''
with salt.utils.files.fopen(hostsfile, 'r') as fp_:
hosts = salt.utils.stringutils.to_unicode(fp_.read())
host_list = entries.split(',')
with salt.utils.files.fopen(hostsfile, 'w') as out_file:
for line in hosts.splitlines():
if not line or line.strip().startswith('#'):
out_file.write(salt.utils.stringutils.to_str('{0}\n'.format(line)))
continue
comps = line.split()
for host in host_list:
if host in comps[1:]:
comps.remove(host)
if len(comps) > 1:
out_file.write(salt.utils.stringutils.to_str(' '.join(comps)))
out_file.write(salt.utils.stringutils.to_str('\n')) | [
"def",
"hosts_remove",
"(",
"hostsfile",
"=",
"'/etc/hosts'",
",",
"entries",
"=",
"None",
")",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"hostsfile",
",",
"'r'",
")",
"as",
"fp_",
":",
"hosts",
"=",
"salt",
".",
"utils",
".... | Remove a host from the /etc/hosts file. If doing so will leave a line
containing only an IP address, then the line will be deleted. This function
will leave comments and blank lines intact.
CLI Examples:
.. code-block:: bash
salt '*' dnsutil.hosts_remove /etc/hosts ad1.yuk.co
salt '*' dnsutil.hosts_remove /etc/hosts ad2.yuk.co,ad1.yuk.co | [
"Remove",
"a",
"host",
"from",
"the",
"/",
"etc",
"/",
"hosts",
"file",
".",
"If",
"doing",
"so",
"will",
"leave",
"a",
"line",
"containing",
"only",
"an",
"IP",
"address",
"then",
"the",
"line",
"will",
"be",
"deleted",
".",
"This",
"function",
"will"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dnsutil.py#L91-L119 | train |
saltstack/salt | salt/modules/dnsutil.py | parse_zone | def parse_zone(zonefile=None, zone=None):
'''
Parses a zone file. Can be passed raw zone data on the API level.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.parse_zone /var/lib/named/example.com.zone
'''
if zonefile:
try:
with salt.utils.files.fopen(zonefile, 'r') as fp_:
zone = salt.utils.stringutils.to_unicode(fp_.read())
except Exception:
pass
if not zone:
return 'Error: Zone data was not found'
zonedict = {}
mode = 'single'
for line in zone.splitlines():
comps = line.split(';')
line = comps[0].strip()
if not line:
continue
comps = line.split()
if line.startswith('$'):
zonedict[comps[0].replace('$', '')] = comps[1]
continue
if '(' in line and ')' not in line:
mode = 'multi'
multi = ''
if mode == 'multi':
multi += ' {0}'.format(line)
if ')' in line:
mode = 'single'
line = multi.replace('(', '').replace(')', '')
else:
continue
if 'ORIGIN' in zonedict:
comps = line.replace('@', zonedict['ORIGIN']).split()
else:
comps = line.split()
if 'SOA' in line:
if comps[1] != 'IN':
comps.pop(1)
zonedict['ORIGIN'] = comps[0]
zonedict['NETWORK'] = comps[1]
zonedict['SOURCE'] = comps[3]
zonedict['CONTACT'] = comps[4].replace('.', '@', 1)
zonedict['SERIAL'] = comps[5]
zonedict['REFRESH'] = _to_seconds(comps[6])
zonedict['RETRY'] = _to_seconds(comps[7])
zonedict['EXPIRE'] = _to_seconds(comps[8])
zonedict['MINTTL'] = _to_seconds(comps[9])
continue
if comps[0] == 'IN':
comps.insert(0, zonedict['ORIGIN'])
if not comps[0].endswith('.') and 'NS' not in line:
comps[0] = '{0}.{1}'.format(comps[0], zonedict['ORIGIN'])
if comps[2] == 'NS':
zonedict.setdefault('NS', []).append(comps[3])
elif comps[2] == 'MX':
if 'MX' not in zonedict:
zonedict.setdefault('MX', []).append({'priority': comps[3],
'host': comps[4]})
elif comps[3] in ('A', 'AAAA'):
zonedict.setdefault(comps[3], {})[comps[0]] = {
'TARGET': comps[4],
'TTL': comps[1],
}
else:
zonedict.setdefault(comps[2], {})[comps[0]] = comps[3]
return zonedict | python | def parse_zone(zonefile=None, zone=None):
'''
Parses a zone file. Can be passed raw zone data on the API level.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.parse_zone /var/lib/named/example.com.zone
'''
if zonefile:
try:
with salt.utils.files.fopen(zonefile, 'r') as fp_:
zone = salt.utils.stringutils.to_unicode(fp_.read())
except Exception:
pass
if not zone:
return 'Error: Zone data was not found'
zonedict = {}
mode = 'single'
for line in zone.splitlines():
comps = line.split(';')
line = comps[0].strip()
if not line:
continue
comps = line.split()
if line.startswith('$'):
zonedict[comps[0].replace('$', '')] = comps[1]
continue
if '(' in line and ')' not in line:
mode = 'multi'
multi = ''
if mode == 'multi':
multi += ' {0}'.format(line)
if ')' in line:
mode = 'single'
line = multi.replace('(', '').replace(')', '')
else:
continue
if 'ORIGIN' in zonedict:
comps = line.replace('@', zonedict['ORIGIN']).split()
else:
comps = line.split()
if 'SOA' in line:
if comps[1] != 'IN':
comps.pop(1)
zonedict['ORIGIN'] = comps[0]
zonedict['NETWORK'] = comps[1]
zonedict['SOURCE'] = comps[3]
zonedict['CONTACT'] = comps[4].replace('.', '@', 1)
zonedict['SERIAL'] = comps[5]
zonedict['REFRESH'] = _to_seconds(comps[6])
zonedict['RETRY'] = _to_seconds(comps[7])
zonedict['EXPIRE'] = _to_seconds(comps[8])
zonedict['MINTTL'] = _to_seconds(comps[9])
continue
if comps[0] == 'IN':
comps.insert(0, zonedict['ORIGIN'])
if not comps[0].endswith('.') and 'NS' not in line:
comps[0] = '{0}.{1}'.format(comps[0], zonedict['ORIGIN'])
if comps[2] == 'NS':
zonedict.setdefault('NS', []).append(comps[3])
elif comps[2] == 'MX':
if 'MX' not in zonedict:
zonedict.setdefault('MX', []).append({'priority': comps[3],
'host': comps[4]})
elif comps[3] in ('A', 'AAAA'):
zonedict.setdefault(comps[3], {})[comps[0]] = {
'TARGET': comps[4],
'TTL': comps[1],
}
else:
zonedict.setdefault(comps[2], {})[comps[0]] = comps[3]
return zonedict | [
"def",
"parse_zone",
"(",
"zonefile",
"=",
"None",
",",
"zone",
"=",
"None",
")",
":",
"if",
"zonefile",
":",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"zonefile",
",",
"'r'",
")",
"as",
"fp_",
":",
"zone",
"=",
"... | Parses a zone file. Can be passed raw zone data on the API level.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.parse_zone /var/lib/named/example.com.zone | [
"Parses",
"a",
"zone",
"file",
".",
"Can",
"be",
"passed",
"raw",
"zone",
"data",
"on",
"the",
"API",
"level",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dnsutil.py#L122-L197 | train |
saltstack/salt | salt/modules/dnsutil.py | _to_seconds | def _to_seconds(timestr):
'''
Converts a time value to seconds.
As per RFC1035 (page 45), max time is 1 week, so anything longer (or
unreadable) will be set to one week (604800 seconds).
'''
timestr = timestr.upper()
if 'H' in timestr:
seconds = int(timestr.replace('H', '')) * 3600
elif 'D' in timestr:
seconds = int(timestr.replace('D', '')) * 86400
elif 'W' in timestr:
seconds = 604800
else:
try:
seconds = int(timestr)
except ValueError:
seconds = 604800
if seconds > 604800:
seconds = 604800
return seconds | python | def _to_seconds(timestr):
'''
Converts a time value to seconds.
As per RFC1035 (page 45), max time is 1 week, so anything longer (or
unreadable) will be set to one week (604800 seconds).
'''
timestr = timestr.upper()
if 'H' in timestr:
seconds = int(timestr.replace('H', '')) * 3600
elif 'D' in timestr:
seconds = int(timestr.replace('D', '')) * 86400
elif 'W' in timestr:
seconds = 604800
else:
try:
seconds = int(timestr)
except ValueError:
seconds = 604800
if seconds > 604800:
seconds = 604800
return seconds | [
"def",
"_to_seconds",
"(",
"timestr",
")",
":",
"timestr",
"=",
"timestr",
".",
"upper",
"(",
")",
"if",
"'H'",
"in",
"timestr",
":",
"seconds",
"=",
"int",
"(",
"timestr",
".",
"replace",
"(",
"'H'",
",",
"''",
")",
")",
"*",
"3600",
"elif",
"'D'"... | Converts a time value to seconds.
As per RFC1035 (page 45), max time is 1 week, so anything longer (or
unreadable) will be set to one week (604800 seconds). | [
"Converts",
"a",
"time",
"value",
"to",
"seconds",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dnsutil.py#L200-L221 | train |
saltstack/salt | salt/modules/dnsutil.py | A | def A(host, nameserver=None):
'''
Return the A record(s) for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.A www.google.com
'''
if _has_dig():
return __salt__['dig.A'](host, nameserver)
elif nameserver is None:
# fall back to the socket interface, if we don't care who resolves
try:
addresses = [sock[4][0] for sock in socket.getaddrinfo(host, None, socket.AF_INET, 0, socket.SOCK_RAW)]
return addresses
except socket.gaierror:
return 'Unable to resolve {0}'.format(host)
return 'This function requires dig, which is not currently available' | python | def A(host, nameserver=None):
'''
Return the A record(s) for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.A www.google.com
'''
if _has_dig():
return __salt__['dig.A'](host, nameserver)
elif nameserver is None:
# fall back to the socket interface, if we don't care who resolves
try:
addresses = [sock[4][0] for sock in socket.getaddrinfo(host, None, socket.AF_INET, 0, socket.SOCK_RAW)]
return addresses
except socket.gaierror:
return 'Unable to resolve {0}'.format(host)
return 'This function requires dig, which is not currently available' | [
"def",
"A",
"(",
"host",
",",
"nameserver",
"=",
"None",
")",
":",
"if",
"_has_dig",
"(",
")",
":",
"return",
"__salt__",
"[",
"'dig.A'",
"]",
"(",
"host",
",",
"nameserver",
")",
"elif",
"nameserver",
"is",
"None",
":",
"# fall back to the socket interfac... | Return the A record(s) for ``host``.
Always returns a list.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.A www.google.com | [
"Return",
"the",
"A",
"record",
"(",
"s",
")",
"for",
"host",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dnsutil.py#L249-L271 | train |
saltstack/salt | salt/modules/dnsutil.py | AAAA | def AAAA(host, nameserver=None):
'''
Return the AAAA record(s) for ``host``.
Always returns a list.
.. versionadded:: 2014.7.5
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.AAAA www.google.com
'''
if _has_dig():
return __salt__['dig.AAAA'](host, nameserver)
elif nameserver is None:
# fall back to the socket interface, if we don't care who resolves
try:
addresses = [sock[4][0] for sock in socket.getaddrinfo(host, None, socket.AF_INET6, 0, socket.SOCK_RAW)]
return addresses
except socket.gaierror:
return 'Unable to resolve {0}'.format(host)
return 'This function requires dig, which is not currently available' | python | def AAAA(host, nameserver=None):
'''
Return the AAAA record(s) for ``host``.
Always returns a list.
.. versionadded:: 2014.7.5
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.AAAA www.google.com
'''
if _has_dig():
return __salt__['dig.AAAA'](host, nameserver)
elif nameserver is None:
# fall back to the socket interface, if we don't care who resolves
try:
addresses = [sock[4][0] for sock in socket.getaddrinfo(host, None, socket.AF_INET6, 0, socket.SOCK_RAW)]
return addresses
except socket.gaierror:
return 'Unable to resolve {0}'.format(host)
return 'This function requires dig, which is not currently available' | [
"def",
"AAAA",
"(",
"host",
",",
"nameserver",
"=",
"None",
")",
":",
"if",
"_has_dig",
"(",
")",
":",
"return",
"__salt__",
"[",
"'dig.AAAA'",
"]",
"(",
"host",
",",
"nameserver",
")",
"elif",
"nameserver",
"is",
"None",
":",
"# fall back to the socket in... | Return the AAAA record(s) for ``host``.
Always returns a list.
.. versionadded:: 2014.7.5
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.AAAA www.google.com | [
"Return",
"the",
"AAAA",
"record",
"(",
"s",
")",
"for",
"host",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dnsutil.py#L274-L298 | train |
saltstack/salt | salt/modules/dnsutil.py | NS | def NS(domain, resolve=True, nameserver=None):
'''
Return a list of IPs of the nameservers for ``domain``
If 'resolve' is False, don't resolve names.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.NS google.com
'''
if _has_dig():
return __salt__['dig.NS'](domain, resolve, nameserver)
return 'This function requires dig, which is not currently available' | python | def NS(domain, resolve=True, nameserver=None):
'''
Return a list of IPs of the nameservers for ``domain``
If 'resolve' is False, don't resolve names.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.NS google.com
'''
if _has_dig():
return __salt__['dig.NS'](domain, resolve, nameserver)
return 'This function requires dig, which is not currently available' | [
"def",
"NS",
"(",
"domain",
",",
"resolve",
"=",
"True",
",",
"nameserver",
"=",
"None",
")",
":",
"if",
"_has_dig",
"(",
")",
":",
"return",
"__salt__",
"[",
"'dig.NS'",
"]",
"(",
"domain",
",",
"resolve",
",",
"nameserver",
")",
"return",
"'This func... | Return a list of IPs of the nameservers for ``domain``
If 'resolve' is False, don't resolve names.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.NS google.com | [
"Return",
"a",
"list",
"of",
"IPs",
"of",
"the",
"nameservers",
"for",
"domain"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dnsutil.py#L301-L317 | train |
saltstack/salt | salt/modules/dnsutil.py | MX | def MX(domain, resolve=False, nameserver=None):
'''
Return a list of lists for the MX of ``domain``.
If the 'resolve' argument is True, resolve IPs for the servers.
It's limited to one IP, because although in practice it's very rarely a
round robin, it is an acceptable configuration and pulling just one IP lets
the data be similar to the non-resolved version. If you think an MX has
multiple IPs, don't use the resolver here, resolve them in a separate step.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.MX google.com
'''
if _has_dig():
return __salt__['dig.MX'](domain, resolve, nameserver)
return 'This function requires dig, which is not currently available' | python | def MX(domain, resolve=False, nameserver=None):
'''
Return a list of lists for the MX of ``domain``.
If the 'resolve' argument is True, resolve IPs for the servers.
It's limited to one IP, because although in practice it's very rarely a
round robin, it is an acceptable configuration and pulling just one IP lets
the data be similar to the non-resolved version. If you think an MX has
multiple IPs, don't use the resolver here, resolve them in a separate step.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.MX google.com
'''
if _has_dig():
return __salt__['dig.MX'](domain, resolve, nameserver)
return 'This function requires dig, which is not currently available' | [
"def",
"MX",
"(",
"domain",
",",
"resolve",
"=",
"False",
",",
"nameserver",
"=",
"None",
")",
":",
"if",
"_has_dig",
"(",
")",
":",
"return",
"__salt__",
"[",
"'dig.MX'",
"]",
"(",
"domain",
",",
"resolve",
",",
"nameserver",
")",
"return",
"'This fun... | Return a list of lists for the MX of ``domain``.
If the 'resolve' argument is True, resolve IPs for the servers.
It's limited to one IP, because although in practice it's very rarely a
round robin, it is an acceptable configuration and pulling just one IP lets
the data be similar to the non-resolved version. If you think an MX has
multiple IPs, don't use the resolver here, resolve them in a separate step.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.MX google.com | [
"Return",
"a",
"list",
"of",
"lists",
"for",
"the",
"MX",
"of",
"domain",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dnsutil.py#L340-L360 | train |
saltstack/salt | salt/modules/dnsutil.py | serial | def serial(zone='', update=False):
'''
Return, store and update a dns serial for your zone files.
zone: a keyword for a specific zone
update: store an updated version of the serial in a grain
If ``update`` is False, the function will retrieve an existing serial or
return the current date if no serial is stored. Nothing will be stored
If ``update`` is True, the function will set the serial to the current date
if none exist or if the existing serial is for a previous date. If a serial
for greater than the current date is already stored, the function will
increment it.
This module stores the serial in a grain, you can explicitly set the
stored value as a grain named ``dnsserial_<zone_name>``.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.serial example.com
'''
grains = {}
key = 'dnsserial'
if zone:
key += '_{0}'.format(zone)
stored = __salt__['grains.get'](key=key)
present = time.strftime('%Y%m%d01')
if not update:
return stored or present
if stored and stored >= present:
current = six.text_type(int(stored) + 1)
else:
current = present
__salt__['grains.setval'](key=key, val=current)
return current | python | def serial(zone='', update=False):
'''
Return, store and update a dns serial for your zone files.
zone: a keyword for a specific zone
update: store an updated version of the serial in a grain
If ``update`` is False, the function will retrieve an existing serial or
return the current date if no serial is stored. Nothing will be stored
If ``update`` is True, the function will set the serial to the current date
if none exist or if the existing serial is for a previous date. If a serial
for greater than the current date is already stored, the function will
increment it.
This module stores the serial in a grain, you can explicitly set the
stored value as a grain named ``dnsserial_<zone_name>``.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.serial example.com
'''
grains = {}
key = 'dnsserial'
if zone:
key += '_{0}'.format(zone)
stored = __salt__['grains.get'](key=key)
present = time.strftime('%Y%m%d01')
if not update:
return stored or present
if stored and stored >= present:
current = six.text_type(int(stored) + 1)
else:
current = present
__salt__['grains.setval'](key=key, val=current)
return current | [
"def",
"serial",
"(",
"zone",
"=",
"''",
",",
"update",
"=",
"False",
")",
":",
"grains",
"=",
"{",
"}",
"key",
"=",
"'dnsserial'",
"if",
"zone",
":",
"key",
"+=",
"'_{0}'",
".",
"format",
"(",
"zone",
")",
"stored",
"=",
"__salt__",
"[",
"'grains.... | Return, store and update a dns serial for your zone files.
zone: a keyword for a specific zone
update: store an updated version of the serial in a grain
If ``update`` is False, the function will retrieve an existing serial or
return the current date if no serial is stored. Nothing will be stored
If ``update`` is True, the function will set the serial to the current date
if none exist or if the existing serial is for a previous date. If a serial
for greater than the current date is already stored, the function will
increment it.
This module stores the serial in a grain, you can explicitly set the
stored value as a grain named ``dnsserial_<zone_name>``.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.serial example.com | [
"Return",
"store",
"and",
"update",
"a",
"dns",
"serial",
"for",
"your",
"zone",
"files",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dnsutil.py#L363-L401 | train |
saltstack/salt | salt/master.py | Maintenance._post_fork_init | def _post_fork_init(self):
'''
Some things need to be init'd after the fork has completed
The easiest example is that one of these module types creates a thread
in the parent process, then once the fork happens you'll start getting
errors like "WARNING: Mixing fork() and threads detected; memory leaked."
'''
# Load Runners
ropts = dict(self.opts)
ropts['quiet'] = True
runner_client = salt.runner.RunnerClient(ropts)
# Load Returners
self.returners = salt.loader.returners(self.opts, {})
# Init Scheduler
self.schedule = salt.utils.schedule.Schedule(self.opts,
runner_client.functions_dict(),
returners=self.returners)
self.ckminions = salt.utils.minions.CkMinions(self.opts)
# Make Event bus for firing
self.event = salt.utils.event.get_master_event(self.opts, self.opts['sock_dir'], listen=False)
# Init any values needed by the git ext pillar
self.git_pillar = salt.daemons.masterapi.init_git_pillar(self.opts)
self.presence_events = False
if self.opts.get('presence_events', False):
tcp_only = True
for transport, _ in iter_transport_opts(self.opts):
if transport != 'tcp':
tcp_only = False
if not tcp_only:
# For a TCP only transport, the presence events will be
# handled in the transport code.
self.presence_events = True | python | def _post_fork_init(self):
'''
Some things need to be init'd after the fork has completed
The easiest example is that one of these module types creates a thread
in the parent process, then once the fork happens you'll start getting
errors like "WARNING: Mixing fork() and threads detected; memory leaked."
'''
# Load Runners
ropts = dict(self.opts)
ropts['quiet'] = True
runner_client = salt.runner.RunnerClient(ropts)
# Load Returners
self.returners = salt.loader.returners(self.opts, {})
# Init Scheduler
self.schedule = salt.utils.schedule.Schedule(self.opts,
runner_client.functions_dict(),
returners=self.returners)
self.ckminions = salt.utils.minions.CkMinions(self.opts)
# Make Event bus for firing
self.event = salt.utils.event.get_master_event(self.opts, self.opts['sock_dir'], listen=False)
# Init any values needed by the git ext pillar
self.git_pillar = salt.daemons.masterapi.init_git_pillar(self.opts)
self.presence_events = False
if self.opts.get('presence_events', False):
tcp_only = True
for transport, _ in iter_transport_opts(self.opts):
if transport != 'tcp':
tcp_only = False
if not tcp_only:
# For a TCP only transport, the presence events will be
# handled in the transport code.
self.presence_events = True | [
"def",
"_post_fork_init",
"(",
"self",
")",
":",
"# Load Runners",
"ropts",
"=",
"dict",
"(",
"self",
".",
"opts",
")",
"ropts",
"[",
"'quiet'",
"]",
"=",
"True",
"runner_client",
"=",
"salt",
".",
"runner",
".",
"RunnerClient",
"(",
"ropts",
")",
"# Loa... | Some things need to be init'd after the fork has completed
The easiest example is that one of these module types creates a thread
in the parent process, then once the fork happens you'll start getting
errors like "WARNING: Mixing fork() and threads detected; memory leaked." | [
"Some",
"things",
"need",
"to",
"be",
"init",
"d",
"after",
"the",
"fork",
"has",
"completed",
"The",
"easiest",
"example",
"is",
"that",
"one",
"of",
"these",
"module",
"types",
"creates",
"a",
"thread",
"in",
"the",
"parent",
"process",
"then",
"once",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L179-L212 | train |
saltstack/salt | salt/master.py | Maintenance.run | def run(self):
'''
This is the general passive maintenance process controller for the Salt
master.
This is where any data that needs to be cleanly maintained from the
master is maintained.
'''
salt.utils.process.appendproctitle(self.__class__.__name__)
# init things that need to be done after the process is forked
self._post_fork_init()
# Make Start Times
last = int(time.time())
old_present = set()
while True:
now = int(time.time())
if (now - last) >= self.loop_interval:
salt.daemons.masterapi.clean_old_jobs(self.opts)
salt.daemons.masterapi.clean_expired_tokens(self.opts)
salt.daemons.masterapi.clean_pub_auth(self.opts)
salt.daemons.masterapi.clean_proc_dir(self.opts)
self.handle_git_pillar()
self.handle_schedule()
self.handle_key_cache()
self.handle_presence(old_present)
self.handle_key_rotate(now)
salt.utils.verify.check_max_open_files(self.opts)
last = now
time.sleep(self.loop_interval) | python | def run(self):
'''
This is the general passive maintenance process controller for the Salt
master.
This is where any data that needs to be cleanly maintained from the
master is maintained.
'''
salt.utils.process.appendproctitle(self.__class__.__name__)
# init things that need to be done after the process is forked
self._post_fork_init()
# Make Start Times
last = int(time.time())
old_present = set()
while True:
now = int(time.time())
if (now - last) >= self.loop_interval:
salt.daemons.masterapi.clean_old_jobs(self.opts)
salt.daemons.masterapi.clean_expired_tokens(self.opts)
salt.daemons.masterapi.clean_pub_auth(self.opts)
salt.daemons.masterapi.clean_proc_dir(self.opts)
self.handle_git_pillar()
self.handle_schedule()
self.handle_key_cache()
self.handle_presence(old_present)
self.handle_key_rotate(now)
salt.utils.verify.check_max_open_files(self.opts)
last = now
time.sleep(self.loop_interval) | [
"def",
"run",
"(",
"self",
")",
":",
"salt",
".",
"utils",
".",
"process",
".",
"appendproctitle",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
"# init things that need to be done after the process is forked",
"self",
".",
"_post_fork_init",
"(",
")",
"# M... | This is the general passive maintenance process controller for the Salt
master.
This is where any data that needs to be cleanly maintained from the
master is maintained. | [
"This",
"is",
"the",
"general",
"passive",
"maintenance",
"process",
"controller",
"for",
"the",
"Salt",
"master",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L214-L245 | train |
saltstack/salt | salt/master.py | Maintenance.handle_key_cache | def handle_key_cache(self):
'''
Evaluate accepted keys and create a msgpack file
which contains a list
'''
if self.opts['key_cache'] == 'sched':
keys = []
#TODO DRY from CKMinions
if self.opts['transport'] in ('zeromq', 'tcp'):
acc = 'minions'
else:
acc = 'accepted'
for fn_ in os.listdir(os.path.join(self.opts['pki_dir'], acc)):
if not fn_.startswith('.') and os.path.isfile(os.path.join(self.opts['pki_dir'], acc, fn_)):
keys.append(fn_)
log.debug('Writing master key cache')
# Write a temporary file securely
if six.PY2:
with salt.utils.atomicfile.atomic_open(os.path.join(self.opts['pki_dir'], acc, '.key_cache')) as cache_file:
self.serial.dump(keys, cache_file)
else:
with salt.utils.atomicfile.atomic_open(os.path.join(self.opts['pki_dir'], acc, '.key_cache'), mode='wb') as cache_file:
self.serial.dump(keys, cache_file) | python | def handle_key_cache(self):
'''
Evaluate accepted keys and create a msgpack file
which contains a list
'''
if self.opts['key_cache'] == 'sched':
keys = []
#TODO DRY from CKMinions
if self.opts['transport'] in ('zeromq', 'tcp'):
acc = 'minions'
else:
acc = 'accepted'
for fn_ in os.listdir(os.path.join(self.opts['pki_dir'], acc)):
if not fn_.startswith('.') and os.path.isfile(os.path.join(self.opts['pki_dir'], acc, fn_)):
keys.append(fn_)
log.debug('Writing master key cache')
# Write a temporary file securely
if six.PY2:
with salt.utils.atomicfile.atomic_open(os.path.join(self.opts['pki_dir'], acc, '.key_cache')) as cache_file:
self.serial.dump(keys, cache_file)
else:
with salt.utils.atomicfile.atomic_open(os.path.join(self.opts['pki_dir'], acc, '.key_cache'), mode='wb') as cache_file:
self.serial.dump(keys, cache_file) | [
"def",
"handle_key_cache",
"(",
"self",
")",
":",
"if",
"self",
".",
"opts",
"[",
"'key_cache'",
"]",
"==",
"'sched'",
":",
"keys",
"=",
"[",
"]",
"#TODO DRY from CKMinions",
"if",
"self",
".",
"opts",
"[",
"'transport'",
"]",
"in",
"(",
"'zeromq'",
",",... | Evaluate accepted keys and create a msgpack file
which contains a list | [
"Evaluate",
"accepted",
"keys",
"and",
"create",
"a",
"msgpack",
"file",
"which",
"contains",
"a",
"list"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L247-L270 | train |
saltstack/salt | salt/master.py | Maintenance.handle_key_rotate | def handle_key_rotate(self, now):
'''
Rotate the AES key rotation
'''
to_rotate = False
dfn = os.path.join(self.opts['cachedir'], '.dfn')
try:
stats = os.stat(dfn)
# Basic Windows permissions don't distinguish between
# user/group/all. Check for read-only state instead.
if salt.utils.platform.is_windows() and not os.access(dfn, os.W_OK):
to_rotate = True
# Cannot delete read-only files on Windows.
os.chmod(dfn, stat.S_IRUSR | stat.S_IWUSR)
elif stats.st_mode == 0o100400:
to_rotate = True
else:
log.error('Found dropfile with incorrect permissions, ignoring...')
os.remove(dfn)
except os.error:
pass
if self.opts.get('publish_session'):
if now - self.rotate >= self.opts['publish_session']:
to_rotate = True
if to_rotate:
log.info('Rotating master AES key')
for secret_key, secret_map in six.iteritems(SMaster.secrets):
# should be unnecessary-- since no one else should be modifying
with secret_map['secret'].get_lock():
secret_map['secret'].value = salt.utils.stringutils.to_bytes(secret_map['reload']())
self.event.fire_event({'rotate_{0}_key'.format(secret_key): True}, tag='key')
self.rotate = now
if self.opts.get('ping_on_rotate'):
# Ping all minions to get them to pick up the new key
log.debug('Pinging all connected minions '
'due to key rotation')
salt.utils.master.ping_all_connected_minions(self.opts) | python | def handle_key_rotate(self, now):
'''
Rotate the AES key rotation
'''
to_rotate = False
dfn = os.path.join(self.opts['cachedir'], '.dfn')
try:
stats = os.stat(dfn)
# Basic Windows permissions don't distinguish between
# user/group/all. Check for read-only state instead.
if salt.utils.platform.is_windows() and not os.access(dfn, os.W_OK):
to_rotate = True
# Cannot delete read-only files on Windows.
os.chmod(dfn, stat.S_IRUSR | stat.S_IWUSR)
elif stats.st_mode == 0o100400:
to_rotate = True
else:
log.error('Found dropfile with incorrect permissions, ignoring...')
os.remove(dfn)
except os.error:
pass
if self.opts.get('publish_session'):
if now - self.rotate >= self.opts['publish_session']:
to_rotate = True
if to_rotate:
log.info('Rotating master AES key')
for secret_key, secret_map in six.iteritems(SMaster.secrets):
# should be unnecessary-- since no one else should be modifying
with secret_map['secret'].get_lock():
secret_map['secret'].value = salt.utils.stringutils.to_bytes(secret_map['reload']())
self.event.fire_event({'rotate_{0}_key'.format(secret_key): True}, tag='key')
self.rotate = now
if self.opts.get('ping_on_rotate'):
# Ping all minions to get them to pick up the new key
log.debug('Pinging all connected minions '
'due to key rotation')
salt.utils.master.ping_all_connected_minions(self.opts) | [
"def",
"handle_key_rotate",
"(",
"self",
",",
"now",
")",
":",
"to_rotate",
"=",
"False",
"dfn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"opts",
"[",
"'cachedir'",
"]",
",",
"'.dfn'",
")",
"try",
":",
"stats",
"=",
"os",
".",
"stat",... | Rotate the AES key rotation | [
"Rotate",
"the",
"AES",
"key",
"rotation"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L272-L310 | train |
saltstack/salt | salt/master.py | Maintenance.handle_git_pillar | def handle_git_pillar(self):
'''
Update git pillar
'''
try:
for pillar in self.git_pillar:
pillar.fetch_remotes()
except Exception as exc:
log.error('Exception caught while updating git_pillar',
exc_info=True) | python | def handle_git_pillar(self):
'''
Update git pillar
'''
try:
for pillar in self.git_pillar:
pillar.fetch_remotes()
except Exception as exc:
log.error('Exception caught while updating git_pillar',
exc_info=True) | [
"def",
"handle_git_pillar",
"(",
"self",
")",
":",
"try",
":",
"for",
"pillar",
"in",
"self",
".",
"git_pillar",
":",
"pillar",
".",
"fetch_remotes",
"(",
")",
"except",
"Exception",
"as",
"exc",
":",
"log",
".",
"error",
"(",
"'Exception caught while updati... | Update git pillar | [
"Update",
"git",
"pillar"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L312-L321 | train |
saltstack/salt | salt/master.py | Maintenance.handle_schedule | def handle_schedule(self):
'''
Evaluate the scheduler
'''
try:
self.schedule.eval()
# Check if scheduler requires lower loop interval than
# the loop_interval setting
if self.schedule.loop_interval < self.loop_interval:
self.loop_interval = self.schedule.loop_interval
except Exception as exc:
log.error('Exception %s occurred in scheduled job', exc) | python | def handle_schedule(self):
'''
Evaluate the scheduler
'''
try:
self.schedule.eval()
# Check if scheduler requires lower loop interval than
# the loop_interval setting
if self.schedule.loop_interval < self.loop_interval:
self.loop_interval = self.schedule.loop_interval
except Exception as exc:
log.error('Exception %s occurred in scheduled job', exc) | [
"def",
"handle_schedule",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"schedule",
".",
"eval",
"(",
")",
"# Check if scheduler requires lower loop interval than",
"# the loop_interval setting",
"if",
"self",
".",
"schedule",
".",
"loop_interval",
"<",
"self",
".... | Evaluate the scheduler | [
"Evaluate",
"the",
"scheduler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L323-L334 | train |
saltstack/salt | salt/master.py | Maintenance.handle_presence | def handle_presence(self, old_present):
'''
Fire presence events if enabled
'''
# On the first run it may need more time for the EventPublisher
# to come up and be ready. Set the timeout to account for this.
if self.presence_events and self.event.connect_pull(timeout=3):
present = self.ckminions.connected_ids()
new = present.difference(old_present)
lost = old_present.difference(present)
if new or lost:
# Fire new minions present event
data = {'new': list(new),
'lost': list(lost)}
self.event.fire_event(data, tagify('change', 'presence'))
data = {'present': list(present)}
self.event.fire_event(data, tagify('present', 'presence'))
old_present.clear()
old_present.update(present) | python | def handle_presence(self, old_present):
'''
Fire presence events if enabled
'''
# On the first run it may need more time for the EventPublisher
# to come up and be ready. Set the timeout to account for this.
if self.presence_events and self.event.connect_pull(timeout=3):
present = self.ckminions.connected_ids()
new = present.difference(old_present)
lost = old_present.difference(present)
if new or lost:
# Fire new minions present event
data = {'new': list(new),
'lost': list(lost)}
self.event.fire_event(data, tagify('change', 'presence'))
data = {'present': list(present)}
self.event.fire_event(data, tagify('present', 'presence'))
old_present.clear()
old_present.update(present) | [
"def",
"handle_presence",
"(",
"self",
",",
"old_present",
")",
":",
"# On the first run it may need more time for the EventPublisher",
"# to come up and be ready. Set the timeout to account for this.",
"if",
"self",
".",
"presence_events",
"and",
"self",
".",
"event",
".",
"co... | Fire presence events if enabled | [
"Fire",
"presence",
"events",
"if",
"enabled"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L336-L354 | train |
saltstack/salt | salt/master.py | FileserverUpdate.fill_buckets | def fill_buckets(self):
'''
Get the configured backends and the intervals for any backend which
supports them, and set up the update "buckets". There will be one
bucket for each thing being updated at a given interval.
'''
update_intervals = self.fileserver.update_intervals()
self.buckets = {}
for backend in self.fileserver.backends():
fstr = '{0}.update'.format(backend)
try:
update_func = self.fileserver.servers[fstr]
except KeyError:
log.debug(
'No update function for the %s filserver backend',
backend
)
continue
if backend in update_intervals:
# Variable intervals are supported for this backend
for id_, interval in six.iteritems(update_intervals[backend]):
if not interval:
# Don't allow an interval of 0
interval = DEFAULT_INTERVAL
log.debug(
'An update_interval of 0 is not supported, '
'falling back to %s', interval
)
i_ptr = self.buckets.setdefault(interval, OrderedDict())
# Backend doesn't technically need to be present in the
# key, all we *really* need is the function reference, but
# having it there makes it easier to provide meaningful
# debug logging in the update threads.
i_ptr.setdefault((backend, update_func), []).append(id_)
else:
# Variable intervals are not supported for this backend, so
# fall back to the global interval for that fileserver. Since
# this backend doesn't support variable updates, we have
# nothing to pass to the backend's update func, so we'll just
# set the value to None.
try:
interval_key = '{0}_update_interval'.format(backend)
interval = self.opts[interval_key]
except KeyError:
interval = DEFAULT_INTERVAL
log.warning(
'%s key missing from configuration. Falling back to '
'default interval of %d seconds',
interval_key, interval
)
self.buckets.setdefault(
interval, OrderedDict())[(backend, update_func)] = None | python | def fill_buckets(self):
'''
Get the configured backends and the intervals for any backend which
supports them, and set up the update "buckets". There will be one
bucket for each thing being updated at a given interval.
'''
update_intervals = self.fileserver.update_intervals()
self.buckets = {}
for backend in self.fileserver.backends():
fstr = '{0}.update'.format(backend)
try:
update_func = self.fileserver.servers[fstr]
except KeyError:
log.debug(
'No update function for the %s filserver backend',
backend
)
continue
if backend in update_intervals:
# Variable intervals are supported for this backend
for id_, interval in six.iteritems(update_intervals[backend]):
if not interval:
# Don't allow an interval of 0
interval = DEFAULT_INTERVAL
log.debug(
'An update_interval of 0 is not supported, '
'falling back to %s', interval
)
i_ptr = self.buckets.setdefault(interval, OrderedDict())
# Backend doesn't technically need to be present in the
# key, all we *really* need is the function reference, but
# having it there makes it easier to provide meaningful
# debug logging in the update threads.
i_ptr.setdefault((backend, update_func), []).append(id_)
else:
# Variable intervals are not supported for this backend, so
# fall back to the global interval for that fileserver. Since
# this backend doesn't support variable updates, we have
# nothing to pass to the backend's update func, so we'll just
# set the value to None.
try:
interval_key = '{0}_update_interval'.format(backend)
interval = self.opts[interval_key]
except KeyError:
interval = DEFAULT_INTERVAL
log.warning(
'%s key missing from configuration. Falling back to '
'default interval of %d seconds',
interval_key, interval
)
self.buckets.setdefault(
interval, OrderedDict())[(backend, update_func)] = None | [
"def",
"fill_buckets",
"(",
"self",
")",
":",
"update_intervals",
"=",
"self",
".",
"fileserver",
".",
"update_intervals",
"(",
")",
"self",
".",
"buckets",
"=",
"{",
"}",
"for",
"backend",
"in",
"self",
".",
"fileserver",
".",
"backends",
"(",
")",
":",... | Get the configured backends and the intervals for any backend which
supports them, and set up the update "buckets". There will be one
bucket for each thing being updated at a given interval. | [
"Get",
"the",
"configured",
"backends",
"and",
"the",
"intervals",
"for",
"any",
"backend",
"which",
"supports",
"them",
"and",
"set",
"up",
"the",
"update",
"buckets",
".",
"There",
"will",
"be",
"one",
"bucket",
"for",
"each",
"thing",
"being",
"updated",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L385-L436 | train |
saltstack/salt | salt/master.py | FileserverUpdate.update_fileserver | def update_fileserver(self, interval, backends):
'''
Threading target which handles all updates for a given wait interval
'''
def _do_update():
log.debug(
'Performing fileserver updates for items with an update '
'interval of %d', interval
)
for backend, update_args in six.iteritems(backends):
backend_name, update_func = backend
try:
if update_args:
log.debug(
'Updating %s fileserver cache for the following '
'targets: %s', backend_name, update_args
)
args = (update_args,)
else:
log.debug('Updating %s fileserver cache', backend_name)
args = ()
update_func(*args)
except Exception as exc:
log.exception(
'Uncaught exception while updating %s fileserver '
'cache', backend_name
)
log.debug(
'Completed fileserver updates for items with an update '
'interval of %d, waiting %d seconds', interval, interval
)
condition = threading.Condition()
_do_update()
while True:
with condition:
condition.wait(interval)
_do_update() | python | def update_fileserver(self, interval, backends):
'''
Threading target which handles all updates for a given wait interval
'''
def _do_update():
log.debug(
'Performing fileserver updates for items with an update '
'interval of %d', interval
)
for backend, update_args in six.iteritems(backends):
backend_name, update_func = backend
try:
if update_args:
log.debug(
'Updating %s fileserver cache for the following '
'targets: %s', backend_name, update_args
)
args = (update_args,)
else:
log.debug('Updating %s fileserver cache', backend_name)
args = ()
update_func(*args)
except Exception as exc:
log.exception(
'Uncaught exception while updating %s fileserver '
'cache', backend_name
)
log.debug(
'Completed fileserver updates for items with an update '
'interval of %d, waiting %d seconds', interval, interval
)
condition = threading.Condition()
_do_update()
while True:
with condition:
condition.wait(interval)
_do_update() | [
"def",
"update_fileserver",
"(",
"self",
",",
"interval",
",",
"backends",
")",
":",
"def",
"_do_update",
"(",
")",
":",
"log",
".",
"debug",
"(",
"'Performing fileserver updates for items with an update '",
"'interval of %d'",
",",
"interval",
")",
"for",
"backend"... | Threading target which handles all updates for a given wait interval | [
"Threading",
"target",
"which",
"handles",
"all",
"updates",
"for",
"a",
"given",
"wait",
"interval"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L438-L477 | train |
saltstack/salt | salt/master.py | FileserverUpdate.run | def run(self):
'''
Start the update threads
'''
salt.utils.process.appendproctitle(self.__class__.__name__)
# Clean out the fileserver backend cache
salt.daemons.masterapi.clean_fsbackend(self.opts)
for interval in self.buckets:
self.update_threads[interval] = threading.Thread(
target=self.update_fileserver,
args=(interval, self.buckets[interval]),
)
self.update_threads[interval].start()
# Keep the process alive
while True:
time.sleep(60) | python | def run(self):
'''
Start the update threads
'''
salt.utils.process.appendproctitle(self.__class__.__name__)
# Clean out the fileserver backend cache
salt.daemons.masterapi.clean_fsbackend(self.opts)
for interval in self.buckets:
self.update_threads[interval] = threading.Thread(
target=self.update_fileserver,
args=(interval, self.buckets[interval]),
)
self.update_threads[interval].start()
# Keep the process alive
while True:
time.sleep(60) | [
"def",
"run",
"(",
"self",
")",
":",
"salt",
".",
"utils",
".",
"process",
".",
"appendproctitle",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
"# Clean out the fileserver backend cache",
"salt",
".",
"daemons",
".",
"masterapi",
".",
"clean_fsbackend",
... | Start the update threads | [
"Start",
"the",
"update",
"threads"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L479-L496 | train |
saltstack/salt | salt/master.py | Master._pre_flight | def _pre_flight(self):
'''
Run pre flight checks. If anything in this method fails then the master
should not start up.
'''
errors = []
critical_errors = []
try:
os.chdir('/')
except OSError as err:
errors.append(
'Cannot change to root directory ({0})'.format(err)
)
if self.opts.get('fileserver_verify_config', True):
# Avoid circular import
import salt.fileserver
fileserver = salt.fileserver.Fileserver(self.opts)
if not fileserver.servers:
errors.append(
'Failed to load fileserver backends, the configured backends '
'are: {0}'.format(', '.join(self.opts['fileserver_backend']))
)
else:
# Run init() for all backends which support the function, to
# double-check configuration
try:
fileserver.init()
except salt.exceptions.FileserverConfigError as exc:
critical_errors.append('{0}'.format(exc))
if not self.opts['fileserver_backend']:
errors.append('No fileserver backends are configured')
# Check to see if we need to create a pillar cache dir
if self.opts['pillar_cache'] and not os.path.isdir(os.path.join(self.opts['cachedir'], 'pillar_cache')):
try:
with salt.utils.files.set_umask(0o077):
os.mkdir(os.path.join(self.opts['cachedir'], 'pillar_cache'))
except OSError:
pass
if self.opts.get('git_pillar_verify_config', True):
try:
git_pillars = [
x for x in self.opts.get('ext_pillar', [])
if 'git' in x
and not isinstance(x['git'], six.string_types)
]
except TypeError:
git_pillars = []
critical_errors.append(
'Invalid ext_pillar configuration. It is likely that the '
'external pillar type was not specified for one or more '
'external pillars.'
)
if git_pillars:
try:
new_opts = copy.deepcopy(self.opts)
import salt.pillar.git_pillar
for repo in git_pillars:
new_opts['ext_pillar'] = [repo]
try:
git_pillar = salt.utils.gitfs.GitPillar(
new_opts,
repo['git'],
per_remote_overrides=salt.pillar.git_pillar.PER_REMOTE_OVERRIDES,
per_remote_only=salt.pillar.git_pillar.PER_REMOTE_ONLY,
global_only=salt.pillar.git_pillar.GLOBAL_ONLY)
except salt.exceptions.FileserverConfigError as exc:
critical_errors.append(exc.strerror)
finally:
del new_opts
if errors or critical_errors:
for error in errors:
log.error(error)
for error in critical_errors:
log.critical(error)
log.critical('Master failed pre flight checks, exiting\n')
sys.exit(salt.defaults.exitcodes.EX_GENERIC) | python | def _pre_flight(self):
'''
Run pre flight checks. If anything in this method fails then the master
should not start up.
'''
errors = []
critical_errors = []
try:
os.chdir('/')
except OSError as err:
errors.append(
'Cannot change to root directory ({0})'.format(err)
)
if self.opts.get('fileserver_verify_config', True):
# Avoid circular import
import salt.fileserver
fileserver = salt.fileserver.Fileserver(self.opts)
if not fileserver.servers:
errors.append(
'Failed to load fileserver backends, the configured backends '
'are: {0}'.format(', '.join(self.opts['fileserver_backend']))
)
else:
# Run init() for all backends which support the function, to
# double-check configuration
try:
fileserver.init()
except salt.exceptions.FileserverConfigError as exc:
critical_errors.append('{0}'.format(exc))
if not self.opts['fileserver_backend']:
errors.append('No fileserver backends are configured')
# Check to see if we need to create a pillar cache dir
if self.opts['pillar_cache'] and not os.path.isdir(os.path.join(self.opts['cachedir'], 'pillar_cache')):
try:
with salt.utils.files.set_umask(0o077):
os.mkdir(os.path.join(self.opts['cachedir'], 'pillar_cache'))
except OSError:
pass
if self.opts.get('git_pillar_verify_config', True):
try:
git_pillars = [
x for x in self.opts.get('ext_pillar', [])
if 'git' in x
and not isinstance(x['git'], six.string_types)
]
except TypeError:
git_pillars = []
critical_errors.append(
'Invalid ext_pillar configuration. It is likely that the '
'external pillar type was not specified for one or more '
'external pillars.'
)
if git_pillars:
try:
new_opts = copy.deepcopy(self.opts)
import salt.pillar.git_pillar
for repo in git_pillars:
new_opts['ext_pillar'] = [repo]
try:
git_pillar = salt.utils.gitfs.GitPillar(
new_opts,
repo['git'],
per_remote_overrides=salt.pillar.git_pillar.PER_REMOTE_OVERRIDES,
per_remote_only=salt.pillar.git_pillar.PER_REMOTE_ONLY,
global_only=salt.pillar.git_pillar.GLOBAL_ONLY)
except salt.exceptions.FileserverConfigError as exc:
critical_errors.append(exc.strerror)
finally:
del new_opts
if errors or critical_errors:
for error in errors:
log.error(error)
for error in critical_errors:
log.critical(error)
log.critical('Master failed pre flight checks, exiting\n')
sys.exit(salt.defaults.exitcodes.EX_GENERIC) | [
"def",
"_pre_flight",
"(",
"self",
")",
":",
"errors",
"=",
"[",
"]",
"critical_errors",
"=",
"[",
"]",
"try",
":",
"os",
".",
"chdir",
"(",
"'/'",
")",
"except",
"OSError",
"as",
"err",
":",
"errors",
".",
"append",
"(",
"'Cannot change to root director... | Run pre flight checks. If anything in this method fails then the master
should not start up. | [
"Run",
"pre",
"flight",
"checks",
".",
"If",
"anything",
"in",
"this",
"method",
"fails",
"then",
"the",
"master",
"should",
"not",
"start",
"up",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L563-L644 | train |
saltstack/salt | salt/master.py | Master.start | def start(self):
'''
Turn on the master server components
'''
self._pre_flight()
log.info('salt-master is starting as user \'%s\'', salt.utils.user.get_user())
enable_sigusr1_handler()
enable_sigusr2_handler()
self.__set_max_open_files()
# Reset signals to default ones before adding processes to the process
# manager. We don't want the processes being started to inherit those
# signal handlers
with salt.utils.process.default_signals(signal.SIGINT, signal.SIGTERM):
# Setup the secrets here because the PubServerChannel may need
# them as well.
SMaster.secrets['aes'] = {
'secret': multiprocessing.Array(
ctypes.c_char,
salt.utils.stringutils.to_bytes(
salt.crypt.Crypticle.generate_key_string()
)
),
'reload': salt.crypt.Crypticle.generate_key_string
}
log.info('Creating master process manager')
# Since there are children having their own ProcessManager we should wait for kill more time.
self.process_manager = salt.utils.process.ProcessManager(wait_for_kill=5)
pub_channels = []
log.info('Creating master publisher process')
log_queue = salt.log.setup.get_multiprocessing_logging_queue()
for _, opts in iter_transport_opts(self.opts):
chan = salt.transport.server.PubServerChannel.factory(opts)
chan.pre_fork(self.process_manager, kwargs={'log_queue': log_queue})
pub_channels.append(chan)
log.info('Creating master event publisher process')
self.process_manager.add_process(salt.utils.event.EventPublisher, args=(self.opts,))
if self.opts.get('reactor'):
if isinstance(self.opts['engines'], list):
rine = False
for item in self.opts['engines']:
if 'reactor' in item:
rine = True
break
if not rine:
self.opts['engines'].append({'reactor': {}})
else:
if 'reactor' not in self.opts['engines']:
log.info('Enabling the reactor engine')
self.opts['engines']['reactor'] = {}
salt.engines.start_engines(self.opts, self.process_manager)
# must be after channels
log.info('Creating master maintenance process')
self.process_manager.add_process(Maintenance, args=(self.opts,))
if self.opts.get('event_return'):
log.info('Creating master event return process')
self.process_manager.add_process(salt.utils.event.EventReturn, args=(self.opts,))
ext_procs = self.opts.get('ext_processes', [])
for proc in ext_procs:
log.info('Creating ext_processes process: %s', proc)
try:
mod = '.'.join(proc.split('.')[:-1])
cls = proc.split('.')[-1]
_tmp = __import__(mod, globals(), locals(), [cls], -1)
cls = _tmp.__getattribute__(cls)
self.process_manager.add_process(cls, args=(self.opts,))
except Exception:
log.error('Error creating ext_processes process: %s', proc)
if HAS_HALITE and 'halite' in self.opts:
log.info('Creating master halite process')
self.process_manager.add_process(Halite, args=(self.opts['halite'],))
# TODO: remove, or at least push into the transport stuff (pre-fork probably makes sense there)
if self.opts['con_cache']:
log.info('Creating master concache process')
self.process_manager.add_process(salt.utils.master.ConnectedCache, args=(self.opts,))
# workaround for issue #16315, race condition
log.debug('Sleeping for two seconds to let concache rest')
time.sleep(2)
log.info('Creating master request server process')
kwargs = {}
if salt.utils.platform.is_windows():
kwargs['log_queue'] = log_queue
kwargs['log_queue_level'] = salt.log.setup.get_multiprocessing_logging_level()
kwargs['secrets'] = SMaster.secrets
self.process_manager.add_process(
ReqServer,
args=(self.opts, self.key, self.master_key),
kwargs=kwargs,
name='ReqServer')
self.process_manager.add_process(
FileserverUpdate,
args=(self.opts,))
# Fire up SSDP discovery publisher
if self.opts['discovery']:
if salt.utils.ssdp.SSDPDiscoveryServer.is_available():
self.process_manager.add_process(salt.utils.ssdp.SSDPDiscoveryServer(
port=self.opts['discovery']['port'],
listen_ip=self.opts['interface'],
answer={'mapping': self.opts['discovery'].get('mapping', {})}).run)
else:
log.error('Unable to load SSDP: asynchronous IO is not available.')
if sys.version_info.major == 2:
log.error('You are using Python 2, please install "trollius" module to enable SSDP discovery.')
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, self._handle_signals)
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGTERM, self._handle_signals)
self.process_manager.run() | python | def start(self):
'''
Turn on the master server components
'''
self._pre_flight()
log.info('salt-master is starting as user \'%s\'', salt.utils.user.get_user())
enable_sigusr1_handler()
enable_sigusr2_handler()
self.__set_max_open_files()
# Reset signals to default ones before adding processes to the process
# manager. We don't want the processes being started to inherit those
# signal handlers
with salt.utils.process.default_signals(signal.SIGINT, signal.SIGTERM):
# Setup the secrets here because the PubServerChannel may need
# them as well.
SMaster.secrets['aes'] = {
'secret': multiprocessing.Array(
ctypes.c_char,
salt.utils.stringutils.to_bytes(
salt.crypt.Crypticle.generate_key_string()
)
),
'reload': salt.crypt.Crypticle.generate_key_string
}
log.info('Creating master process manager')
# Since there are children having their own ProcessManager we should wait for kill more time.
self.process_manager = salt.utils.process.ProcessManager(wait_for_kill=5)
pub_channels = []
log.info('Creating master publisher process')
log_queue = salt.log.setup.get_multiprocessing_logging_queue()
for _, opts in iter_transport_opts(self.opts):
chan = salt.transport.server.PubServerChannel.factory(opts)
chan.pre_fork(self.process_manager, kwargs={'log_queue': log_queue})
pub_channels.append(chan)
log.info('Creating master event publisher process')
self.process_manager.add_process(salt.utils.event.EventPublisher, args=(self.opts,))
if self.opts.get('reactor'):
if isinstance(self.opts['engines'], list):
rine = False
for item in self.opts['engines']:
if 'reactor' in item:
rine = True
break
if not rine:
self.opts['engines'].append({'reactor': {}})
else:
if 'reactor' not in self.opts['engines']:
log.info('Enabling the reactor engine')
self.opts['engines']['reactor'] = {}
salt.engines.start_engines(self.opts, self.process_manager)
# must be after channels
log.info('Creating master maintenance process')
self.process_manager.add_process(Maintenance, args=(self.opts,))
if self.opts.get('event_return'):
log.info('Creating master event return process')
self.process_manager.add_process(salt.utils.event.EventReturn, args=(self.opts,))
ext_procs = self.opts.get('ext_processes', [])
for proc in ext_procs:
log.info('Creating ext_processes process: %s', proc)
try:
mod = '.'.join(proc.split('.')[:-1])
cls = proc.split('.')[-1]
_tmp = __import__(mod, globals(), locals(), [cls], -1)
cls = _tmp.__getattribute__(cls)
self.process_manager.add_process(cls, args=(self.opts,))
except Exception:
log.error('Error creating ext_processes process: %s', proc)
if HAS_HALITE and 'halite' in self.opts:
log.info('Creating master halite process')
self.process_manager.add_process(Halite, args=(self.opts['halite'],))
# TODO: remove, or at least push into the transport stuff (pre-fork probably makes sense there)
if self.opts['con_cache']:
log.info('Creating master concache process')
self.process_manager.add_process(salt.utils.master.ConnectedCache, args=(self.opts,))
# workaround for issue #16315, race condition
log.debug('Sleeping for two seconds to let concache rest')
time.sleep(2)
log.info('Creating master request server process')
kwargs = {}
if salt.utils.platform.is_windows():
kwargs['log_queue'] = log_queue
kwargs['log_queue_level'] = salt.log.setup.get_multiprocessing_logging_level()
kwargs['secrets'] = SMaster.secrets
self.process_manager.add_process(
ReqServer,
args=(self.opts, self.key, self.master_key),
kwargs=kwargs,
name='ReqServer')
self.process_manager.add_process(
FileserverUpdate,
args=(self.opts,))
# Fire up SSDP discovery publisher
if self.opts['discovery']:
if salt.utils.ssdp.SSDPDiscoveryServer.is_available():
self.process_manager.add_process(salt.utils.ssdp.SSDPDiscoveryServer(
port=self.opts['discovery']['port'],
listen_ip=self.opts['interface'],
answer={'mapping': self.opts['discovery'].get('mapping', {})}).run)
else:
log.error('Unable to load SSDP: asynchronous IO is not available.')
if sys.version_info.major == 2:
log.error('You are using Python 2, please install "trollius" module to enable SSDP discovery.')
# Install the SIGINT/SIGTERM handlers if not done so far
if signal.getsignal(signal.SIGINT) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGINT, self._handle_signals)
if signal.getsignal(signal.SIGTERM) is signal.SIG_DFL:
# No custom signal handling was added, install our own
signal.signal(signal.SIGTERM, self._handle_signals)
self.process_manager.run() | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_pre_flight",
"(",
")",
"log",
".",
"info",
"(",
"'salt-master is starting as user \\'%s\\''",
",",
"salt",
".",
"utils",
".",
"user",
".",
"get_user",
"(",
")",
")",
"enable_sigusr1_handler",
"(",
")",
... | Turn on the master server components | [
"Turn",
"on",
"the",
"master",
"server",
"components"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L646-L774 | train |
saltstack/salt | salt/master.py | Halite.run | def run(self):
'''
Fire up halite!
'''
salt.utils.process.appendproctitle(self.__class__.__name__)
halite.start(self.hopts) | python | def run(self):
'''
Fire up halite!
'''
salt.utils.process.appendproctitle(self.__class__.__name__)
halite.start(self.hopts) | [
"def",
"run",
"(",
"self",
")",
":",
"salt",
".",
"utils",
".",
"process",
".",
"appendproctitle",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
"halite",
".",
"start",
"(",
"self",
".",
"hopts",
")"
] | Fire up halite! | [
"Fire",
"up",
"halite!"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L817-L822 | train |
saltstack/salt | salt/master.py | ReqServer.__bind | def __bind(self):
'''
Binds the reply server
'''
if self.log_queue is not None:
salt.log.setup.set_multiprocessing_logging_queue(self.log_queue)
if self.log_queue_level is not None:
salt.log.setup.set_multiprocessing_logging_level(self.log_queue_level)
salt.log.setup.setup_multiprocessing_logging(self.log_queue)
if self.secrets is not None:
SMaster.secrets = self.secrets
dfn = os.path.join(self.opts['cachedir'], '.dfn')
if os.path.isfile(dfn):
try:
if salt.utils.platform.is_windows() and not os.access(dfn, os.W_OK):
# Cannot delete read-only files on Windows.
os.chmod(dfn, stat.S_IRUSR | stat.S_IWUSR)
os.remove(dfn)
except os.error:
pass
# Wait for kill should be less then parent's ProcessManager.
self.process_manager = salt.utils.process.ProcessManager(name='ReqServer_ProcessManager',
wait_for_kill=1)
req_channels = []
tcp_only = True
for transport, opts in iter_transport_opts(self.opts):
chan = salt.transport.server.ReqServerChannel.factory(opts)
chan.pre_fork(self.process_manager)
req_channels.append(chan)
if transport != 'tcp':
tcp_only = False
kwargs = {}
if salt.utils.platform.is_windows():
kwargs['log_queue'] = self.log_queue
kwargs['log_queue_level'] = self.log_queue_level
# Use one worker thread if only the TCP transport is set up on
# Windows and we are using Python 2. There is load balancer
# support on Windows for the TCP transport when using Python 3.
if tcp_only and six.PY2 and int(self.opts['worker_threads']) != 1:
log.warning('TCP transport supports only 1 worker on Windows '
'when using Python 2.')
self.opts['worker_threads'] = 1
# Reset signals to default ones before adding processes to the process
# manager. We don't want the processes being started to inherit those
# signal handlers
with salt.utils.process.default_signals(signal.SIGINT, signal.SIGTERM):
for ind in range(int(self.opts['worker_threads'])):
name = 'MWorker-{0}'.format(ind)
self.process_manager.add_process(MWorker,
args=(self.opts,
self.master_key,
self.key,
req_channels,
name),
kwargs=kwargs,
name=name)
self.process_manager.run() | python | def __bind(self):
'''
Binds the reply server
'''
if self.log_queue is not None:
salt.log.setup.set_multiprocessing_logging_queue(self.log_queue)
if self.log_queue_level is not None:
salt.log.setup.set_multiprocessing_logging_level(self.log_queue_level)
salt.log.setup.setup_multiprocessing_logging(self.log_queue)
if self.secrets is not None:
SMaster.secrets = self.secrets
dfn = os.path.join(self.opts['cachedir'], '.dfn')
if os.path.isfile(dfn):
try:
if salt.utils.platform.is_windows() and not os.access(dfn, os.W_OK):
# Cannot delete read-only files on Windows.
os.chmod(dfn, stat.S_IRUSR | stat.S_IWUSR)
os.remove(dfn)
except os.error:
pass
# Wait for kill should be less then parent's ProcessManager.
self.process_manager = salt.utils.process.ProcessManager(name='ReqServer_ProcessManager',
wait_for_kill=1)
req_channels = []
tcp_only = True
for transport, opts in iter_transport_opts(self.opts):
chan = salt.transport.server.ReqServerChannel.factory(opts)
chan.pre_fork(self.process_manager)
req_channels.append(chan)
if transport != 'tcp':
tcp_only = False
kwargs = {}
if salt.utils.platform.is_windows():
kwargs['log_queue'] = self.log_queue
kwargs['log_queue_level'] = self.log_queue_level
# Use one worker thread if only the TCP transport is set up on
# Windows and we are using Python 2. There is load balancer
# support on Windows for the TCP transport when using Python 3.
if tcp_only and six.PY2 and int(self.opts['worker_threads']) != 1:
log.warning('TCP transport supports only 1 worker on Windows '
'when using Python 2.')
self.opts['worker_threads'] = 1
# Reset signals to default ones before adding processes to the process
# manager. We don't want the processes being started to inherit those
# signal handlers
with salt.utils.process.default_signals(signal.SIGINT, signal.SIGTERM):
for ind in range(int(self.opts['worker_threads'])):
name = 'MWorker-{0}'.format(ind)
self.process_manager.add_process(MWorker,
args=(self.opts,
self.master_key,
self.key,
req_channels,
name),
kwargs=kwargs,
name=name)
self.process_manager.run() | [
"def",
"__bind",
"(",
"self",
")",
":",
"if",
"self",
".",
"log_queue",
"is",
"not",
"None",
":",
"salt",
".",
"log",
".",
"setup",
".",
"set_multiprocessing_logging_queue",
"(",
"self",
".",
"log_queue",
")",
"if",
"self",
".",
"log_queue_level",
"is",
... | Binds the reply server | [
"Binds",
"the",
"reply",
"server"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L876-L937 | train |
saltstack/salt | salt/master.py | MWorker.__bind | def __bind(self):
'''
Bind to the local port
'''
# using ZMQIOLoop since we *might* need zmq in there
install_zmq()
self.io_loop = ZMQDefaultLoop()
self.io_loop.make_current()
for req_channel in self.req_channels:
req_channel.post_fork(self._handle_payload, io_loop=self.io_loop) # TODO: cleaner? Maybe lazily?
try:
self.io_loop.start()
except (KeyboardInterrupt, SystemExit):
# Tornado knows what to do
pass | python | def __bind(self):
'''
Bind to the local port
'''
# using ZMQIOLoop since we *might* need zmq in there
install_zmq()
self.io_loop = ZMQDefaultLoop()
self.io_loop.make_current()
for req_channel in self.req_channels:
req_channel.post_fork(self._handle_payload, io_loop=self.io_loop) # TODO: cleaner? Maybe lazily?
try:
self.io_loop.start()
except (KeyboardInterrupt, SystemExit):
# Tornado knows what to do
pass | [
"def",
"__bind",
"(",
"self",
")",
":",
"# using ZMQIOLoop since we *might* need zmq in there",
"install_zmq",
"(",
")",
"self",
".",
"io_loop",
"=",
"ZMQDefaultLoop",
"(",
")",
"self",
".",
"io_loop",
".",
"make_current",
"(",
")",
"for",
"req_channel",
"in",
"... | Bind to the local port | [
"Bind",
"to",
"the",
"local",
"port"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1024-L1038 | train |
saltstack/salt | salt/master.py | MWorker._handle_payload | def _handle_payload(self, payload):
'''
The _handle_payload method is the key method used to figure out what
needs to be done with communication to the server
Example cleartext payload generated for 'salt myminion test.ping':
{'enc': 'clear',
'load': {'arg': [],
'cmd': 'publish',
'fun': 'test.ping',
'jid': '',
'key': 'alsdkjfa.,maljf-==adflkjadflkjalkjadfadflkajdflkj',
'kwargs': {'show_jid': False, 'show_timeout': False},
'ret': '',
'tgt': 'myminion',
'tgt_type': 'glob',
'user': 'root'}}
:param dict payload: The payload route to the appropriate handler
'''
key = payload['enc']
load = payload['load']
ret = {'aes': self._handle_aes,
'clear': self._handle_clear}[key](load)
raise tornado.gen.Return(ret) | python | def _handle_payload(self, payload):
'''
The _handle_payload method is the key method used to figure out what
needs to be done with communication to the server
Example cleartext payload generated for 'salt myminion test.ping':
{'enc': 'clear',
'load': {'arg': [],
'cmd': 'publish',
'fun': 'test.ping',
'jid': '',
'key': 'alsdkjfa.,maljf-==adflkjadflkjalkjadfadflkajdflkj',
'kwargs': {'show_jid': False, 'show_timeout': False},
'ret': '',
'tgt': 'myminion',
'tgt_type': 'glob',
'user': 'root'}}
:param dict payload: The payload route to the appropriate handler
'''
key = payload['enc']
load = payload['load']
ret = {'aes': self._handle_aes,
'clear': self._handle_clear}[key](load)
raise tornado.gen.Return(ret) | [
"def",
"_handle_payload",
"(",
"self",
",",
"payload",
")",
":",
"key",
"=",
"payload",
"[",
"'enc'",
"]",
"load",
"=",
"payload",
"[",
"'load'",
"]",
"ret",
"=",
"{",
"'aes'",
":",
"self",
".",
"_handle_aes",
",",
"'clear'",
":",
"self",
".",
"_hand... | The _handle_payload method is the key method used to figure out what
needs to be done with communication to the server
Example cleartext payload generated for 'salt myminion test.ping':
{'enc': 'clear',
'load': {'arg': [],
'cmd': 'publish',
'fun': 'test.ping',
'jid': '',
'key': 'alsdkjfa.,maljf-==adflkjadflkjalkjadfadflkajdflkj',
'kwargs': {'show_jid': False, 'show_timeout': False},
'ret': '',
'tgt': 'myminion',
'tgt_type': 'glob',
'user': 'root'}}
:param dict payload: The payload route to the appropriate handler | [
"The",
"_handle_payload",
"method",
"is",
"the",
"key",
"method",
"used",
"to",
"figure",
"out",
"what",
"needs",
"to",
"be",
"done",
"with",
"communication",
"to",
"the",
"server"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1041-L1066 | train |
saltstack/salt | salt/master.py | MWorker._post_stats | def _post_stats(self, stats):
'''
Fire events with stat info if it's time
'''
end_time = time.time()
if end_time - self.stat_clock > self.opts['master_stats_event_iter']:
# Fire the event with the stats and wipe the tracker
self.aes_funcs.event.fire_event({'time': end_time - self.stat_clock, 'worker': self.name, 'stats': stats}, tagify(self.name, 'stats'))
self.stats = collections.defaultdict(lambda: {'mean': 0, 'latency': 0, 'runs': 0})
self.stat_clock = end_time | python | def _post_stats(self, stats):
'''
Fire events with stat info if it's time
'''
end_time = time.time()
if end_time - self.stat_clock > self.opts['master_stats_event_iter']:
# Fire the event with the stats and wipe the tracker
self.aes_funcs.event.fire_event({'time': end_time - self.stat_clock, 'worker': self.name, 'stats': stats}, tagify(self.name, 'stats'))
self.stats = collections.defaultdict(lambda: {'mean': 0, 'latency': 0, 'runs': 0})
self.stat_clock = end_time | [
"def",
"_post_stats",
"(",
"self",
",",
"stats",
")",
":",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"if",
"end_time",
"-",
"self",
".",
"stat_clock",
">",
"self",
".",
"opts",
"[",
"'master_stats_event_iter'",
"]",
":",
"# Fire the event with the stat... | Fire events with stat info if it's time | [
"Fire",
"events",
"with",
"stat",
"info",
"if",
"it",
"s",
"time"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1068-L1077 | train |
saltstack/salt | salt/master.py | MWorker._handle_clear | def _handle_clear(self, load):
'''
Process a cleartext command
:param dict load: Cleartext payload
:return: The result of passing the load to a function in ClearFuncs corresponding to
the command specified in the load's 'cmd' key.
'''
log.trace('Clear payload received with command %s', load['cmd'])
cmd = load['cmd']
if cmd.startswith('__'):
return False
if self.opts['master_stats']:
start = time.time()
ret = getattr(self.clear_funcs, cmd)(load), {'fun': 'send_clear'}
if self.opts['master_stats']:
stats = salt.utils.event.update_stats(self.stats, start, load)
self._post_stats(stats)
return ret | python | def _handle_clear(self, load):
'''
Process a cleartext command
:param dict load: Cleartext payload
:return: The result of passing the load to a function in ClearFuncs corresponding to
the command specified in the load's 'cmd' key.
'''
log.trace('Clear payload received with command %s', load['cmd'])
cmd = load['cmd']
if cmd.startswith('__'):
return False
if self.opts['master_stats']:
start = time.time()
ret = getattr(self.clear_funcs, cmd)(load), {'fun': 'send_clear'}
if self.opts['master_stats']:
stats = salt.utils.event.update_stats(self.stats, start, load)
self._post_stats(stats)
return ret | [
"def",
"_handle_clear",
"(",
"self",
",",
"load",
")",
":",
"log",
".",
"trace",
"(",
"'Clear payload received with command %s'",
",",
"load",
"[",
"'cmd'",
"]",
")",
"cmd",
"=",
"load",
"[",
"'cmd'",
"]",
"if",
"cmd",
".",
"startswith",
"(",
"'__'",
")"... | Process a cleartext command
:param dict load: Cleartext payload
:return: The result of passing the load to a function in ClearFuncs corresponding to
the command specified in the load's 'cmd' key. | [
"Process",
"a",
"cleartext",
"command"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1079-L1097 | train |
saltstack/salt | salt/master.py | MWorker._handle_aes | def _handle_aes(self, data):
'''
Process a command sent via an AES key
:param str load: Encrypted payload
:return: The result of passing the load to a function in AESFuncs corresponding to
the command specified in the load's 'cmd' key.
'''
if 'cmd' not in data:
log.error('Received malformed command %s', data)
return {}
cmd = data['cmd']
log.trace('AES payload received with command %s', data['cmd'])
if cmd.startswith('__'):
return False
if self.opts['master_stats']:
start = time.time()
def run_func(data):
return self.aes_funcs.run_func(data['cmd'], data)
with StackContext(functools.partial(RequestContext,
{'data': data,
'opts': self.opts})):
ret = run_func(data)
if self.opts['master_stats']:
stats = salt.utils.event.update_stats(self.stats, start, data)
self._post_stats(stats)
return ret | python | def _handle_aes(self, data):
'''
Process a command sent via an AES key
:param str load: Encrypted payload
:return: The result of passing the load to a function in AESFuncs corresponding to
the command specified in the load's 'cmd' key.
'''
if 'cmd' not in data:
log.error('Received malformed command %s', data)
return {}
cmd = data['cmd']
log.trace('AES payload received with command %s', data['cmd'])
if cmd.startswith('__'):
return False
if self.opts['master_stats']:
start = time.time()
def run_func(data):
return self.aes_funcs.run_func(data['cmd'], data)
with StackContext(functools.partial(RequestContext,
{'data': data,
'opts': self.opts})):
ret = run_func(data)
if self.opts['master_stats']:
stats = salt.utils.event.update_stats(self.stats, start, data)
self._post_stats(stats)
return ret | [
"def",
"_handle_aes",
"(",
"self",
",",
"data",
")",
":",
"if",
"'cmd'",
"not",
"in",
"data",
":",
"log",
".",
"error",
"(",
"'Received malformed command %s'",
",",
"data",
")",
"return",
"{",
"}",
"cmd",
"=",
"data",
"[",
"'cmd'",
"]",
"log",
".",
"... | Process a command sent via an AES key
:param str load: Encrypted payload
:return: The result of passing the load to a function in AESFuncs corresponding to
the command specified in the load's 'cmd' key. | [
"Process",
"a",
"command",
"sent",
"via",
"an",
"AES",
"key"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1099-L1128 | train |
saltstack/salt | salt/master.py | MWorker.run | def run(self):
'''
Start a Master Worker
'''
salt.utils.process.appendproctitle(self.name)
self.clear_funcs = ClearFuncs(
self.opts,
self.key,
)
self.aes_funcs = AESFuncs(self.opts)
salt.utils.crypt.reinit_crypto()
self.__bind() | python | def run(self):
'''
Start a Master Worker
'''
salt.utils.process.appendproctitle(self.name)
self.clear_funcs = ClearFuncs(
self.opts,
self.key,
)
self.aes_funcs = AESFuncs(self.opts)
salt.utils.crypt.reinit_crypto()
self.__bind() | [
"def",
"run",
"(",
"self",
")",
":",
"salt",
".",
"utils",
".",
"process",
".",
"appendproctitle",
"(",
"self",
".",
"name",
")",
"self",
".",
"clear_funcs",
"=",
"ClearFuncs",
"(",
"self",
".",
"opts",
",",
"self",
".",
"key",
",",
")",
"self",
".... | Start a Master Worker | [
"Start",
"a",
"Master",
"Worker"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1130-L1141 | train |
saltstack/salt | salt/master.py | AESFuncs.__setup_fileserver | def __setup_fileserver(self):
'''
Set the local file objects from the file server interface
'''
# Avoid circular import
import salt.fileserver
self.fs_ = salt.fileserver.Fileserver(self.opts)
self._serve_file = self.fs_.serve_file
self._file_find = self.fs_._find_file
self._file_hash = self.fs_.file_hash
self._file_hash_and_stat = self.fs_.file_hash_and_stat
self._file_list = self.fs_.file_list
self._file_list_emptydirs = self.fs_.file_list_emptydirs
self._dir_list = self.fs_.dir_list
self._symlink_list = self.fs_.symlink_list
self._file_envs = self.fs_.file_envs | python | def __setup_fileserver(self):
'''
Set the local file objects from the file server interface
'''
# Avoid circular import
import salt.fileserver
self.fs_ = salt.fileserver.Fileserver(self.opts)
self._serve_file = self.fs_.serve_file
self._file_find = self.fs_._find_file
self._file_hash = self.fs_.file_hash
self._file_hash_and_stat = self.fs_.file_hash_and_stat
self._file_list = self.fs_.file_list
self._file_list_emptydirs = self.fs_.file_list_emptydirs
self._dir_list = self.fs_.dir_list
self._symlink_list = self.fs_.symlink_list
self._file_envs = self.fs_.file_envs | [
"def",
"__setup_fileserver",
"(",
"self",
")",
":",
"# Avoid circular import",
"import",
"salt",
".",
"fileserver",
"self",
".",
"fs_",
"=",
"salt",
".",
"fileserver",
".",
"Fileserver",
"(",
"self",
".",
"opts",
")",
"self",
".",
"_serve_file",
"=",
"self",... | Set the local file objects from the file server interface | [
"Set",
"the",
"local",
"file",
"objects",
"from",
"the",
"file",
"server",
"interface"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1176-L1191 | train |
saltstack/salt | salt/master.py | AESFuncs.__verify_minion | def __verify_minion(self, id_, token):
'''
Take a minion id and a string signed with the minion private key
The string needs to verify as 'salt' with the minion public key
:param str id_: A minion ID
:param str token: A string signed with the minion private key
:rtype: bool
:return: Boolean indicating whether or not the token can be verified.
'''
if not salt.utils.verify.valid_id(self.opts, id_):
return False
pub_path = os.path.join(self.opts['pki_dir'], 'minions', id_)
try:
pub = salt.crypt.get_rsa_pub_key(pub_path)
except (IOError, OSError):
log.warning(
'Salt minion claiming to be %s attempted to communicate with '
'master, but key could not be read and verification was denied.',
id_
)
return False
except (ValueError, IndexError, TypeError) as err:
log.error('Unable to load public key "%s": %s', pub_path, err)
try:
if salt.crypt.public_decrypt(pub, token) == b'salt':
return True
except ValueError as err:
log.error('Unable to decrypt token: %s', err)
log.error(
'Salt minion claiming to be %s has attempted to communicate with '
'the master and could not be verified', id_
)
return False | python | def __verify_minion(self, id_, token):
'''
Take a minion id and a string signed with the minion private key
The string needs to verify as 'salt' with the minion public key
:param str id_: A minion ID
:param str token: A string signed with the minion private key
:rtype: bool
:return: Boolean indicating whether or not the token can be verified.
'''
if not salt.utils.verify.valid_id(self.opts, id_):
return False
pub_path = os.path.join(self.opts['pki_dir'], 'minions', id_)
try:
pub = salt.crypt.get_rsa_pub_key(pub_path)
except (IOError, OSError):
log.warning(
'Salt minion claiming to be %s attempted to communicate with '
'master, but key could not be read and verification was denied.',
id_
)
return False
except (ValueError, IndexError, TypeError) as err:
log.error('Unable to load public key "%s": %s', pub_path, err)
try:
if salt.crypt.public_decrypt(pub, token) == b'salt':
return True
except ValueError as err:
log.error('Unable to decrypt token: %s', err)
log.error(
'Salt minion claiming to be %s has attempted to communicate with '
'the master and could not be verified', id_
)
return False | [
"def",
"__verify_minion",
"(",
"self",
",",
"id_",
",",
"token",
")",
":",
"if",
"not",
"salt",
".",
"utils",
".",
"verify",
".",
"valid_id",
"(",
"self",
".",
"opts",
",",
"id_",
")",
":",
"return",
"False",
"pub_path",
"=",
"os",
".",
"path",
"."... | Take a minion id and a string signed with the minion private key
The string needs to verify as 'salt' with the minion public key
:param str id_: A minion ID
:param str token: A string signed with the minion private key
:rtype: bool
:return: Boolean indicating whether or not the token can be verified. | [
"Take",
"a",
"minion",
"id",
"and",
"a",
"string",
"signed",
"with",
"the",
"minion",
"private",
"key",
"The",
"string",
"needs",
"to",
"verify",
"as",
"salt",
"with",
"the",
"minion",
"public",
"key"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1193-L1229 | train |
saltstack/salt | salt/master.py | AESFuncs.__verify_minion_publish | def __verify_minion_publish(self, clear_load):
'''
Verify that the passed information authorized a minion to execute
:param dict clear_load: A publication load from a minion
:rtype: bool
:return: A boolean indicating if the minion is allowed to publish the command in the load
'''
# Verify that the load is valid
if 'peer' not in self.opts:
return False
if not isinstance(self.opts['peer'], dict):
return False
if any(key not in clear_load for key in ('fun', 'arg', 'tgt', 'ret', 'tok', 'id')):
return False
# If the command will make a recursive publish don't run
if clear_load['fun'].startswith('publish.'):
return False
# Check the permissions for this minion
if not self.__verify_minion(clear_load['id'], clear_load['tok']):
# The minion is not who it says it is!
# We don't want to listen to it!
log.warning(
'Minion id %s is not who it says it is and is attempting '
'to issue a peer command', clear_load['id']
)
return False
clear_load.pop('tok')
perms = []
for match in self.opts['peer']:
if re.match(match, clear_load['id']):
# This is the list of funcs/modules!
if isinstance(self.opts['peer'][match], list):
perms.extend(self.opts['peer'][match])
if ',' in clear_load['fun']:
# 'arg': [['cat', '/proc/cpuinfo'], [], ['foo']]
clear_load['fun'] = clear_load['fun'].split(',')
arg_ = []
for arg in clear_load['arg']:
arg_.append(arg.split())
clear_load['arg'] = arg_
# finally, check the auth of the load
return self.ckminions.auth_check(
perms,
clear_load['fun'],
clear_load['arg'],
clear_load['tgt'],
clear_load.get('tgt_type', 'glob'),
publish_validate=True) | python | def __verify_minion_publish(self, clear_load):
'''
Verify that the passed information authorized a minion to execute
:param dict clear_load: A publication load from a minion
:rtype: bool
:return: A boolean indicating if the minion is allowed to publish the command in the load
'''
# Verify that the load is valid
if 'peer' not in self.opts:
return False
if not isinstance(self.opts['peer'], dict):
return False
if any(key not in clear_load for key in ('fun', 'arg', 'tgt', 'ret', 'tok', 'id')):
return False
# If the command will make a recursive publish don't run
if clear_load['fun'].startswith('publish.'):
return False
# Check the permissions for this minion
if not self.__verify_minion(clear_load['id'], clear_load['tok']):
# The minion is not who it says it is!
# We don't want to listen to it!
log.warning(
'Minion id %s is not who it says it is and is attempting '
'to issue a peer command', clear_load['id']
)
return False
clear_load.pop('tok')
perms = []
for match in self.opts['peer']:
if re.match(match, clear_load['id']):
# This is the list of funcs/modules!
if isinstance(self.opts['peer'][match], list):
perms.extend(self.opts['peer'][match])
if ',' in clear_load['fun']:
# 'arg': [['cat', '/proc/cpuinfo'], [], ['foo']]
clear_load['fun'] = clear_load['fun'].split(',')
arg_ = []
for arg in clear_load['arg']:
arg_.append(arg.split())
clear_load['arg'] = arg_
# finally, check the auth of the load
return self.ckminions.auth_check(
perms,
clear_load['fun'],
clear_load['arg'],
clear_load['tgt'],
clear_load.get('tgt_type', 'glob'),
publish_validate=True) | [
"def",
"__verify_minion_publish",
"(",
"self",
",",
"clear_load",
")",
":",
"# Verify that the load is valid",
"if",
"'peer'",
"not",
"in",
"self",
".",
"opts",
":",
"return",
"False",
"if",
"not",
"isinstance",
"(",
"self",
".",
"opts",
"[",
"'peer'",
"]",
... | Verify that the passed information authorized a minion to execute
:param dict clear_load: A publication load from a minion
:rtype: bool
:return: A boolean indicating if the minion is allowed to publish the command in the load | [
"Verify",
"that",
"the",
"passed",
"information",
"authorized",
"a",
"minion",
"to",
"execute"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1244-L1294 | train |
saltstack/salt | salt/master.py | AESFuncs.__verify_load | def __verify_load(self, load, verify_keys):
'''
A utility function to perform common verification steps.
:param dict load: A payload received from a minion
:param list verify_keys: A list of strings that should be present in a
given load
:rtype: bool
:rtype: dict
:return: The original load (except for the token) if the load can be
verified. False if the load is invalid.
'''
if any(key not in load for key in verify_keys):
return False
if 'tok' not in load:
log.error(
'Received incomplete call from %s for \'%s\', missing \'%s\'',
load['id'], inspect_stack()['co_name'], 'tok'
)
return False
if not self.__verify_minion(load['id'], load['tok']):
# The minion is not who it says it is!
# We don't want to listen to it!
log.warning('Minion id %s is not who it says it is!', load['id'])
return False
if 'tok' in load:
load.pop('tok')
return load | python | def __verify_load(self, load, verify_keys):
'''
A utility function to perform common verification steps.
:param dict load: A payload received from a minion
:param list verify_keys: A list of strings that should be present in a
given load
:rtype: bool
:rtype: dict
:return: The original load (except for the token) if the load can be
verified. False if the load is invalid.
'''
if any(key not in load for key in verify_keys):
return False
if 'tok' not in load:
log.error(
'Received incomplete call from %s for \'%s\', missing \'%s\'',
load['id'], inspect_stack()['co_name'], 'tok'
)
return False
if not self.__verify_minion(load['id'], load['tok']):
# The minion is not who it says it is!
# We don't want to listen to it!
log.warning('Minion id %s is not who it says it is!', load['id'])
return False
if 'tok' in load:
load.pop('tok')
return load | [
"def",
"__verify_load",
"(",
"self",
",",
"load",
",",
"verify_keys",
")",
":",
"if",
"any",
"(",
"key",
"not",
"in",
"load",
"for",
"key",
"in",
"verify_keys",
")",
":",
"return",
"False",
"if",
"'tok'",
"not",
"in",
"load",
":",
"log",
".",
"error"... | A utility function to perform common verification steps.
:param dict load: A payload received from a minion
:param list verify_keys: A list of strings that should be present in a
given load
:rtype: bool
:rtype: dict
:return: The original load (except for the token) if the load can be
verified. False if the load is invalid. | [
"A",
"utility",
"function",
"to",
"perform",
"common",
"verification",
"steps",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1296-L1326 | train |
saltstack/salt | salt/master.py | AESFuncs._master_tops | def _master_tops(self, load):
'''
Return the results from an external node classifier if one is
specified
:param dict load: A payload received from a minion
:return: The results from an external node classifier
'''
load = self.__verify_load(load, ('id', 'tok'))
if load is False:
return {}
return self.masterapi._master_tops(load, skip_verify=True) | python | def _master_tops(self, load):
'''
Return the results from an external node classifier if one is
specified
:param dict load: A payload received from a minion
:return: The results from an external node classifier
'''
load = self.__verify_load(load, ('id', 'tok'))
if load is False:
return {}
return self.masterapi._master_tops(load, skip_verify=True) | [
"def",
"_master_tops",
"(",
"self",
",",
"load",
")",
":",
"load",
"=",
"self",
".",
"__verify_load",
"(",
"load",
",",
"(",
"'id'",
",",
"'tok'",
")",
")",
"if",
"load",
"is",
"False",
":",
"return",
"{",
"}",
"return",
"self",
".",
"masterapi",
"... | Return the results from an external node classifier if one is
specified
:param dict load: A payload received from a minion
:return: The results from an external node classifier | [
"Return",
"the",
"results",
"from",
"an",
"external",
"node",
"classifier",
"if",
"one",
"is",
"specified"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1328-L1339 | train |
saltstack/salt | salt/master.py | AESFuncs._mine_get | def _mine_get(self, load):
'''
Gathers the data from the specified minions' mine
:param dict load: A payload received from a minion
:rtype: dict
:return: Mine data from the specified minions
'''
load = self.__verify_load(load, ('id', 'tgt', 'fun', 'tok'))
if load is False:
return {}
else:
return self.masterapi._mine_get(load, skip_verify=True) | python | def _mine_get(self, load):
'''
Gathers the data from the specified minions' mine
:param dict load: A payload received from a minion
:rtype: dict
:return: Mine data from the specified minions
'''
load = self.__verify_load(load, ('id', 'tgt', 'fun', 'tok'))
if load is False:
return {}
else:
return self.masterapi._mine_get(load, skip_verify=True) | [
"def",
"_mine_get",
"(",
"self",
",",
"load",
")",
":",
"load",
"=",
"self",
".",
"__verify_load",
"(",
"load",
",",
"(",
"'id'",
",",
"'tgt'",
",",
"'fun'",
",",
"'tok'",
")",
")",
"if",
"load",
"is",
"False",
":",
"return",
"{",
"}",
"else",
":... | Gathers the data from the specified minions' mine
:param dict load: A payload received from a minion
:rtype: dict
:return: Mine data from the specified minions | [
"Gathers",
"the",
"data",
"from",
"the",
"specified",
"minions",
"mine"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1379-L1392 | train |
saltstack/salt | salt/master.py | AESFuncs._mine | def _mine(self, load):
'''
Store the mine data
:param dict load: A payload received from a minion
:rtype: bool
:return: True if the data has been stored in the mine
'''
load = self.__verify_load(load, ('id', 'data', 'tok'))
if load is False:
return {}
return self.masterapi._mine(load, skip_verify=True) | python | def _mine(self, load):
'''
Store the mine data
:param dict load: A payload received from a minion
:rtype: bool
:return: True if the data has been stored in the mine
'''
load = self.__verify_load(load, ('id', 'data', 'tok'))
if load is False:
return {}
return self.masterapi._mine(load, skip_verify=True) | [
"def",
"_mine",
"(",
"self",
",",
"load",
")",
":",
"load",
"=",
"self",
".",
"__verify_load",
"(",
"load",
",",
"(",
"'id'",
",",
"'data'",
",",
"'tok'",
")",
")",
"if",
"load",
"is",
"False",
":",
"return",
"{",
"}",
"return",
"self",
".",
"mas... | Store the mine data
:param dict load: A payload received from a minion
:rtype: bool
:return: True if the data has been stored in the mine | [
"Store",
"the",
"mine",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1394-L1406 | train |
saltstack/salt | salt/master.py | AESFuncs._mine_delete | def _mine_delete(self, load):
'''
Allow the minion to delete a specific function from its own mine
:param dict load: A payload received from a minion
:rtype: bool
:return: Boolean indicating whether or not the given function was deleted from the mine
'''
load = self.__verify_load(load, ('id', 'fun', 'tok'))
if load is False:
return {}
else:
return self.masterapi._mine_delete(load) | python | def _mine_delete(self, load):
'''
Allow the minion to delete a specific function from its own mine
:param dict load: A payload received from a minion
:rtype: bool
:return: Boolean indicating whether or not the given function was deleted from the mine
'''
load = self.__verify_load(load, ('id', 'fun', 'tok'))
if load is False:
return {}
else:
return self.masterapi._mine_delete(load) | [
"def",
"_mine_delete",
"(",
"self",
",",
"load",
")",
":",
"load",
"=",
"self",
".",
"__verify_load",
"(",
"load",
",",
"(",
"'id'",
",",
"'fun'",
",",
"'tok'",
")",
")",
"if",
"load",
"is",
"False",
":",
"return",
"{",
"}",
"else",
":",
"return",
... | Allow the minion to delete a specific function from its own mine
:param dict load: A payload received from a minion
:rtype: bool
:return: Boolean indicating whether or not the given function was deleted from the mine | [
"Allow",
"the",
"minion",
"to",
"delete",
"a",
"specific",
"function",
"from",
"its",
"own",
"mine"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1408-L1421 | train |
saltstack/salt | salt/master.py | AESFuncs._mine_flush | def _mine_flush(self, load):
'''
Allow the minion to delete all of its own mine contents
:param dict load: A payload received from a minion
'''
load = self.__verify_load(load, ('id', 'tok'))
if load is False:
return {}
else:
return self.masterapi._mine_flush(load, skip_verify=True) | python | def _mine_flush(self, load):
'''
Allow the minion to delete all of its own mine contents
:param dict load: A payload received from a minion
'''
load = self.__verify_load(load, ('id', 'tok'))
if load is False:
return {}
else:
return self.masterapi._mine_flush(load, skip_verify=True) | [
"def",
"_mine_flush",
"(",
"self",
",",
"load",
")",
":",
"load",
"=",
"self",
".",
"__verify_load",
"(",
"load",
",",
"(",
"'id'",
",",
"'tok'",
")",
")",
"if",
"load",
"is",
"False",
":",
"return",
"{",
"}",
"else",
":",
"return",
"self",
".",
... | Allow the minion to delete all of its own mine contents
:param dict load: A payload received from a minion | [
"Allow",
"the",
"minion",
"to",
"delete",
"all",
"of",
"its",
"own",
"mine",
"contents"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1423-L1433 | train |
saltstack/salt | salt/master.py | AESFuncs._file_recv | def _file_recv(self, load):
'''
Allows minions to send files to the master, files are sent to the
master file cache
'''
if any(key not in load for key in ('id', 'path', 'loc')):
return False
if not isinstance(load['path'], list):
return False
if not self.opts['file_recv']:
return False
if not salt.utils.verify.valid_id(self.opts, load['id']):
return False
if 'loc' in load and load['loc'] < 0:
log.error('Invalid file pointer: load[loc] < 0')
return False
if len(load['data']) + load.get('loc', 0) > self.opts['file_recv_max_size'] * 0x100000:
log.error(
'file_recv_max_size limit of %d MB exceeded! %s will be '
'truncated. To successfully push this file, adjust '
'file_recv_max_size to an integer (in MB) large enough to '
'accommodate it.', self.opts['file_recv_max_size'], load['path']
)
return False
if 'tok' not in load:
log.error(
'Received incomplete call from %s for \'%s\', missing \'%s\'',
load['id'], inspect_stack()['co_name'], 'tok'
)
return False
if not self.__verify_minion(load['id'], load['tok']):
# The minion is not who it says it is!
# We don't want to listen to it!
log.warning('Minion id %s is not who it says it is!', load['id'])
return {}
load.pop('tok')
# Join path
sep_path = os.sep.join(load['path'])
# Path normalization should have been done by the sending
# minion but we can't guarantee it. Re-do it here.
normpath = os.path.normpath(sep_path)
# Ensure that this safety check is done after the path
# have been normalized.
if os.path.isabs(normpath) or '../' in load['path']:
# Can overwrite master files!!
return False
cpath = os.path.join(
self.opts['cachedir'],
'minions',
load['id'],
'files',
normpath)
# One last safety check here
if not os.path.normpath(cpath).startswith(self.opts['cachedir']):
log.warning(
'Attempt to write received file outside of master cache '
'directory! Requested path: %s. Access denied.', cpath
)
return False
cdir = os.path.dirname(cpath)
if not os.path.isdir(cdir):
try:
os.makedirs(cdir)
except os.error:
pass
if os.path.isfile(cpath) and load['loc'] != 0:
mode = 'ab'
else:
mode = 'wb'
with salt.utils.files.fopen(cpath, mode) as fp_:
if load['loc']:
fp_.seek(load['loc'])
fp_.write(salt.utils.stringutils.to_bytes(load['data']))
return True | python | def _file_recv(self, load):
'''
Allows minions to send files to the master, files are sent to the
master file cache
'''
if any(key not in load for key in ('id', 'path', 'loc')):
return False
if not isinstance(load['path'], list):
return False
if not self.opts['file_recv']:
return False
if not salt.utils.verify.valid_id(self.opts, load['id']):
return False
if 'loc' in load and load['loc'] < 0:
log.error('Invalid file pointer: load[loc] < 0')
return False
if len(load['data']) + load.get('loc', 0) > self.opts['file_recv_max_size'] * 0x100000:
log.error(
'file_recv_max_size limit of %d MB exceeded! %s will be '
'truncated. To successfully push this file, adjust '
'file_recv_max_size to an integer (in MB) large enough to '
'accommodate it.', self.opts['file_recv_max_size'], load['path']
)
return False
if 'tok' not in load:
log.error(
'Received incomplete call from %s for \'%s\', missing \'%s\'',
load['id'], inspect_stack()['co_name'], 'tok'
)
return False
if not self.__verify_minion(load['id'], load['tok']):
# The minion is not who it says it is!
# We don't want to listen to it!
log.warning('Minion id %s is not who it says it is!', load['id'])
return {}
load.pop('tok')
# Join path
sep_path = os.sep.join(load['path'])
# Path normalization should have been done by the sending
# minion but we can't guarantee it. Re-do it here.
normpath = os.path.normpath(sep_path)
# Ensure that this safety check is done after the path
# have been normalized.
if os.path.isabs(normpath) or '../' in load['path']:
# Can overwrite master files!!
return False
cpath = os.path.join(
self.opts['cachedir'],
'minions',
load['id'],
'files',
normpath)
# One last safety check here
if not os.path.normpath(cpath).startswith(self.opts['cachedir']):
log.warning(
'Attempt to write received file outside of master cache '
'directory! Requested path: %s. Access denied.', cpath
)
return False
cdir = os.path.dirname(cpath)
if not os.path.isdir(cdir):
try:
os.makedirs(cdir)
except os.error:
pass
if os.path.isfile(cpath) and load['loc'] != 0:
mode = 'ab'
else:
mode = 'wb'
with salt.utils.files.fopen(cpath, mode) as fp_:
if load['loc']:
fp_.seek(load['loc'])
fp_.write(salt.utils.stringutils.to_bytes(load['data']))
return True | [
"def",
"_file_recv",
"(",
"self",
",",
"load",
")",
":",
"if",
"any",
"(",
"key",
"not",
"in",
"load",
"for",
"key",
"in",
"(",
"'id'",
",",
"'path'",
",",
"'loc'",
")",
")",
":",
"return",
"False",
"if",
"not",
"isinstance",
"(",
"load",
"[",
"'... | Allows minions to send files to the master, files are sent to the
master file cache | [
"Allows",
"minions",
"to",
"send",
"files",
"to",
"the",
"master",
"files",
"are",
"sent",
"to",
"the",
"master",
"file",
"cache"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1435-L1514 | train |
saltstack/salt | salt/master.py | AESFuncs._pillar | def _pillar(self, load):
'''
Return the pillar data for the minion
:param dict load: Minion payload
:rtype: dict
:return: The pillar data for the minion
'''
if any(key not in load for key in ('id', 'grains')):
return False
if not salt.utils.verify.valid_id(self.opts, load['id']):
return False
load['grains']['id'] = load['id']
pillar = salt.pillar.get_pillar(
self.opts,
load['grains'],
load['id'],
load.get('saltenv', load.get('env')),
ext=load.get('ext'),
pillar_override=load.get('pillar_override', {}),
pillarenv=load.get('pillarenv'),
extra_minion_data=load.get('extra_minion_data'))
data = pillar.compile_pillar()
self.fs_.update_opts()
if self.opts.get('minion_data_cache', False):
self.masterapi.cache.store('minions/{0}'.format(load['id']),
'data',
{'grains': load['grains'],
'pillar': data})
if self.opts.get('minion_data_cache_events') is True:
self.event.fire_event({'Minion data cache refresh': load['id']}, tagify(load['id'], 'refresh', 'minion'))
return data | python | def _pillar(self, load):
'''
Return the pillar data for the minion
:param dict load: Minion payload
:rtype: dict
:return: The pillar data for the minion
'''
if any(key not in load for key in ('id', 'grains')):
return False
if not salt.utils.verify.valid_id(self.opts, load['id']):
return False
load['grains']['id'] = load['id']
pillar = salt.pillar.get_pillar(
self.opts,
load['grains'],
load['id'],
load.get('saltenv', load.get('env')),
ext=load.get('ext'),
pillar_override=load.get('pillar_override', {}),
pillarenv=load.get('pillarenv'),
extra_minion_data=load.get('extra_minion_data'))
data = pillar.compile_pillar()
self.fs_.update_opts()
if self.opts.get('minion_data_cache', False):
self.masterapi.cache.store('minions/{0}'.format(load['id']),
'data',
{'grains': load['grains'],
'pillar': data})
if self.opts.get('minion_data_cache_events') is True:
self.event.fire_event({'Minion data cache refresh': load['id']}, tagify(load['id'], 'refresh', 'minion'))
return data | [
"def",
"_pillar",
"(",
"self",
",",
"load",
")",
":",
"if",
"any",
"(",
"key",
"not",
"in",
"load",
"for",
"key",
"in",
"(",
"'id'",
",",
"'grains'",
")",
")",
":",
"return",
"False",
"if",
"not",
"salt",
".",
"utils",
".",
"verify",
".",
"valid_... | Return the pillar data for the minion
:param dict load: Minion payload
:rtype: dict
:return: The pillar data for the minion | [
"Return",
"the",
"pillar",
"data",
"for",
"the",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1516-L1549 | train |
saltstack/salt | salt/master.py | AESFuncs._minion_event | def _minion_event(self, load):
'''
Receive an event from the minion and fire it on the master event
interface
:param dict load: The minion payload
'''
load = self.__verify_load(load, ('id', 'tok'))
if load is False:
return {}
# Route to master event bus
self.masterapi._minion_event(load)
# Process locally
self._handle_minion_event(load) | python | def _minion_event(self, load):
'''
Receive an event from the minion and fire it on the master event
interface
:param dict load: The minion payload
'''
load = self.__verify_load(load, ('id', 'tok'))
if load is False:
return {}
# Route to master event bus
self.masterapi._minion_event(load)
# Process locally
self._handle_minion_event(load) | [
"def",
"_minion_event",
"(",
"self",
",",
"load",
")",
":",
"load",
"=",
"self",
".",
"__verify_load",
"(",
"load",
",",
"(",
"'id'",
",",
"'tok'",
")",
")",
"if",
"load",
"is",
"False",
":",
"return",
"{",
"}",
"# Route to master event bus",
"self",
"... | Receive an event from the minion and fire it on the master event
interface
:param dict load: The minion payload | [
"Receive",
"an",
"event",
"from",
"the",
"minion",
"and",
"fire",
"it",
"on",
"the",
"master",
"event",
"interface"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1551-L1564 | train |
saltstack/salt | salt/master.py | AESFuncs._handle_minion_event | def _handle_minion_event(self, load):
'''
Act on specific events from minions
'''
id_ = load['id']
if load.get('tag', '') == '_salt_error':
log.error(
'Received minion error from [%s]: %s',
id_, load['data']['message']
)
for event in load.get('events', []):
event_data = event.get('data', {})
if 'minions' in event_data:
jid = event_data.get('jid')
if not jid:
continue
minions = event_data['minions']
try:
salt.utils.job.store_minions(
self.opts,
jid,
minions,
mminion=self.mminion,
syndic_id=id_)
except (KeyError, salt.exceptions.SaltCacheError) as exc:
log.error(
'Could not add minion(s) %s for job %s: %s',
minions, jid, exc
) | python | def _handle_minion_event(self, load):
'''
Act on specific events from minions
'''
id_ = load['id']
if load.get('tag', '') == '_salt_error':
log.error(
'Received minion error from [%s]: %s',
id_, load['data']['message']
)
for event in load.get('events', []):
event_data = event.get('data', {})
if 'minions' in event_data:
jid = event_data.get('jid')
if not jid:
continue
minions = event_data['minions']
try:
salt.utils.job.store_minions(
self.opts,
jid,
minions,
mminion=self.mminion,
syndic_id=id_)
except (KeyError, salt.exceptions.SaltCacheError) as exc:
log.error(
'Could not add minion(s) %s for job %s: %s',
minions, jid, exc
) | [
"def",
"_handle_minion_event",
"(",
"self",
",",
"load",
")",
":",
"id_",
"=",
"load",
"[",
"'id'",
"]",
"if",
"load",
".",
"get",
"(",
"'tag'",
",",
"''",
")",
"==",
"'_salt_error'",
":",
"log",
".",
"error",
"(",
"'Received minion error from [%s]: %s'",
... | Act on specific events from minions | [
"Act",
"on",
"specific",
"events",
"from",
"minions"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1566-L1595 | train |
saltstack/salt | salt/master.py | AESFuncs._return | def _return(self, load):
'''
Handle the return data sent from the minions.
Takes the return, verifies it and fires it on the master event bus.
Typically, this event is consumed by the Salt CLI waiting on the other
end of the event bus but could be heard by any listener on the bus.
:param dict load: The minion payload
'''
if self.opts['require_minion_sign_messages'] and 'sig' not in load:
log.critical(
'_return: Master is requiring minions to sign their '
'messages, but there is no signature in this payload from '
'%s.', load['id']
)
return False
if 'sig' in load:
log.trace('Verifying signed event publish from minion')
sig = load.pop('sig')
this_minion_pubkey = os.path.join(self.opts['pki_dir'], 'minions/{0}'.format(load['id']))
serialized_load = salt.serializers.msgpack.serialize(load)
if not salt.crypt.verify_signature(this_minion_pubkey, serialized_load, sig):
log.info('Failed to verify event signature from minion %s.', load['id'])
if self.opts['drop_messages_signature_fail']:
log.critical(
'Drop_messages_signature_fail is enabled, dropping '
'message from %s', load['id']
)
return False
else:
log.info('But \'drop_message_signature_fail\' is disabled, so message is still accepted.')
load['sig'] = sig
try:
salt.utils.job.store_job(
self.opts, load, event=self.event, mminion=self.mminion)
except salt.exceptions.SaltCacheError:
log.error('Could not store job information for load: %s', load) | python | def _return(self, load):
'''
Handle the return data sent from the minions.
Takes the return, verifies it and fires it on the master event bus.
Typically, this event is consumed by the Salt CLI waiting on the other
end of the event bus but could be heard by any listener on the bus.
:param dict load: The minion payload
'''
if self.opts['require_minion_sign_messages'] and 'sig' not in load:
log.critical(
'_return: Master is requiring minions to sign their '
'messages, but there is no signature in this payload from '
'%s.', load['id']
)
return False
if 'sig' in load:
log.trace('Verifying signed event publish from minion')
sig = load.pop('sig')
this_minion_pubkey = os.path.join(self.opts['pki_dir'], 'minions/{0}'.format(load['id']))
serialized_load = salt.serializers.msgpack.serialize(load)
if not salt.crypt.verify_signature(this_minion_pubkey, serialized_load, sig):
log.info('Failed to verify event signature from minion %s.', load['id'])
if self.opts['drop_messages_signature_fail']:
log.critical(
'Drop_messages_signature_fail is enabled, dropping '
'message from %s', load['id']
)
return False
else:
log.info('But \'drop_message_signature_fail\' is disabled, so message is still accepted.')
load['sig'] = sig
try:
salt.utils.job.store_job(
self.opts, load, event=self.event, mminion=self.mminion)
except salt.exceptions.SaltCacheError:
log.error('Could not store job information for load: %s', load) | [
"def",
"_return",
"(",
"self",
",",
"load",
")",
":",
"if",
"self",
".",
"opts",
"[",
"'require_minion_sign_messages'",
"]",
"and",
"'sig'",
"not",
"in",
"load",
":",
"log",
".",
"critical",
"(",
"'_return: Master is requiring minions to sign their '",
"'messages,... | Handle the return data sent from the minions.
Takes the return, verifies it and fires it on the master event bus.
Typically, this event is consumed by the Salt CLI waiting on the other
end of the event bus but could be heard by any listener on the bus.
:param dict load: The minion payload | [
"Handle",
"the",
"return",
"data",
"sent",
"from",
"the",
"minions",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1597-L1636 | train |
saltstack/salt | salt/master.py | AESFuncs._syndic_return | def _syndic_return(self, load):
'''
Receive a syndic minion return and format it to look like returns from
individual minions.
:param dict load: The minion payload
'''
loads = load.get('load')
if not isinstance(loads, list):
loads = [load] # support old syndics not aggregating returns
for load in loads:
# Verify the load
if any(key not in load for key in ('return', 'jid', 'id')):
continue
# if we have a load, save it
if load.get('load'):
fstr = '{0}.save_load'.format(self.opts['master_job_cache'])
self.mminion.returners[fstr](load['jid'], load['load'])
# Register the syndic
syndic_cache_path = os.path.join(self.opts['cachedir'], 'syndics', load['id'])
if not os.path.exists(syndic_cache_path):
path_name = os.path.split(syndic_cache_path)[0]
if not os.path.exists(path_name):
os.makedirs(path_name)
with salt.utils.files.fopen(syndic_cache_path, 'w') as wfh:
wfh.write('')
# Format individual return loads
for key, item in six.iteritems(load['return']):
ret = {'jid': load['jid'],
'id': key}
ret.update(item)
if 'master_id' in load:
ret['master_id'] = load['master_id']
if 'fun' in load:
ret['fun'] = load['fun']
if 'arg' in load:
ret['fun_args'] = load['arg']
if 'out' in load:
ret['out'] = load['out']
if 'sig' in load:
ret['sig'] = load['sig']
self._return(ret) | python | def _syndic_return(self, load):
'''
Receive a syndic minion return and format it to look like returns from
individual minions.
:param dict load: The minion payload
'''
loads = load.get('load')
if not isinstance(loads, list):
loads = [load] # support old syndics not aggregating returns
for load in loads:
# Verify the load
if any(key not in load for key in ('return', 'jid', 'id')):
continue
# if we have a load, save it
if load.get('load'):
fstr = '{0}.save_load'.format(self.opts['master_job_cache'])
self.mminion.returners[fstr](load['jid'], load['load'])
# Register the syndic
syndic_cache_path = os.path.join(self.opts['cachedir'], 'syndics', load['id'])
if not os.path.exists(syndic_cache_path):
path_name = os.path.split(syndic_cache_path)[0]
if not os.path.exists(path_name):
os.makedirs(path_name)
with salt.utils.files.fopen(syndic_cache_path, 'w') as wfh:
wfh.write('')
# Format individual return loads
for key, item in six.iteritems(load['return']):
ret = {'jid': load['jid'],
'id': key}
ret.update(item)
if 'master_id' in load:
ret['master_id'] = load['master_id']
if 'fun' in load:
ret['fun'] = load['fun']
if 'arg' in load:
ret['fun_args'] = load['arg']
if 'out' in load:
ret['out'] = load['out']
if 'sig' in load:
ret['sig'] = load['sig']
self._return(ret) | [
"def",
"_syndic_return",
"(",
"self",
",",
"load",
")",
":",
"loads",
"=",
"load",
".",
"get",
"(",
"'load'",
")",
"if",
"not",
"isinstance",
"(",
"loads",
",",
"list",
")",
":",
"loads",
"=",
"[",
"load",
"]",
"# support old syndics not aggregating return... | Receive a syndic minion return and format it to look like returns from
individual minions.
:param dict load: The minion payload | [
"Receive",
"a",
"syndic",
"minion",
"return",
"and",
"format",
"it",
"to",
"look",
"like",
"returns",
"from",
"individual",
"minions",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1638-L1681 | train |
saltstack/salt | salt/master.py | AESFuncs.minion_runner | def minion_runner(self, clear_load):
'''
Execute a runner from a minion, return the runner's function data
:param dict clear_load: The minion payload
:rtype: dict
:return: The runner function data
'''
load = self.__verify_load(clear_load, ('fun', 'arg', 'id', 'tok'))
if load is False:
return {}
else:
return self.masterapi.minion_runner(clear_load) | python | def minion_runner(self, clear_load):
'''
Execute a runner from a minion, return the runner's function data
:param dict clear_load: The minion payload
:rtype: dict
:return: The runner function data
'''
load = self.__verify_load(clear_load, ('fun', 'arg', 'id', 'tok'))
if load is False:
return {}
else:
return self.masterapi.minion_runner(clear_load) | [
"def",
"minion_runner",
"(",
"self",
",",
"clear_load",
")",
":",
"load",
"=",
"self",
".",
"__verify_load",
"(",
"clear_load",
",",
"(",
"'fun'",
",",
"'arg'",
",",
"'id'",
",",
"'tok'",
")",
")",
"if",
"load",
"is",
"False",
":",
"return",
"{",
"}"... | Execute a runner from a minion, return the runner's function data
:param dict clear_load: The minion payload
:rtype: dict
:return: The runner function data | [
"Execute",
"a",
"runner",
"from",
"a",
"minion",
"return",
"the",
"runner",
"s",
"function",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1683-L1696 | train |
saltstack/salt | salt/master.py | AESFuncs.pub_ret | def pub_ret(self, load):
'''
Request the return data from a specific jid, only allowed
if the requesting minion also initialted the execution.
:param dict load: The minion payload
:rtype: dict
:return: Return data corresponding to a given JID
'''
load = self.__verify_load(load, ('jid', 'id', 'tok'))
if load is False:
return {}
# Check that this minion can access this data
auth_cache = os.path.join(
self.opts['cachedir'],
'publish_auth')
if not os.path.isdir(auth_cache):
os.makedirs(auth_cache)
jid_fn = os.path.join(auth_cache, six.text_type(load['jid']))
with salt.utils.files.fopen(jid_fn, 'r') as fp_:
if not load['id'] == fp_.read():
return {}
# Grab the latest and return
return self.local.get_cache_returns(load['jid']) | python | def pub_ret(self, load):
'''
Request the return data from a specific jid, only allowed
if the requesting minion also initialted the execution.
:param dict load: The minion payload
:rtype: dict
:return: Return data corresponding to a given JID
'''
load = self.__verify_load(load, ('jid', 'id', 'tok'))
if load is False:
return {}
# Check that this minion can access this data
auth_cache = os.path.join(
self.opts['cachedir'],
'publish_auth')
if not os.path.isdir(auth_cache):
os.makedirs(auth_cache)
jid_fn = os.path.join(auth_cache, six.text_type(load['jid']))
with salt.utils.files.fopen(jid_fn, 'r') as fp_:
if not load['id'] == fp_.read():
return {}
# Grab the latest and return
return self.local.get_cache_returns(load['jid']) | [
"def",
"pub_ret",
"(",
"self",
",",
"load",
")",
":",
"load",
"=",
"self",
".",
"__verify_load",
"(",
"load",
",",
"(",
"'jid'",
",",
"'id'",
",",
"'tok'",
")",
")",
"if",
"load",
"is",
"False",
":",
"return",
"{",
"}",
"# Check that this minion can ac... | Request the return data from a specific jid, only allowed
if the requesting minion also initialted the execution.
:param dict load: The minion payload
:rtype: dict
:return: Return data corresponding to a given JID | [
"Request",
"the",
"return",
"data",
"from",
"a",
"specific",
"jid",
"only",
"allowed",
"if",
"the",
"requesting",
"minion",
"also",
"initialted",
"the",
"execution",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1698-L1722 | train |
saltstack/salt | salt/master.py | AESFuncs.minion_pub | def minion_pub(self, clear_load):
'''
Publish a command initiated from a minion, this method executes minion
restrictions so that the minion publication will only work if it is
enabled in the config.
The configuration on the master allows minions to be matched to
salt functions, so the minions can only publish allowed salt functions
The config will look like this:
.. code-block:: bash
peer:
.*:
- .*
This configuration will enable all minions to execute all commands:
.. code-block:: bash
peer:
foo.example.com:
- test.*
The above configuration will only allow the minion foo.example.com to
execute commands from the test module.
:param dict clear_load: The minion pay
'''
if not self.__verify_minion_publish(clear_load):
return {}
else:
return self.masterapi.minion_pub(clear_load) | python | def minion_pub(self, clear_load):
'''
Publish a command initiated from a minion, this method executes minion
restrictions so that the minion publication will only work if it is
enabled in the config.
The configuration on the master allows minions to be matched to
salt functions, so the minions can only publish allowed salt functions
The config will look like this:
.. code-block:: bash
peer:
.*:
- .*
This configuration will enable all minions to execute all commands:
.. code-block:: bash
peer:
foo.example.com:
- test.*
The above configuration will only allow the minion foo.example.com to
execute commands from the test module.
:param dict clear_load: The minion pay
'''
if not self.__verify_minion_publish(clear_load):
return {}
else:
return self.masterapi.minion_pub(clear_load) | [
"def",
"minion_pub",
"(",
"self",
",",
"clear_load",
")",
":",
"if",
"not",
"self",
".",
"__verify_minion_publish",
"(",
"clear_load",
")",
":",
"return",
"{",
"}",
"else",
":",
"return",
"self",
".",
"masterapi",
".",
"minion_pub",
"(",
"clear_load",
")"
... | Publish a command initiated from a minion, this method executes minion
restrictions so that the minion publication will only work if it is
enabled in the config.
The configuration on the master allows minions to be matched to
salt functions, so the minions can only publish allowed salt functions
The config will look like this:
.. code-block:: bash
peer:
.*:
- .*
This configuration will enable all minions to execute all commands:
.. code-block:: bash
peer:
foo.example.com:
- test.*
The above configuration will only allow the minion foo.example.com to
execute commands from the test module.
:param dict clear_load: The minion pay | [
"Publish",
"a",
"command",
"initiated",
"from",
"a",
"minion",
"this",
"method",
"executes",
"minion",
"restrictions",
"so",
"that",
"the",
"minion",
"publication",
"will",
"only",
"work",
"if",
"it",
"is",
"enabled",
"in",
"the",
"config",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1724-L1757 | train |
saltstack/salt | salt/master.py | AESFuncs.minion_publish | def minion_publish(self, clear_load):
'''
Publish a command initiated from a minion, this method executes minion
restrictions so that the minion publication will only work if it is
enabled in the config.
The configuration on the master allows minions to be matched to
salt functions, so the minions can only publish allowed salt functions
The config will look like this:
.. code-block:: bash
peer:
.*:
- .*
This configuration will enable all minions to execute all commands.
peer:
.. code-block:: bash
foo.example.com:
- test.*
The above configuration will only allow the minion foo.example.com to
execute commands from the test module.
:param dict clear_load: The minion payload
'''
if not self.__verify_minion_publish(clear_load):
return {}
else:
return self.masterapi.minion_publish(clear_load) | python | def minion_publish(self, clear_load):
'''
Publish a command initiated from a minion, this method executes minion
restrictions so that the minion publication will only work if it is
enabled in the config.
The configuration on the master allows minions to be matched to
salt functions, so the minions can only publish allowed salt functions
The config will look like this:
.. code-block:: bash
peer:
.*:
- .*
This configuration will enable all minions to execute all commands.
peer:
.. code-block:: bash
foo.example.com:
- test.*
The above configuration will only allow the minion foo.example.com to
execute commands from the test module.
:param dict clear_load: The minion payload
'''
if not self.__verify_minion_publish(clear_load):
return {}
else:
return self.masterapi.minion_publish(clear_load) | [
"def",
"minion_publish",
"(",
"self",
",",
"clear_load",
")",
":",
"if",
"not",
"self",
".",
"__verify_minion_publish",
"(",
"clear_load",
")",
":",
"return",
"{",
"}",
"else",
":",
"return",
"self",
".",
"masterapi",
".",
"minion_publish",
"(",
"clear_load"... | Publish a command initiated from a minion, this method executes minion
restrictions so that the minion publication will only work if it is
enabled in the config.
The configuration on the master allows minions to be matched to
salt functions, so the minions can only publish allowed salt functions
The config will look like this:
.. code-block:: bash
peer:
.*:
- .*
This configuration will enable all minions to execute all commands.
peer:
.. code-block:: bash
foo.example.com:
- test.*
The above configuration will only allow the minion foo.example.com to
execute commands from the test module.
:param dict clear_load: The minion payload | [
"Publish",
"a",
"command",
"initiated",
"from",
"a",
"minion",
"this",
"method",
"executes",
"minion",
"restrictions",
"so",
"that",
"the",
"minion",
"publication",
"will",
"only",
"work",
"if",
"it",
"is",
"enabled",
"in",
"the",
"config",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1759-L1792 | train |
saltstack/salt | salt/master.py | AESFuncs.revoke_auth | def revoke_auth(self, load):
'''
Allow a minion to request revocation of its own key
:param dict load: The minion payload
:rtype: dict
:return: If the load is invalid, it may be returned. No key operation is performed.
:rtype: bool
:return: True if key was revoked, False if not
'''
load = self.__verify_load(load, ('id', 'tok'))
if not self.opts.get('allow_minion_key_revoke', False):
log.warning(
'Minion %s requested key revoke, but allow_minion_key_revoke '
'is set to False', load['id']
)
return load
if load is False:
return load
else:
return self.masterapi.revoke_auth(load) | python | def revoke_auth(self, load):
'''
Allow a minion to request revocation of its own key
:param dict load: The minion payload
:rtype: dict
:return: If the load is invalid, it may be returned. No key operation is performed.
:rtype: bool
:return: True if key was revoked, False if not
'''
load = self.__verify_load(load, ('id', 'tok'))
if not self.opts.get('allow_minion_key_revoke', False):
log.warning(
'Minion %s requested key revoke, but allow_minion_key_revoke '
'is set to False', load['id']
)
return load
if load is False:
return load
else:
return self.masterapi.revoke_auth(load) | [
"def",
"revoke_auth",
"(",
"self",
",",
"load",
")",
":",
"load",
"=",
"self",
".",
"__verify_load",
"(",
"load",
",",
"(",
"'id'",
",",
"'tok'",
")",
")",
"if",
"not",
"self",
".",
"opts",
".",
"get",
"(",
"'allow_minion_key_revoke'",
",",
"False",
... | Allow a minion to request revocation of its own key
:param dict load: The minion payload
:rtype: dict
:return: If the load is invalid, it may be returned. No key operation is performed.
:rtype: bool
:return: True if key was revoked, False if not | [
"Allow",
"a",
"minion",
"to",
"request",
"revocation",
"of",
"its",
"own",
"key"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1794-L1818 | train |
saltstack/salt | salt/master.py | AESFuncs.run_func | def run_func(self, func, load):
'''
Wrapper for running functions executed with AES encryption
:param function func: The function to run
:return: The result of the master function that was called
'''
# Don't honor private functions
if func.startswith('__'):
# TODO: return some error? Seems odd to return {}
return {}, {'fun': 'send'}
# Run the func
if hasattr(self, func):
try:
start = time.time()
ret = getattr(self, func)(load)
log.trace(
'Master function call %s took %s seconds',
func, time.time() - start
)
except Exception:
ret = ''
log.error('Error in function %s:\n', func, exc_info=True)
else:
log.error(
'Received function %s which is unavailable on the master, '
'returning False', func
)
return False, {'fun': 'send'}
# Don't encrypt the return value for the _return func
# (we don't care about the return value, so why encrypt it?)
if func == '_return':
return ret, {'fun': 'send'}
if func == '_pillar' and 'id' in load:
if load.get('ver') != '2' and self.opts['pillar_version'] == 1:
# Authorized to return old pillar proto
return ret, {'fun': 'send'}
return ret, {'fun': 'send_private', 'key': 'pillar', 'tgt': load['id']}
# Encrypt the return
return ret, {'fun': 'send'} | python | def run_func(self, func, load):
'''
Wrapper for running functions executed with AES encryption
:param function func: The function to run
:return: The result of the master function that was called
'''
# Don't honor private functions
if func.startswith('__'):
# TODO: return some error? Seems odd to return {}
return {}, {'fun': 'send'}
# Run the func
if hasattr(self, func):
try:
start = time.time()
ret = getattr(self, func)(load)
log.trace(
'Master function call %s took %s seconds',
func, time.time() - start
)
except Exception:
ret = ''
log.error('Error in function %s:\n', func, exc_info=True)
else:
log.error(
'Received function %s which is unavailable on the master, '
'returning False', func
)
return False, {'fun': 'send'}
# Don't encrypt the return value for the _return func
# (we don't care about the return value, so why encrypt it?)
if func == '_return':
return ret, {'fun': 'send'}
if func == '_pillar' and 'id' in load:
if load.get('ver') != '2' and self.opts['pillar_version'] == 1:
# Authorized to return old pillar proto
return ret, {'fun': 'send'}
return ret, {'fun': 'send_private', 'key': 'pillar', 'tgt': load['id']}
# Encrypt the return
return ret, {'fun': 'send'} | [
"def",
"run_func",
"(",
"self",
",",
"func",
",",
"load",
")",
":",
"# Don't honor private functions",
"if",
"func",
".",
"startswith",
"(",
"'__'",
")",
":",
"# TODO: return some error? Seems odd to return {}",
"return",
"{",
"}",
",",
"{",
"'fun'",
":",
"'send... | Wrapper for running functions executed with AES encryption
:param function func: The function to run
:return: The result of the master function that was called | [
"Wrapper",
"for",
"running",
"functions",
"executed",
"with",
"AES",
"encryption"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1820-L1859 | train |
saltstack/salt | salt/master.py | ClearFuncs.runner | def runner(self, clear_load):
'''
Send a master control function back to the runner system
'''
# All runner ops pass through eauth
auth_type, err_name, key, sensitive_load_keys = self._prep_auth_info(clear_load)
# Authenticate
auth_check = self.loadauth.check_authentication(clear_load, auth_type, key=key)
error = auth_check.get('error')
if error:
# Authentication error occurred: do not continue.
return {'error': error}
# Authorize
username = auth_check.get('username')
if auth_type != 'user':
runner_check = self.ckminions.runner_check(
auth_check.get('auth_list', []),
clear_load['fun'],
clear_load.get('kwarg', {})
)
if not runner_check:
return {'error': {'name': err_name,
'message': 'Authentication failure of type "{0}" occurred for '
'user {1}.'.format(auth_type, username)}}
elif isinstance(runner_check, dict) and 'error' in runner_check:
# A dictionary with an error name/message was handled by ckminions.runner_check
return runner_check
# No error occurred, consume sensitive settings from the clear_load if passed.
for item in sensitive_load_keys:
clear_load.pop(item, None)
else:
if 'user' in clear_load:
username = clear_load['user']
if salt.auth.AuthUser(username).is_sudo():
username = self.opts.get('user', 'root')
else:
username = salt.utils.user.get_user()
# Authorized. Do the job!
try:
fun = clear_load.pop('fun')
runner_client = salt.runner.RunnerClient(self.opts)
return runner_client.asynchronous(fun,
clear_load.get('kwarg', {}),
username)
except Exception as exc:
log.error('Exception occurred while introspecting %s: %s', fun, exc)
return {'error': {'name': exc.__class__.__name__,
'args': exc.args,
'message': six.text_type(exc)}} | python | def runner(self, clear_load):
'''
Send a master control function back to the runner system
'''
# All runner ops pass through eauth
auth_type, err_name, key, sensitive_load_keys = self._prep_auth_info(clear_load)
# Authenticate
auth_check = self.loadauth.check_authentication(clear_load, auth_type, key=key)
error = auth_check.get('error')
if error:
# Authentication error occurred: do not continue.
return {'error': error}
# Authorize
username = auth_check.get('username')
if auth_type != 'user':
runner_check = self.ckminions.runner_check(
auth_check.get('auth_list', []),
clear_load['fun'],
clear_load.get('kwarg', {})
)
if not runner_check:
return {'error': {'name': err_name,
'message': 'Authentication failure of type "{0}" occurred for '
'user {1}.'.format(auth_type, username)}}
elif isinstance(runner_check, dict) and 'error' in runner_check:
# A dictionary with an error name/message was handled by ckminions.runner_check
return runner_check
# No error occurred, consume sensitive settings from the clear_load if passed.
for item in sensitive_load_keys:
clear_load.pop(item, None)
else:
if 'user' in clear_load:
username = clear_load['user']
if salt.auth.AuthUser(username).is_sudo():
username = self.opts.get('user', 'root')
else:
username = salt.utils.user.get_user()
# Authorized. Do the job!
try:
fun = clear_load.pop('fun')
runner_client = salt.runner.RunnerClient(self.opts)
return runner_client.asynchronous(fun,
clear_load.get('kwarg', {}),
username)
except Exception as exc:
log.error('Exception occurred while introspecting %s: %s', fun, exc)
return {'error': {'name': exc.__class__.__name__,
'args': exc.args,
'message': six.text_type(exc)}} | [
"def",
"runner",
"(",
"self",
",",
"clear_load",
")",
":",
"# All runner ops pass through eauth",
"auth_type",
",",
"err_name",
",",
"key",
",",
"sensitive_load_keys",
"=",
"self",
".",
"_prep_auth_info",
"(",
"clear_load",
")",
"# Authenticate",
"auth_check",
"=",
... | Send a master control function back to the runner system | [
"Send",
"a",
"master",
"control",
"function",
"back",
"to",
"the",
"runner",
"system"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1894-L1947 | train |
saltstack/salt | salt/master.py | ClearFuncs.wheel | def wheel(self, clear_load):
'''
Send a master control function back to the wheel system
'''
# All wheel ops pass through eauth
auth_type, err_name, key, sensitive_load_keys = self._prep_auth_info(clear_load)
# Authenticate
auth_check = self.loadauth.check_authentication(clear_load, auth_type, key=key)
error = auth_check.get('error')
if error:
# Authentication error occurred: do not continue.
return {'error': error}
# Authorize
username = auth_check.get('username')
if auth_type != 'user':
wheel_check = self.ckminions.wheel_check(
auth_check.get('auth_list', []),
clear_load['fun'],
clear_load.get('kwarg', {})
)
if not wheel_check:
return {'error': {'name': err_name,
'message': 'Authentication failure of type "{0}" occurred for '
'user {1}.'.format(auth_type, username)}}
elif isinstance(wheel_check, dict) and 'error' in wheel_check:
# A dictionary with an error name/message was handled by ckminions.wheel_check
return wheel_check
# No error occurred, consume sensitive settings from the clear_load if passed.
for item in sensitive_load_keys:
clear_load.pop(item, None)
else:
if 'user' in clear_load:
username = clear_load['user']
if salt.auth.AuthUser(username).is_sudo():
username = self.opts.get('user', 'root')
else:
username = salt.utils.user.get_user()
# Authorized. Do the job!
try:
jid = salt.utils.jid.gen_jid(self.opts)
fun = clear_load.pop('fun')
tag = tagify(jid, prefix='wheel')
data = {'fun': "wheel.{0}".format(fun),
'jid': jid,
'tag': tag,
'user': username}
self.event.fire_event(data, tagify([jid, 'new'], 'wheel'))
ret = self.wheel_.call_func(fun, full_return=True, **clear_load)
data['return'] = ret['return']
data['success'] = ret['success']
self.event.fire_event(data, tagify([jid, 'ret'], 'wheel'))
return {'tag': tag,
'data': data}
except Exception as exc:
log.error('Exception occurred while introspecting %s: %s', fun, exc)
data['return'] = 'Exception occurred in wheel {0}: {1}: {2}'.format(
fun,
exc.__class__.__name__,
exc,
)
data['success'] = False
self.event.fire_event(data, tagify([jid, 'ret'], 'wheel'))
return {'tag': tag,
'data': data} | python | def wheel(self, clear_load):
'''
Send a master control function back to the wheel system
'''
# All wheel ops pass through eauth
auth_type, err_name, key, sensitive_load_keys = self._prep_auth_info(clear_load)
# Authenticate
auth_check = self.loadauth.check_authentication(clear_load, auth_type, key=key)
error = auth_check.get('error')
if error:
# Authentication error occurred: do not continue.
return {'error': error}
# Authorize
username = auth_check.get('username')
if auth_type != 'user':
wheel_check = self.ckminions.wheel_check(
auth_check.get('auth_list', []),
clear_load['fun'],
clear_load.get('kwarg', {})
)
if not wheel_check:
return {'error': {'name': err_name,
'message': 'Authentication failure of type "{0}" occurred for '
'user {1}.'.format(auth_type, username)}}
elif isinstance(wheel_check, dict) and 'error' in wheel_check:
# A dictionary with an error name/message was handled by ckminions.wheel_check
return wheel_check
# No error occurred, consume sensitive settings from the clear_load if passed.
for item in sensitive_load_keys:
clear_load.pop(item, None)
else:
if 'user' in clear_load:
username = clear_load['user']
if salt.auth.AuthUser(username).is_sudo():
username = self.opts.get('user', 'root')
else:
username = salt.utils.user.get_user()
# Authorized. Do the job!
try:
jid = salt.utils.jid.gen_jid(self.opts)
fun = clear_load.pop('fun')
tag = tagify(jid, prefix='wheel')
data = {'fun': "wheel.{0}".format(fun),
'jid': jid,
'tag': tag,
'user': username}
self.event.fire_event(data, tagify([jid, 'new'], 'wheel'))
ret = self.wheel_.call_func(fun, full_return=True, **clear_load)
data['return'] = ret['return']
data['success'] = ret['success']
self.event.fire_event(data, tagify([jid, 'ret'], 'wheel'))
return {'tag': tag,
'data': data}
except Exception as exc:
log.error('Exception occurred while introspecting %s: %s', fun, exc)
data['return'] = 'Exception occurred in wheel {0}: {1}: {2}'.format(
fun,
exc.__class__.__name__,
exc,
)
data['success'] = False
self.event.fire_event(data, tagify([jid, 'ret'], 'wheel'))
return {'tag': tag,
'data': data} | [
"def",
"wheel",
"(",
"self",
",",
"clear_load",
")",
":",
"# All wheel ops pass through eauth",
"auth_type",
",",
"err_name",
",",
"key",
",",
"sensitive_load_keys",
"=",
"self",
".",
"_prep_auth_info",
"(",
"clear_load",
")",
"# Authenticate",
"auth_check",
"=",
... | Send a master control function back to the wheel system | [
"Send",
"a",
"master",
"control",
"function",
"back",
"to",
"the",
"wheel",
"system"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L1949-L2018 | train |
saltstack/salt | salt/master.py | ClearFuncs.mk_token | def mk_token(self, clear_load):
'''
Create and return an authentication token, the clear load needs to
contain the eauth key and the needed authentication creds.
'''
token = self.loadauth.mk_token(clear_load)
if not token:
log.warning('Authentication failure of type "eauth" occurred.')
return ''
return token | python | def mk_token(self, clear_load):
'''
Create and return an authentication token, the clear load needs to
contain the eauth key and the needed authentication creds.
'''
token = self.loadauth.mk_token(clear_load)
if not token:
log.warning('Authentication failure of type "eauth" occurred.')
return ''
return token | [
"def",
"mk_token",
"(",
"self",
",",
"clear_load",
")",
":",
"token",
"=",
"self",
".",
"loadauth",
".",
"mk_token",
"(",
"clear_load",
")",
"if",
"not",
"token",
":",
"log",
".",
"warning",
"(",
"'Authentication failure of type \"eauth\" occurred.'",
")",
"re... | Create and return an authentication token, the clear load needs to
contain the eauth key and the needed authentication creds. | [
"Create",
"and",
"return",
"an",
"authentication",
"token",
"the",
"clear",
"load",
"needs",
"to",
"contain",
"the",
"eauth",
"key",
"and",
"the",
"needed",
"authentication",
"creds",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L2020-L2029 | train |
saltstack/salt | salt/master.py | ClearFuncs.publish | def publish(self, clear_load):
'''
This method sends out publications to the minions, it can only be used
by the LocalClient.
'''
extra = clear_load.get('kwargs', {})
publisher_acl = salt.acl.PublisherACL(self.opts['publisher_acl_blacklist'])
if publisher_acl.user_is_blacklisted(clear_load['user']) or \
publisher_acl.cmd_is_blacklisted(clear_load['fun']):
log.error(
'%s does not have permissions to run %s. Please contact '
'your local administrator if you believe this is in '
'error.\n', clear_load['user'], clear_load['fun']
)
return {'error': {'name': 'AuthorizationError',
'message': 'Authorization error occurred.'}}
# Retrieve the minions list
delimiter = clear_load.get('kwargs', {}).get('delimiter', DEFAULT_TARGET_DELIM)
_res = self.ckminions.check_minions(
clear_load['tgt'],
clear_load.get('tgt_type', 'glob'),
delimiter
)
minions = _res.get('minions', list())
missing = _res.get('missing', list())
ssh_minions = _res.get('ssh_minions', False)
# Check for external auth calls and authenticate
auth_type, err_name, key, sensitive_load_keys = self._prep_auth_info(extra)
if auth_type == 'user':
auth_check = self.loadauth.check_authentication(clear_load, auth_type, key=key)
else:
auth_check = self.loadauth.check_authentication(extra, auth_type)
# Setup authorization list variable and error information
auth_list = auth_check.get('auth_list', [])
err_msg = 'Authentication failure of type "{0}" occurred.'.format(auth_type)
if auth_check.get('error'):
# Authentication error occurred: do not continue.
log.warning(err_msg)
return {'error': {'name': 'AuthenticationError',
'message': 'Authentication error occurred.'}}
# All Token, Eauth, and non-root users must pass the authorization check
if auth_type != 'user' or (auth_type == 'user' and auth_list):
# Authorize the request
authorized = self.ckminions.auth_check(
auth_list,
clear_load['fun'],
clear_load['arg'],
clear_load['tgt'],
clear_load.get('tgt_type', 'glob'),
minions=minions,
# always accept find_job
whitelist=['saltutil.find_job'],
)
if not authorized:
# Authorization error occurred. Do not continue.
if auth_type == 'eauth' and not auth_list and 'username' in extra and 'eauth' in extra:
log.debug('Auth configuration for eauth "%s" and user "%s" is empty', extra['eauth'], extra['username'])
log.warning(err_msg)
return {'error': {'name': 'AuthorizationError',
'message': 'Authorization error occurred.'}}
# Perform some specific auth_type tasks after the authorization check
if auth_type == 'token':
username = auth_check.get('username')
clear_load['user'] = username
log.debug('Minion tokenized user = "%s"', username)
elif auth_type == 'eauth':
# The username we are attempting to auth with
clear_load['user'] = self.loadauth.load_name(extra)
# If we order masters (via a syndic), don't short circuit if no minions
# are found
if not self.opts.get('order_masters'):
# Check for no minions
if not minions:
return {
'enc': 'clear',
'load': {
'jid': None,
'minions': minions,
'error': 'Master could not resolve minions for target {0}'.format(clear_load['tgt'])
}
}
if extra.get('batch', None):
return self.publish_batch(clear_load, extra, minions, missing)
jid = self._prep_jid(clear_load, extra)
if jid is None:
return {'enc': 'clear',
'load': {'error': 'Master failed to assign jid'}}
payload = self._prep_pub(minions, jid, clear_load, extra, missing)
# Send it!
self._send_ssh_pub(payload, ssh_minions=ssh_minions)
self._send_pub(payload)
return {
'enc': 'clear',
'load': {
'jid': clear_load['jid'],
'minions': minions,
'missing': missing
}
} | python | def publish(self, clear_load):
'''
This method sends out publications to the minions, it can only be used
by the LocalClient.
'''
extra = clear_load.get('kwargs', {})
publisher_acl = salt.acl.PublisherACL(self.opts['publisher_acl_blacklist'])
if publisher_acl.user_is_blacklisted(clear_load['user']) or \
publisher_acl.cmd_is_blacklisted(clear_load['fun']):
log.error(
'%s does not have permissions to run %s. Please contact '
'your local administrator if you believe this is in '
'error.\n', clear_load['user'], clear_load['fun']
)
return {'error': {'name': 'AuthorizationError',
'message': 'Authorization error occurred.'}}
# Retrieve the minions list
delimiter = clear_load.get('kwargs', {}).get('delimiter', DEFAULT_TARGET_DELIM)
_res = self.ckminions.check_minions(
clear_load['tgt'],
clear_load.get('tgt_type', 'glob'),
delimiter
)
minions = _res.get('minions', list())
missing = _res.get('missing', list())
ssh_minions = _res.get('ssh_minions', False)
# Check for external auth calls and authenticate
auth_type, err_name, key, sensitive_load_keys = self._prep_auth_info(extra)
if auth_type == 'user':
auth_check = self.loadauth.check_authentication(clear_load, auth_type, key=key)
else:
auth_check = self.loadauth.check_authentication(extra, auth_type)
# Setup authorization list variable and error information
auth_list = auth_check.get('auth_list', [])
err_msg = 'Authentication failure of type "{0}" occurred.'.format(auth_type)
if auth_check.get('error'):
# Authentication error occurred: do not continue.
log.warning(err_msg)
return {'error': {'name': 'AuthenticationError',
'message': 'Authentication error occurred.'}}
# All Token, Eauth, and non-root users must pass the authorization check
if auth_type != 'user' or (auth_type == 'user' and auth_list):
# Authorize the request
authorized = self.ckminions.auth_check(
auth_list,
clear_load['fun'],
clear_load['arg'],
clear_load['tgt'],
clear_load.get('tgt_type', 'glob'),
minions=minions,
# always accept find_job
whitelist=['saltutil.find_job'],
)
if not authorized:
# Authorization error occurred. Do not continue.
if auth_type == 'eauth' and not auth_list and 'username' in extra and 'eauth' in extra:
log.debug('Auth configuration for eauth "%s" and user "%s" is empty', extra['eauth'], extra['username'])
log.warning(err_msg)
return {'error': {'name': 'AuthorizationError',
'message': 'Authorization error occurred.'}}
# Perform some specific auth_type tasks after the authorization check
if auth_type == 'token':
username = auth_check.get('username')
clear_load['user'] = username
log.debug('Minion tokenized user = "%s"', username)
elif auth_type == 'eauth':
# The username we are attempting to auth with
clear_load['user'] = self.loadauth.load_name(extra)
# If we order masters (via a syndic), don't short circuit if no minions
# are found
if not self.opts.get('order_masters'):
# Check for no minions
if not minions:
return {
'enc': 'clear',
'load': {
'jid': None,
'minions': minions,
'error': 'Master could not resolve minions for target {0}'.format(clear_load['tgt'])
}
}
if extra.get('batch', None):
return self.publish_batch(clear_load, extra, minions, missing)
jid = self._prep_jid(clear_load, extra)
if jid is None:
return {'enc': 'clear',
'load': {'error': 'Master failed to assign jid'}}
payload = self._prep_pub(minions, jid, clear_load, extra, missing)
# Send it!
self._send_ssh_pub(payload, ssh_minions=ssh_minions)
self._send_pub(payload)
return {
'enc': 'clear',
'load': {
'jid': clear_load['jid'],
'minions': minions,
'missing': missing
}
} | [
"def",
"publish",
"(",
"self",
",",
"clear_load",
")",
":",
"extra",
"=",
"clear_load",
".",
"get",
"(",
"'kwargs'",
",",
"{",
"}",
")",
"publisher_acl",
"=",
"salt",
".",
"acl",
".",
"PublisherACL",
"(",
"self",
".",
"opts",
"[",
"'publisher_acl_blackli... | This method sends out publications to the minions, it can only be used
by the LocalClient. | [
"This",
"method",
"sends",
"out",
"publications",
"to",
"the",
"minions",
"it",
"can",
"only",
"be",
"used",
"by",
"the",
"LocalClient",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L2063-L2174 | train |
saltstack/salt | salt/master.py | ClearFuncs._prep_jid | def _prep_jid(self, clear_load, extra):
'''
Return a jid for this publication
'''
# the jid in clear_load can be None, '', or something else. this is an
# attempt to clean up the value before passing to plugins
passed_jid = clear_load['jid'] if clear_load.get('jid') else None
nocache = extra.get('nocache', False)
# Retrieve the jid
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
try:
# Retrieve the jid
jid = self.mminion.returners[fstr](nocache=nocache,
passed_jid=passed_jid)
except (KeyError, TypeError):
# The returner is not present
msg = (
'Failed to allocate a jid. The requested returner \'{0}\' '
'could not be loaded.'.format(fstr.split('.')[0])
)
log.error(msg)
return {'error': msg}
return jid | python | def _prep_jid(self, clear_load, extra):
'''
Return a jid for this publication
'''
# the jid in clear_load can be None, '', or something else. this is an
# attempt to clean up the value before passing to plugins
passed_jid = clear_load['jid'] if clear_load.get('jid') else None
nocache = extra.get('nocache', False)
# Retrieve the jid
fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
try:
# Retrieve the jid
jid = self.mminion.returners[fstr](nocache=nocache,
passed_jid=passed_jid)
except (KeyError, TypeError):
# The returner is not present
msg = (
'Failed to allocate a jid. The requested returner \'{0}\' '
'could not be loaded.'.format(fstr.split('.')[0])
)
log.error(msg)
return {'error': msg}
return jid | [
"def",
"_prep_jid",
"(",
"self",
",",
"clear_load",
",",
"extra",
")",
":",
"# the jid in clear_load can be None, '', or something else. this is an",
"# attempt to clean up the value before passing to plugins",
"passed_jid",
"=",
"clear_load",
"[",
"'jid'",
"]",
"if",
"clear_lo... | Return a jid for this publication | [
"Return",
"a",
"jid",
"for",
"this",
"publication"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L2194-L2217 | train |
saltstack/salt | salt/master.py | ClearFuncs._send_pub | def _send_pub(self, load):
'''
Take a load and send it across the network to connected minions
'''
for transport, opts in iter_transport_opts(self.opts):
chan = salt.transport.server.PubServerChannel.factory(opts)
chan.publish(load) | python | def _send_pub(self, load):
'''
Take a load and send it across the network to connected minions
'''
for transport, opts in iter_transport_opts(self.opts):
chan = salt.transport.server.PubServerChannel.factory(opts)
chan.publish(load) | [
"def",
"_send_pub",
"(",
"self",
",",
"load",
")",
":",
"for",
"transport",
",",
"opts",
"in",
"iter_transport_opts",
"(",
"self",
".",
"opts",
")",
":",
"chan",
"=",
"salt",
".",
"transport",
".",
"server",
".",
"PubServerChannel",
".",
"factory",
"(",
... | Take a load and send it across the network to connected minions | [
"Take",
"a",
"load",
"and",
"send",
"it",
"across",
"the",
"network",
"to",
"connected",
"minions"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L2219-L2225 | train |
saltstack/salt | salt/master.py | ClearFuncs._send_ssh_pub | def _send_ssh_pub(self, load, ssh_minions=False):
'''
Take a load and send it across the network to ssh minions
'''
if self.opts['enable_ssh_minions'] is True and ssh_minions is True:
log.debug('Send payload to ssh minions')
threading.Thread(target=self.ssh_client.cmd, kwargs=load).start() | python | def _send_ssh_pub(self, load, ssh_minions=False):
'''
Take a load and send it across the network to ssh minions
'''
if self.opts['enable_ssh_minions'] is True and ssh_minions is True:
log.debug('Send payload to ssh minions')
threading.Thread(target=self.ssh_client.cmd, kwargs=load).start() | [
"def",
"_send_ssh_pub",
"(",
"self",
",",
"load",
",",
"ssh_minions",
"=",
"False",
")",
":",
"if",
"self",
".",
"opts",
"[",
"'enable_ssh_minions'",
"]",
"is",
"True",
"and",
"ssh_minions",
"is",
"True",
":",
"log",
".",
"debug",
"(",
"'Send payload to ss... | Take a load and send it across the network to ssh minions | [
"Take",
"a",
"load",
"and",
"send",
"it",
"across",
"the",
"network",
"to",
"ssh",
"minions"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L2233-L2239 | train |
saltstack/salt | salt/master.py | ClearFuncs._prep_pub | def _prep_pub(self, minions, jid, clear_load, extra, missing):
'''
Take a given load and perform the necessary steps
to prepare a publication.
TODO: This is really only bound by temporal cohesion
and thus should be refactored even further.
'''
clear_load['jid'] = jid
delimiter = clear_load.get('kwargs', {}).get('delimiter', DEFAULT_TARGET_DELIM)
# TODO Error reporting over the master event bus
self.event.fire_event({'minions': minions}, clear_load['jid'])
new_job_load = {
'jid': clear_load['jid'],
'tgt_type': clear_load['tgt_type'],
'tgt': clear_load['tgt'],
'user': clear_load['user'],
'fun': clear_load['fun'],
'arg': clear_load['arg'],
'minions': minions,
'missing': missing,
}
# Announce the job on the event bus
self.event.fire_event(new_job_load, tagify([clear_load['jid'], 'new'], 'job'))
if self.opts['ext_job_cache']:
fstr = '{0}.save_load'.format(self.opts['ext_job_cache'])
save_load_func = True
# Get the returner's save_load arg_spec.
try:
arg_spec = salt.utils.args.get_function_argspec(self.mminion.returners[fstr])
# Check if 'minions' is included in returner's save_load arg_spec.
# This may be missing in custom returners, which we should warn about.
if 'minions' not in arg_spec.args:
log.critical(
'The specified returner used for the external job cache '
'\'%s\' does not have a \'minions\' kwarg in the returner\'s '
'save_load function.', self.opts['ext_job_cache']
)
except (AttributeError, KeyError):
save_load_func = False
log.critical(
'The specified returner used for the external job cache '
'"%s" does not have a save_load function!',
self.opts['ext_job_cache']
)
if save_load_func:
try:
self.mminion.returners[fstr](clear_load['jid'], clear_load, minions=minions)
except Exception:
log.critical(
'The specified returner threw a stack trace:\n',
exc_info=True
)
# always write out to the master job caches
try:
fstr = '{0}.save_load'.format(self.opts['master_job_cache'])
self.mminion.returners[fstr](clear_load['jid'], clear_load, minions)
except KeyError:
log.critical(
'The specified returner used for the master job cache '
'"%s" does not have a save_load function!',
self.opts['master_job_cache']
)
except Exception:
log.critical(
'The specified returner threw a stack trace:\n',
exc_info=True
)
# Set up the payload
payload = {'enc': 'aes'}
# Altering the contents of the publish load is serious!! Changes here
# break compatibility with minion/master versions and even tiny
# additions can have serious implications on the performance of the
# publish commands.
#
# In short, check with Thomas Hatch before you even think about
# touching this stuff, we can probably do what you want to do another
# way that won't have a negative impact.
load = {
'fun': clear_load['fun'],
'arg': clear_load['arg'],
'tgt': clear_load['tgt'],
'jid': clear_load['jid'],
'ret': clear_load['ret'],
}
# if you specified a master id, lets put that in the load
if 'master_id' in self.opts:
load['master_id'] = self.opts['master_id']
# if someone passed us one, use that
if 'master_id' in extra:
load['master_id'] = extra['master_id']
# Only add the delimiter to the pub data if it is non-default
if delimiter != DEFAULT_TARGET_DELIM:
load['delimiter'] = delimiter
if 'id' in extra:
load['id'] = extra['id']
if 'tgt_type' in clear_load:
load['tgt_type'] = clear_load['tgt_type']
if 'to' in clear_load:
load['to'] = clear_load['to']
if 'kwargs' in clear_load:
if 'ret_config' in clear_load['kwargs']:
load['ret_config'] = clear_load['kwargs'].get('ret_config')
if 'metadata' in clear_load['kwargs']:
load['metadata'] = clear_load['kwargs'].get('metadata')
if 'module_executors' in clear_load['kwargs']:
load['module_executors'] = clear_load['kwargs'].get('module_executors')
if 'executor_opts' in clear_load['kwargs']:
load['executor_opts'] = clear_load['kwargs'].get('executor_opts')
if 'ret_kwargs' in clear_load['kwargs']:
load['ret_kwargs'] = clear_load['kwargs'].get('ret_kwargs')
if 'user' in clear_load:
log.info(
'User %s Published command %s with jid %s',
clear_load['user'], clear_load['fun'], clear_load['jid']
)
load['user'] = clear_load['user']
else:
log.info(
'Published command %s with jid %s',
clear_load['fun'], clear_load['jid']
)
log.debug('Published command details %s', load)
return load | python | def _prep_pub(self, minions, jid, clear_load, extra, missing):
'''
Take a given load and perform the necessary steps
to prepare a publication.
TODO: This is really only bound by temporal cohesion
and thus should be refactored even further.
'''
clear_load['jid'] = jid
delimiter = clear_load.get('kwargs', {}).get('delimiter', DEFAULT_TARGET_DELIM)
# TODO Error reporting over the master event bus
self.event.fire_event({'minions': minions}, clear_load['jid'])
new_job_load = {
'jid': clear_load['jid'],
'tgt_type': clear_load['tgt_type'],
'tgt': clear_load['tgt'],
'user': clear_load['user'],
'fun': clear_load['fun'],
'arg': clear_load['arg'],
'minions': minions,
'missing': missing,
}
# Announce the job on the event bus
self.event.fire_event(new_job_load, tagify([clear_load['jid'], 'new'], 'job'))
if self.opts['ext_job_cache']:
fstr = '{0}.save_load'.format(self.opts['ext_job_cache'])
save_load_func = True
# Get the returner's save_load arg_spec.
try:
arg_spec = salt.utils.args.get_function_argspec(self.mminion.returners[fstr])
# Check if 'minions' is included in returner's save_load arg_spec.
# This may be missing in custom returners, which we should warn about.
if 'minions' not in arg_spec.args:
log.critical(
'The specified returner used for the external job cache '
'\'%s\' does not have a \'minions\' kwarg in the returner\'s '
'save_load function.', self.opts['ext_job_cache']
)
except (AttributeError, KeyError):
save_load_func = False
log.critical(
'The specified returner used for the external job cache '
'"%s" does not have a save_load function!',
self.opts['ext_job_cache']
)
if save_load_func:
try:
self.mminion.returners[fstr](clear_load['jid'], clear_load, minions=minions)
except Exception:
log.critical(
'The specified returner threw a stack trace:\n',
exc_info=True
)
# always write out to the master job caches
try:
fstr = '{0}.save_load'.format(self.opts['master_job_cache'])
self.mminion.returners[fstr](clear_load['jid'], clear_load, minions)
except KeyError:
log.critical(
'The specified returner used for the master job cache '
'"%s" does not have a save_load function!',
self.opts['master_job_cache']
)
except Exception:
log.critical(
'The specified returner threw a stack trace:\n',
exc_info=True
)
# Set up the payload
payload = {'enc': 'aes'}
# Altering the contents of the publish load is serious!! Changes here
# break compatibility with minion/master versions and even tiny
# additions can have serious implications on the performance of the
# publish commands.
#
# In short, check with Thomas Hatch before you even think about
# touching this stuff, we can probably do what you want to do another
# way that won't have a negative impact.
load = {
'fun': clear_load['fun'],
'arg': clear_load['arg'],
'tgt': clear_load['tgt'],
'jid': clear_load['jid'],
'ret': clear_load['ret'],
}
# if you specified a master id, lets put that in the load
if 'master_id' in self.opts:
load['master_id'] = self.opts['master_id']
# if someone passed us one, use that
if 'master_id' in extra:
load['master_id'] = extra['master_id']
# Only add the delimiter to the pub data if it is non-default
if delimiter != DEFAULT_TARGET_DELIM:
load['delimiter'] = delimiter
if 'id' in extra:
load['id'] = extra['id']
if 'tgt_type' in clear_load:
load['tgt_type'] = clear_load['tgt_type']
if 'to' in clear_load:
load['to'] = clear_load['to']
if 'kwargs' in clear_load:
if 'ret_config' in clear_load['kwargs']:
load['ret_config'] = clear_load['kwargs'].get('ret_config')
if 'metadata' in clear_load['kwargs']:
load['metadata'] = clear_load['kwargs'].get('metadata')
if 'module_executors' in clear_load['kwargs']:
load['module_executors'] = clear_load['kwargs'].get('module_executors')
if 'executor_opts' in clear_load['kwargs']:
load['executor_opts'] = clear_load['kwargs'].get('executor_opts')
if 'ret_kwargs' in clear_load['kwargs']:
load['ret_kwargs'] = clear_load['kwargs'].get('ret_kwargs')
if 'user' in clear_load:
log.info(
'User %s Published command %s with jid %s',
clear_load['user'], clear_load['fun'], clear_load['jid']
)
load['user'] = clear_load['user']
else:
log.info(
'Published command %s with jid %s',
clear_load['fun'], clear_load['jid']
)
log.debug('Published command details %s', load)
return load | [
"def",
"_prep_pub",
"(",
"self",
",",
"minions",
",",
"jid",
",",
"clear_load",
",",
"extra",
",",
"missing",
")",
":",
"clear_load",
"[",
"'jid'",
"]",
"=",
"jid",
"delimiter",
"=",
"clear_load",
".",
"get",
"(",
"'kwargs'",
",",
"{",
"}",
")",
".",... | Take a given load and perform the necessary steps
to prepare a publication.
TODO: This is really only bound by temporal cohesion
and thus should be refactored even further. | [
"Take",
"a",
"given",
"load",
"and",
"perform",
"the",
"necessary",
"steps",
"to",
"prepare",
"a",
"publication",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/master.py#L2241-L2378 | train |
saltstack/salt | salt/states/sqlite3.py | row_absent | def row_absent(name, db, table, where_sql, where_args=None):
'''
Makes sure the specified row is absent in db. If multiple rows
match where_sql, then the state will fail.
name
Only used as the unique ID
db
The database file name
table
The table name to check
where_sql
The sql to select the row to check
where_args
The list parameters to substitute in where_sql
'''
changes = {'name': name,
'changes': {},
'result': None,
'comment': ''}
conn = None
try:
conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES)
conn.row_factory = _dict_factory
rows = None
if where_args is None:
rows = _query(conn,
"SELECT * FROM `" + table + "` WHERE " + where_sql)
else:
rows = _query(conn,
"SELECT * FROM `" + table + "` WHERE " + where_sql,
where_args)
if len(rows) > 1:
changes['result'] = False
changes['comment'] = "More than one row matched the specified query"
elif len(rows) == 1:
if __opts__['test']:
changes['result'] = True
changes['comment'] = "Row will be removed in " + table
changes['changes']['old'] = rows[0]
else:
if where_args is None:
cursor = conn.execute("DELETE FROM `" +
table + "` WHERE " + where_sql)
else:
cursor = conn.execute("DELETE FROM `" +
table + "` WHERE " + where_sql,
where_args)
conn.commit()
if cursor.rowcount == 1:
changes['result'] = True
changes['comment'] = "Row removed"
changes['changes']['old'] = rows[0]
else:
changes['result'] = False
changes['comment'] = "Unable to remove row"
else:
changes['result'] = True
changes['comment'] = 'Row is absent'
except Exception as e:
changes['result'] = False
changes['comment'] = six.text_type(e)
finally:
if conn:
conn.close()
return changes | python | def row_absent(name, db, table, where_sql, where_args=None):
'''
Makes sure the specified row is absent in db. If multiple rows
match where_sql, then the state will fail.
name
Only used as the unique ID
db
The database file name
table
The table name to check
where_sql
The sql to select the row to check
where_args
The list parameters to substitute in where_sql
'''
changes = {'name': name,
'changes': {},
'result': None,
'comment': ''}
conn = None
try:
conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES)
conn.row_factory = _dict_factory
rows = None
if where_args is None:
rows = _query(conn,
"SELECT * FROM `" + table + "` WHERE " + where_sql)
else:
rows = _query(conn,
"SELECT * FROM `" + table + "` WHERE " + where_sql,
where_args)
if len(rows) > 1:
changes['result'] = False
changes['comment'] = "More than one row matched the specified query"
elif len(rows) == 1:
if __opts__['test']:
changes['result'] = True
changes['comment'] = "Row will be removed in " + table
changes['changes']['old'] = rows[0]
else:
if where_args is None:
cursor = conn.execute("DELETE FROM `" +
table + "` WHERE " + where_sql)
else:
cursor = conn.execute("DELETE FROM `" +
table + "` WHERE " + where_sql,
where_args)
conn.commit()
if cursor.rowcount == 1:
changes['result'] = True
changes['comment'] = "Row removed"
changes['changes']['old'] = rows[0]
else:
changes['result'] = False
changes['comment'] = "Unable to remove row"
else:
changes['result'] = True
changes['comment'] = 'Row is absent'
except Exception as e:
changes['result'] = False
changes['comment'] = six.text_type(e)
finally:
if conn:
conn.close()
return changes | [
"def",
"row_absent",
"(",
"name",
",",
"db",
",",
"table",
",",
"where_sql",
",",
"where_args",
"=",
"None",
")",
":",
"changes",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
... | Makes sure the specified row is absent in db. If multiple rows
match where_sql, then the state will fail.
name
Only used as the unique ID
db
The database file name
table
The table name to check
where_sql
The sql to select the row to check
where_args
The list parameters to substitute in where_sql | [
"Makes",
"sure",
"the",
"specified",
"row",
"is",
"absent",
"in",
"db",
".",
"If",
"multiple",
"rows",
"match",
"where_sql",
"then",
"the",
"state",
"will",
"fail",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/sqlite3.py#L117-L191 | train |
saltstack/salt | salt/states/sqlite3.py | row_present | def row_present(name,
db,
table,
data,
where_sql,
where_args=None,
update=False):
'''
Checks to make sure the given row exists. If row exists and update is True
then row will be updated with data. Otherwise it will leave existing
row unmodified and check it against data. If the existing data
doesn't match data_check the state will fail. If the row doesn't
exist then it will insert data into the table. If more than one
row matches, then the state will fail.
name
Only used as the unique ID
db
The database file name
table
The table name to check the data
data
The dictionary of key/value pairs to check against if
row exists, insert into the table if it doesn't
where_sql
The sql to select the row to check
where_args
The list parameters to substitute in where_sql
update
True will replace the existing row with data
When False and the row exists and data does not equal
the row data then the state will fail
'''
changes = {'name': name,
'changes': {},
'result': None,
'comment': ''}
conn = None
try:
conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES)
conn.row_factory = _dict_factory
rows = None
if where_args is None:
rows = _query(conn, "SELECT * FROM `" +
table + "` WHERE " + where_sql)
else:
rows = _query(conn, "SELECT * FROM `" +
table + "` WHERE " + where_sql,
where_args)
if len(rows) > 1:
changes['result'] = False
changes['comment'] = 'More than one row matched the specified query'
elif len(rows) == 1:
for key, value in six.iteritems(data):
if key in rows[0] and rows[0][key] != value:
if update:
if __opts__['test']:
changes['result'] = True
changes['comment'] = "Row will be update in " + table
else:
columns = []
params = []
for key, value in six.iteritems(data):
columns.append("`" + key + "`=?")
params.append(value)
if where_args is not None:
params += where_args
sql = "UPDATE `" + table + "` SET "
sql += ",".join(columns)
sql += " WHERE "
sql += where_sql
cursor = conn.execute(sql, params)
conn.commit()
if cursor.rowcount == 1:
changes['result'] = True
changes['comment'] = "Row updated"
changes['changes']['old'] = rows[0]
changes['changes']['new'] = data
else:
changes['result'] = False
changes['comment'] = "Row update failed"
else:
changes['result'] = False
changes['comment'] = "Existing data does" + \
"not match desired state"
break
if changes['result'] is None:
changes['result'] = True
changes['comment'] = "Row exists"
else:
if __opts__['test']:
changes['result'] = True
changes['changes']['new'] = data
changes['comment'] = "Row will be inserted into " + table
else:
columns = []
value_stmt = []
values = []
for key, value in six.iteritems(data):
value_stmt.append('?')
values.append(value)
columns.append("`" + key + "`")
sql = "INSERT INTO `" + table + "` ("
sql += ",".join(columns)
sql += ") VALUES ("
sql += ",".join(value_stmt)
sql += ")"
cursor = conn.execute(sql, values)
conn.commit()
if cursor.rowcount == 1:
changes['result'] = True
changes['changes']['new'] = data
changes['comment'] = 'Inserted row'
else:
changes['result'] = False
changes['comment'] = "Unable to insert data"
except Exception as e:
changes['result'] = False
changes['comment'] = six.text_type(e)
finally:
if conn:
conn.close()
return changes | python | def row_present(name,
db,
table,
data,
where_sql,
where_args=None,
update=False):
'''
Checks to make sure the given row exists. If row exists and update is True
then row will be updated with data. Otherwise it will leave existing
row unmodified and check it against data. If the existing data
doesn't match data_check the state will fail. If the row doesn't
exist then it will insert data into the table. If more than one
row matches, then the state will fail.
name
Only used as the unique ID
db
The database file name
table
The table name to check the data
data
The dictionary of key/value pairs to check against if
row exists, insert into the table if it doesn't
where_sql
The sql to select the row to check
where_args
The list parameters to substitute in where_sql
update
True will replace the existing row with data
When False and the row exists and data does not equal
the row data then the state will fail
'''
changes = {'name': name,
'changes': {},
'result': None,
'comment': ''}
conn = None
try:
conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES)
conn.row_factory = _dict_factory
rows = None
if where_args is None:
rows = _query(conn, "SELECT * FROM `" +
table + "` WHERE " + where_sql)
else:
rows = _query(conn, "SELECT * FROM `" +
table + "` WHERE " + where_sql,
where_args)
if len(rows) > 1:
changes['result'] = False
changes['comment'] = 'More than one row matched the specified query'
elif len(rows) == 1:
for key, value in six.iteritems(data):
if key in rows[0] and rows[0][key] != value:
if update:
if __opts__['test']:
changes['result'] = True
changes['comment'] = "Row will be update in " + table
else:
columns = []
params = []
for key, value in six.iteritems(data):
columns.append("`" + key + "`=?")
params.append(value)
if where_args is not None:
params += where_args
sql = "UPDATE `" + table + "` SET "
sql += ",".join(columns)
sql += " WHERE "
sql += where_sql
cursor = conn.execute(sql, params)
conn.commit()
if cursor.rowcount == 1:
changes['result'] = True
changes['comment'] = "Row updated"
changes['changes']['old'] = rows[0]
changes['changes']['new'] = data
else:
changes['result'] = False
changes['comment'] = "Row update failed"
else:
changes['result'] = False
changes['comment'] = "Existing data does" + \
"not match desired state"
break
if changes['result'] is None:
changes['result'] = True
changes['comment'] = "Row exists"
else:
if __opts__['test']:
changes['result'] = True
changes['changes']['new'] = data
changes['comment'] = "Row will be inserted into " + table
else:
columns = []
value_stmt = []
values = []
for key, value in six.iteritems(data):
value_stmt.append('?')
values.append(value)
columns.append("`" + key + "`")
sql = "INSERT INTO `" + table + "` ("
sql += ",".join(columns)
sql += ") VALUES ("
sql += ",".join(value_stmt)
sql += ")"
cursor = conn.execute(sql, values)
conn.commit()
if cursor.rowcount == 1:
changes['result'] = True
changes['changes']['new'] = data
changes['comment'] = 'Inserted row'
else:
changes['result'] = False
changes['comment'] = "Unable to insert data"
except Exception as e:
changes['result'] = False
changes['comment'] = six.text_type(e)
finally:
if conn:
conn.close()
return changes | [
"def",
"row_present",
"(",
"name",
",",
"db",
",",
"table",
",",
"data",
",",
"where_sql",
",",
"where_args",
"=",
"None",
",",
"update",
"=",
"False",
")",
":",
"changes",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'re... | Checks to make sure the given row exists. If row exists and update is True
then row will be updated with data. Otherwise it will leave existing
row unmodified and check it against data. If the existing data
doesn't match data_check the state will fail. If the row doesn't
exist then it will insert data into the table. If more than one
row matches, then the state will fail.
name
Only used as the unique ID
db
The database file name
table
The table name to check the data
data
The dictionary of key/value pairs to check against if
row exists, insert into the table if it doesn't
where_sql
The sql to select the row to check
where_args
The list parameters to substitute in where_sql
update
True will replace the existing row with data
When False and the row exists and data does not equal
the row data then the state will fail | [
"Checks",
"to",
"make",
"sure",
"the",
"given",
"row",
"exists",
".",
"If",
"row",
"exists",
"and",
"update",
"is",
"True",
"then",
"row",
"will",
"be",
"updated",
"with",
"data",
".",
"Otherwise",
"it",
"will",
"leave",
"existing",
"row",
"unmodified",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/sqlite3.py#L194-L331 | train |
saltstack/salt | salt/states/sqlite3.py | table_absent | def table_absent(name, db):
'''
Make sure the specified table does not exist
name
The name of the table
db
The name of the database file
'''
changes = {'name': name,
'changes': {},
'result': None,
'comment': ''}
conn = None
try:
conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES)
tables = _query(conn, "SELECT sql FROM sqlite_master " +
" WHERE type='table' AND name=?", [name])
if len(tables) == 1:
if __opts__['test']:
changes['result'] = True
changes['comment'] = "'" + name + "' will be dropped"
else:
conn.execute("DROP TABLE " + name)
conn.commit()
changes['changes']['old'] = tables[0][0]
changes['result'] = True
changes['comment'] = "'" + name + "' was dropped"
elif not tables:
changes['result'] = True
changes['comment'] = "'" + name + "' is already absent"
else:
changes['result'] = False
changes['comment'] = "Multiple tables with the same name='" + \
name + "'"
except Exception as e:
changes['result'] = False
changes['comment'] = six.text_type(e)
finally:
if conn:
conn.close()
return changes | python | def table_absent(name, db):
'''
Make sure the specified table does not exist
name
The name of the table
db
The name of the database file
'''
changes = {'name': name,
'changes': {},
'result': None,
'comment': ''}
conn = None
try:
conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES)
tables = _query(conn, "SELECT sql FROM sqlite_master " +
" WHERE type='table' AND name=?", [name])
if len(tables) == 1:
if __opts__['test']:
changes['result'] = True
changes['comment'] = "'" + name + "' will be dropped"
else:
conn.execute("DROP TABLE " + name)
conn.commit()
changes['changes']['old'] = tables[0][0]
changes['result'] = True
changes['comment'] = "'" + name + "' was dropped"
elif not tables:
changes['result'] = True
changes['comment'] = "'" + name + "' is already absent"
else:
changes['result'] = False
changes['comment'] = "Multiple tables with the same name='" + \
name + "'"
except Exception as e:
changes['result'] = False
changes['comment'] = six.text_type(e)
finally:
if conn:
conn.close()
return changes | [
"def",
"table_absent",
"(",
"name",
",",
"db",
")",
":",
"changes",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"conn",
"=",
"None",
"try",
":",
"conn",
"=",
"s... | Make sure the specified table does not exist
name
The name of the table
db
The name of the database file | [
"Make",
"sure",
"the",
"specified",
"table",
"does",
"not",
"exist"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/sqlite3.py#L334-L380 | train |
saltstack/salt | salt/states/sqlite3.py | table_present | def table_present(name, db, schema, force=False):
'''
Make sure the specified table exists with the specified schema
name
The name of the table
db
The name of the database file
schema
The dictionary containing the schema information
force
If the name of the table exists and force is set to False,
the state will fail. If force is set to True, the existing
table will be replaced with the new table
'''
changes = {'name': name,
'changes': {},
'result': None,
'comment': ''}
conn = None
try:
conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES)
tables = _query(conn,
"SELECT sql FROM sqlite_master " +
"WHERE type='table' AND name=?", [name])
if len(tables) == 1:
sql = None
if isinstance(schema, six.string_types):
sql = schema.strip()
else:
sql = _get_sql_from_schema(name, schema)
if sql != tables[0][0]:
if force:
if __opts__['test']:
changes['result'] = True
changes['changes']['old'] = tables[0][0]
changes['changes']['new'] = sql
changes['comment'] = "'" + name + "' will be replaced"
else:
conn.execute("DROP TABLE `" + name + "`")
conn.execute(sql)
conn.commit()
changes['result'] = True
changes['changes']['old'] = tables[0][0]
changes['changes']['new'] = sql
changes['comment'] = "Replaced '" + name + "'"
else:
changes['result'] = False
changes['comment'] = "Expected schema=" + sql + \
"\nactual schema=" + tables[0][0]
else:
changes['result'] = True
changes['comment'] = "'" + name + \
"' exists with matching schema"
elif not tables:
# Create the table
sql = None
if isinstance(schema, six.string_types):
sql = schema
else:
sql = _get_sql_from_schema(name, schema)
if __opts__['test']:
changes['result'] = True
changes['changes']['new'] = sql
changes['comment'] = "'" + name + "' will be created"
else:
conn.execute(sql)
conn.commit()
changes['result'] = True
changes['changes']['new'] = sql
changes['comment'] = "Created table '" + name + "'"
else:
changes['result'] = False
changes['comment'] = 'Multiple tables with the same name=' + name
except Exception as e:
changes['result'] = False
changes['comment'] = str(e)
finally:
if conn:
conn.close()
return changes | python | def table_present(name, db, schema, force=False):
'''
Make sure the specified table exists with the specified schema
name
The name of the table
db
The name of the database file
schema
The dictionary containing the schema information
force
If the name of the table exists and force is set to False,
the state will fail. If force is set to True, the existing
table will be replaced with the new table
'''
changes = {'name': name,
'changes': {},
'result': None,
'comment': ''}
conn = None
try:
conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES)
tables = _query(conn,
"SELECT sql FROM sqlite_master " +
"WHERE type='table' AND name=?", [name])
if len(tables) == 1:
sql = None
if isinstance(schema, six.string_types):
sql = schema.strip()
else:
sql = _get_sql_from_schema(name, schema)
if sql != tables[0][0]:
if force:
if __opts__['test']:
changes['result'] = True
changes['changes']['old'] = tables[0][0]
changes['changes']['new'] = sql
changes['comment'] = "'" + name + "' will be replaced"
else:
conn.execute("DROP TABLE `" + name + "`")
conn.execute(sql)
conn.commit()
changes['result'] = True
changes['changes']['old'] = tables[0][0]
changes['changes']['new'] = sql
changes['comment'] = "Replaced '" + name + "'"
else:
changes['result'] = False
changes['comment'] = "Expected schema=" + sql + \
"\nactual schema=" + tables[0][0]
else:
changes['result'] = True
changes['comment'] = "'" + name + \
"' exists with matching schema"
elif not tables:
# Create the table
sql = None
if isinstance(schema, six.string_types):
sql = schema
else:
sql = _get_sql_from_schema(name, schema)
if __opts__['test']:
changes['result'] = True
changes['changes']['new'] = sql
changes['comment'] = "'" + name + "' will be created"
else:
conn.execute(sql)
conn.commit()
changes['result'] = True
changes['changes']['new'] = sql
changes['comment'] = "Created table '" + name + "'"
else:
changes['result'] = False
changes['comment'] = 'Multiple tables with the same name=' + name
except Exception as e:
changes['result'] = False
changes['comment'] = str(e)
finally:
if conn:
conn.close()
return changes | [
"def",
"table_present",
"(",
"name",
",",
"db",
",",
"schema",
",",
"force",
"=",
"False",
")",
":",
"changes",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"conn"... | Make sure the specified table exists with the specified schema
name
The name of the table
db
The name of the database file
schema
The dictionary containing the schema information
force
If the name of the table exists and force is set to False,
the state will fail. If force is set to True, the existing
table will be replaced with the new table | [
"Make",
"sure",
"the",
"specified",
"table",
"exists",
"with",
"the",
"specified",
"schema"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/sqlite3.py#L383-L471 | train |
saltstack/salt | salt/matchers/range_match.py | match | def match(tgt, opts=None):
'''
Matches based on range cluster
'''
if not opts:
opts = __opts__
if HAS_RANGE:
range_ = seco.range.Range(opts['range_server'])
try:
return opts['grains']['fqdn'] in range_.expand(tgt)
except seco.range.RangeException as exc:
log.debug('Range exception in compound match: %s', exc)
return False
return False | python | def match(tgt, opts=None):
'''
Matches based on range cluster
'''
if not opts:
opts = __opts__
if HAS_RANGE:
range_ = seco.range.Range(opts['range_server'])
try:
return opts['grains']['fqdn'] in range_.expand(tgt)
except seco.range.RangeException as exc:
log.debug('Range exception in compound match: %s', exc)
return False
return False | [
"def",
"match",
"(",
"tgt",
",",
"opts",
"=",
"None",
")",
":",
"if",
"not",
"opts",
":",
"opts",
"=",
"__opts__",
"if",
"HAS_RANGE",
":",
"range_",
"=",
"seco",
".",
"range",
".",
"Range",
"(",
"opts",
"[",
"'range_server'",
"]",
")",
"try",
":",
... | Matches based on range cluster | [
"Matches",
"based",
"on",
"range",
"cluster"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/matchers/range_match.py#L19-L32 | train |
saltstack/salt | salt/returners/cassandra_return.py | returner | def returner(ret):
'''
Return data to a Cassandra ColumnFamily
'''
consistency_level = getattr(pycassa.ConsistencyLevel,
__opts__['cassandra.consistency_level'])
pool = pycassa.ConnectionPool(__opts__['cassandra.keyspace'],
__opts__['cassandra.servers'])
ccf = pycassa.ColumnFamily(pool, __opts__['cassandra.column_family'],
write_consistency_level=consistency_level)
columns = {'fun': ret['fun'],
'id': ret['id']}
if isinstance(ret['return'], dict):
for key, value in six.iteritems(ret['return']):
columns['return.{0}'.format(key)] = six.text_type(value)
else:
columns['return'] = six.text_type(ret['return'])
log.debug(columns)
ccf.insert(ret['jid'], columns) | python | def returner(ret):
'''
Return data to a Cassandra ColumnFamily
'''
consistency_level = getattr(pycassa.ConsistencyLevel,
__opts__['cassandra.consistency_level'])
pool = pycassa.ConnectionPool(__opts__['cassandra.keyspace'],
__opts__['cassandra.servers'])
ccf = pycassa.ColumnFamily(pool, __opts__['cassandra.column_family'],
write_consistency_level=consistency_level)
columns = {'fun': ret['fun'],
'id': ret['id']}
if isinstance(ret['return'], dict):
for key, value in six.iteritems(ret['return']):
columns['return.{0}'.format(key)] = six.text_type(value)
else:
columns['return'] = six.text_type(ret['return'])
log.debug(columns)
ccf.insert(ret['jid'], columns) | [
"def",
"returner",
"(",
"ret",
")",
":",
"consistency_level",
"=",
"getattr",
"(",
"pycassa",
".",
"ConsistencyLevel",
",",
"__opts__",
"[",
"'cassandra.consistency_level'",
"]",
")",
"pool",
"=",
"pycassa",
".",
"ConnectionPool",
"(",
"__opts__",
"[",
"'cassand... | Return data to a Cassandra ColumnFamily | [
"Return",
"data",
"to",
"a",
"Cassandra",
"ColumnFamily"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/cassandra_return.py#L54-L76 | train |
saltstack/salt | salt/modules/seed.py | prep_bootstrap | def prep_bootstrap(mpt):
'''
Update and get the random script to a random place
CLI Example:
.. code-block:: bash
salt '*' seed.prep_bootstrap /tmp
'''
# Verify that the boostrap script is downloaded
bs_ = __salt__['config.gather_bootstrap_script']()
fpd_ = os.path.join(mpt, 'tmp', "{0}".format(
uuid.uuid4()))
if not os.path.exists(fpd_):
os.makedirs(fpd_)
os.chmod(fpd_, 0o700)
fp_ = os.path.join(fpd_, os.path.basename(bs_))
# Copy script into tmp
shutil.copy(bs_, fp_)
tmppath = fpd_.replace(mpt, '')
return fp_, tmppath | python | def prep_bootstrap(mpt):
'''
Update and get the random script to a random place
CLI Example:
.. code-block:: bash
salt '*' seed.prep_bootstrap /tmp
'''
# Verify that the boostrap script is downloaded
bs_ = __salt__['config.gather_bootstrap_script']()
fpd_ = os.path.join(mpt, 'tmp', "{0}".format(
uuid.uuid4()))
if not os.path.exists(fpd_):
os.makedirs(fpd_)
os.chmod(fpd_, 0o700)
fp_ = os.path.join(fpd_, os.path.basename(bs_))
# Copy script into tmp
shutil.copy(bs_, fp_)
tmppath = fpd_.replace(mpt, '')
return fp_, tmppath | [
"def",
"prep_bootstrap",
"(",
"mpt",
")",
":",
"# Verify that the boostrap script is downloaded",
"bs_",
"=",
"__salt__",
"[",
"'config.gather_bootstrap_script'",
"]",
"(",
")",
"fpd_",
"=",
"os",
".",
"path",
".",
"join",
"(",
"mpt",
",",
"'tmp'",
",",
"\"{0}\"... | Update and get the random script to a random place
CLI Example:
.. code-block:: bash
salt '*' seed.prep_bootstrap /tmp | [
"Update",
"and",
"get",
"the",
"random",
"script",
"to",
"a",
"random",
"place"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/seed.py#L39-L61 | train |
saltstack/salt | salt/modules/seed.py | apply_ | def apply_(path, id_=None, config=None, approve_key=True, install=True,
prep_install=False, pub_key=None, priv_key=None, mount_point=None):
'''
Seed a location (disk image, directory, or block device) with the
minion config, approve the minion's key, and/or install salt-minion.
CLI Example:
.. code-block:: bash
salt 'minion' seed.apply path id [config=config_data] \\
[gen_key=(true|false)] [approve_key=(true|false)] \\
[install=(true|false)]
path
Full path to the directory, device, or disk image on the target
minion's file system.
id
Minion id with which to seed the path.
config
Minion configuration options. By default, the 'master' option is set to
the target host's 'master'.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: true.
install
Install salt-minion, if absent. Default: true.
prep_install
Prepare the bootstrap script, but don't run it. Default: false
'''
stats = __salt__['file.stats'](path, follow_symlinks=True)
if not stats:
return '{0} does not exist'.format(path)
ftype = stats['type']
path = stats['target']
log.debug('Mounting %s at %s', ftype, path)
try:
os.makedirs(path)
except OSError:
# The directory already exists
pass
mpt = _mount(path, ftype, mount_point)
if not mpt:
return '{0} could not be mounted'.format(path)
tmp = os.path.join(mpt, 'tmp')
log.debug('Attempting to create directory %s', tmp)
try:
os.makedirs(tmp)
except OSError:
if not os.path.isdir(tmp):
raise
cfg_files = mkconfig(config, tmp=tmp, id_=id_, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if _check_install(mpt):
# salt-minion is already installed, just move the config and keys
# into place
log.info('salt-minion pre-installed on image, '
'configuring as %s', id_)
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
if not os.path.isdir(os.path.join(mpt, pki_dir.lstrip('/'))):
__salt__['file.makedirs'](
os.path.join(mpt, pki_dir.lstrip('/'), '')
)
os.rename(cfg_files['privkey'], os.path.join(
mpt, pki_dir.lstrip('/'), 'minion.pem'))
os.rename(cfg_files['pubkey'], os.path.join(
mpt, pki_dir.lstrip('/'), 'minion.pub'))
os.rename(cfg_files['config'], os.path.join(mpt, 'etc/salt/minion'))
res = True
elif install:
log.info('Attempting to install salt-minion to %s', mpt)
res = _install(mpt)
elif prep_install:
log.error('The prep_install option is no longer supported. Please use '
'the bootstrap script installed with Salt, located at %s.',
salt.syspaths.BOOTSTRAP)
res = False
else:
log.warning('No useful action performed on %s', mpt)
res = False
_umount(mpt, ftype)
return res | python | def apply_(path, id_=None, config=None, approve_key=True, install=True,
prep_install=False, pub_key=None, priv_key=None, mount_point=None):
'''
Seed a location (disk image, directory, or block device) with the
minion config, approve the minion's key, and/or install salt-minion.
CLI Example:
.. code-block:: bash
salt 'minion' seed.apply path id [config=config_data] \\
[gen_key=(true|false)] [approve_key=(true|false)] \\
[install=(true|false)]
path
Full path to the directory, device, or disk image on the target
minion's file system.
id
Minion id with which to seed the path.
config
Minion configuration options. By default, the 'master' option is set to
the target host's 'master'.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: true.
install
Install salt-minion, if absent. Default: true.
prep_install
Prepare the bootstrap script, but don't run it. Default: false
'''
stats = __salt__['file.stats'](path, follow_symlinks=True)
if not stats:
return '{0} does not exist'.format(path)
ftype = stats['type']
path = stats['target']
log.debug('Mounting %s at %s', ftype, path)
try:
os.makedirs(path)
except OSError:
# The directory already exists
pass
mpt = _mount(path, ftype, mount_point)
if not mpt:
return '{0} could not be mounted'.format(path)
tmp = os.path.join(mpt, 'tmp')
log.debug('Attempting to create directory %s', tmp)
try:
os.makedirs(tmp)
except OSError:
if not os.path.isdir(tmp):
raise
cfg_files = mkconfig(config, tmp=tmp, id_=id_, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if _check_install(mpt):
# salt-minion is already installed, just move the config and keys
# into place
log.info('salt-minion pre-installed on image, '
'configuring as %s', id_)
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
if not os.path.isdir(os.path.join(mpt, pki_dir.lstrip('/'))):
__salt__['file.makedirs'](
os.path.join(mpt, pki_dir.lstrip('/'), '')
)
os.rename(cfg_files['privkey'], os.path.join(
mpt, pki_dir.lstrip('/'), 'minion.pem'))
os.rename(cfg_files['pubkey'], os.path.join(
mpt, pki_dir.lstrip('/'), 'minion.pub'))
os.rename(cfg_files['config'], os.path.join(mpt, 'etc/salt/minion'))
res = True
elif install:
log.info('Attempting to install salt-minion to %s', mpt)
res = _install(mpt)
elif prep_install:
log.error('The prep_install option is no longer supported. Please use '
'the bootstrap script installed with Salt, located at %s.',
salt.syspaths.BOOTSTRAP)
res = False
else:
log.warning('No useful action performed on %s', mpt)
res = False
_umount(mpt, ftype)
return res | [
"def",
"apply_",
"(",
"path",
",",
"id_",
"=",
"None",
",",
"config",
"=",
"None",
",",
"approve_key",
"=",
"True",
",",
"install",
"=",
"True",
",",
"prep_install",
"=",
"False",
",",
"pub_key",
"=",
"None",
",",
"priv_key",
"=",
"None",
",",
"mount... | Seed a location (disk image, directory, or block device) with the
minion config, approve the minion's key, and/or install salt-minion.
CLI Example:
.. code-block:: bash
salt 'minion' seed.apply path id [config=config_data] \\
[gen_key=(true|false)] [approve_key=(true|false)] \\
[install=(true|false)]
path
Full path to the directory, device, or disk image on the target
minion's file system.
id
Minion id with which to seed the path.
config
Minion configuration options. By default, the 'master' option is set to
the target host's 'master'.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: true.
install
Install salt-minion, if absent. Default: true.
prep_install
Prepare the bootstrap script, but don't run it. Default: false | [
"Seed",
"a",
"location",
"(",
"disk",
"image",
"directory",
"or",
"block",
"device",
")",
"with",
"the",
"minion",
"config",
"approve",
"the",
"minion",
"s",
"key",
"and",
"/",
"or",
"install",
"salt",
"-",
"minion",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/seed.py#L94-L187 | train |
saltstack/salt | salt/modules/seed.py | mkconfig | def mkconfig(config=None,
tmp=None,
id_=None,
approve_key=True,
pub_key=None,
priv_key=None):
'''
Generate keys and config and put them in a tmp directory.
pub_key
absolute path or file content of an optional preseeded salt key
priv_key
absolute path or file content of an optional preseeded salt key
CLI Example:
.. code-block:: bash
salt 'minion' seed.mkconfig [config=config_data] [tmp=tmp_dir] \\
[id_=minion_id] [approve_key=(true|false)]
'''
if tmp is None:
tmp = tempfile.mkdtemp()
if config is None:
config = {}
if 'master' not in config and __opts__['master'] != 'salt':
config['master'] = __opts__['master']
if id_:
config['id'] = id_
# Write the new minion's config to a tmp file
tmp_config = os.path.join(tmp, 'minion')
with salt.utils.files.fopen(tmp_config, 'w+') as fp_:
fp_.write(salt.utils.cloud.salt_config_to_yaml(config))
# Generate keys for the minion
pubkeyfn = os.path.join(tmp, 'minion.pub')
privkeyfn = os.path.join(tmp, 'minion.pem')
preseeded = pub_key and priv_key
if preseeded:
log.debug('Writing minion.pub to %s', pubkeyfn)
log.debug('Writing minion.pem to %s', privkeyfn)
with salt.utils.files.fopen(pubkeyfn, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(_file_or_content(pub_key)))
with salt.utils.files.fopen(privkeyfn, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(_file_or_content(priv_key)))
os.chmod(pubkeyfn, 0o600)
os.chmod(privkeyfn, 0o600)
else:
salt.crypt.gen_keys(tmp, 'minion', 2048)
if approve_key and not preseeded:
with salt.utils.files.fopen(pubkeyfn) as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
__salt__['pillar.ext']({'virtkey': [id_, pubkey]})
return {'config': tmp_config, 'pubkey': pubkeyfn, 'privkey': privkeyfn} | python | def mkconfig(config=None,
tmp=None,
id_=None,
approve_key=True,
pub_key=None,
priv_key=None):
'''
Generate keys and config and put them in a tmp directory.
pub_key
absolute path or file content of an optional preseeded salt key
priv_key
absolute path or file content of an optional preseeded salt key
CLI Example:
.. code-block:: bash
salt 'minion' seed.mkconfig [config=config_data] [tmp=tmp_dir] \\
[id_=minion_id] [approve_key=(true|false)]
'''
if tmp is None:
tmp = tempfile.mkdtemp()
if config is None:
config = {}
if 'master' not in config and __opts__['master'] != 'salt':
config['master'] = __opts__['master']
if id_:
config['id'] = id_
# Write the new minion's config to a tmp file
tmp_config = os.path.join(tmp, 'minion')
with salt.utils.files.fopen(tmp_config, 'w+') as fp_:
fp_.write(salt.utils.cloud.salt_config_to_yaml(config))
# Generate keys for the minion
pubkeyfn = os.path.join(tmp, 'minion.pub')
privkeyfn = os.path.join(tmp, 'minion.pem')
preseeded = pub_key and priv_key
if preseeded:
log.debug('Writing minion.pub to %s', pubkeyfn)
log.debug('Writing minion.pem to %s', privkeyfn)
with salt.utils.files.fopen(pubkeyfn, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(_file_or_content(pub_key)))
with salt.utils.files.fopen(privkeyfn, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(_file_or_content(priv_key)))
os.chmod(pubkeyfn, 0o600)
os.chmod(privkeyfn, 0o600)
else:
salt.crypt.gen_keys(tmp, 'minion', 2048)
if approve_key and not preseeded:
with salt.utils.files.fopen(pubkeyfn) as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
__salt__['pillar.ext']({'virtkey': [id_, pubkey]})
return {'config': tmp_config, 'pubkey': pubkeyfn, 'privkey': privkeyfn} | [
"def",
"mkconfig",
"(",
"config",
"=",
"None",
",",
"tmp",
"=",
"None",
",",
"id_",
"=",
"None",
",",
"approve_key",
"=",
"True",
",",
"pub_key",
"=",
"None",
",",
"priv_key",
"=",
"None",
")",
":",
"if",
"tmp",
"is",
"None",
":",
"tmp",
"=",
"te... | Generate keys and config and put them in a tmp directory.
pub_key
absolute path or file content of an optional preseeded salt key
priv_key
absolute path or file content of an optional preseeded salt key
CLI Example:
.. code-block:: bash
salt 'minion' seed.mkconfig [config=config_data] [tmp=tmp_dir] \\
[id_=minion_id] [approve_key=(true|false)] | [
"Generate",
"keys",
"and",
"config",
"and",
"put",
"them",
"in",
"a",
"tmp",
"directory",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/seed.py#L190-L246 | train |
saltstack/salt | salt/modules/seed.py | _install | def _install(mpt):
'''
Determine whether salt-minion is installed and, if not,
install it.
Return True if install is successful or already installed.
'''
_check_resolv(mpt)
boot_, tmppath = (prep_bootstrap(mpt)
or salt.syspaths.BOOTSTRAP)
# Exec the chroot command
cmd = 'if type salt-minion; then exit 0; '
cmd += 'else sh {0} -c /tmp; fi'.format(os.path.join(tmppath, 'bootstrap-salt.sh'))
return not __salt__['cmd.run_chroot'](mpt, cmd, python_shell=True)['retcode'] | python | def _install(mpt):
'''
Determine whether salt-minion is installed and, if not,
install it.
Return True if install is successful or already installed.
'''
_check_resolv(mpt)
boot_, tmppath = (prep_bootstrap(mpt)
or salt.syspaths.BOOTSTRAP)
# Exec the chroot command
cmd = 'if type salt-minion; then exit 0; '
cmd += 'else sh {0} -c /tmp; fi'.format(os.path.join(tmppath, 'bootstrap-salt.sh'))
return not __salt__['cmd.run_chroot'](mpt, cmd, python_shell=True)['retcode'] | [
"def",
"_install",
"(",
"mpt",
")",
":",
"_check_resolv",
"(",
"mpt",
")",
"boot_",
",",
"tmppath",
"=",
"(",
"prep_bootstrap",
"(",
"mpt",
")",
"or",
"salt",
".",
"syspaths",
".",
"BOOTSTRAP",
")",
"# Exec the chroot command",
"cmd",
"=",
"'if type salt-min... | Determine whether salt-minion is installed and, if not,
install it.
Return True if install is successful or already installed. | [
"Determine",
"whether",
"salt",
"-",
"minion",
"is",
"installed",
"and",
"if",
"not",
"install",
"it",
".",
"Return",
"True",
"if",
"install",
"is",
"successful",
"or",
"already",
"installed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/seed.py#L249-L261 | train |
saltstack/salt | salt/modules/seed.py | _check_resolv | def _check_resolv(mpt):
'''
Check that the resolv.conf is present and populated
'''
resolv = os.path.join(mpt, 'etc/resolv.conf')
replace = False
if os.path.islink(resolv):
resolv = os.path.realpath(resolv)
if not os.path.isdir(os.path.dirname(resolv)):
os.makedirs(os.path.dirname(resolv))
if not os.path.isfile(resolv):
replace = True
if not replace:
with salt.utils.files.fopen(resolv, 'rb') as fp_:
conts = salt.utils.stringutils.to_unicode(fp_.read())
if 'nameserver' not in conts:
replace = True
if 'nameserver 127.0.0.1' in conts:
replace = True
if replace:
shutil.copy('/etc/resolv.conf', resolv) | python | def _check_resolv(mpt):
'''
Check that the resolv.conf is present and populated
'''
resolv = os.path.join(mpt, 'etc/resolv.conf')
replace = False
if os.path.islink(resolv):
resolv = os.path.realpath(resolv)
if not os.path.isdir(os.path.dirname(resolv)):
os.makedirs(os.path.dirname(resolv))
if not os.path.isfile(resolv):
replace = True
if not replace:
with salt.utils.files.fopen(resolv, 'rb') as fp_:
conts = salt.utils.stringutils.to_unicode(fp_.read())
if 'nameserver' not in conts:
replace = True
if 'nameserver 127.0.0.1' in conts:
replace = True
if replace:
shutil.copy('/etc/resolv.conf', resolv) | [
"def",
"_check_resolv",
"(",
"mpt",
")",
":",
"resolv",
"=",
"os",
".",
"path",
".",
"join",
"(",
"mpt",
",",
"'etc/resolv.conf'",
")",
"replace",
"=",
"False",
"if",
"os",
".",
"path",
".",
"islink",
"(",
"resolv",
")",
":",
"resolv",
"=",
"os",
"... | Check that the resolv.conf is present and populated | [
"Check",
"that",
"the",
"resolv",
".",
"conf",
"is",
"present",
"and",
"populated"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/seed.py#L264-L284 | train |
saltstack/salt | salt/utils/win_lgpo_netsh.py | _netsh_file | def _netsh_file(content):
'''
helper function to get the results of ``netsh -f content.txt``
Running ``netsh`` will drop you into a ``netsh`` prompt where you can issue
``netsh`` commands. You can put a series of commands in an external file and
run them as if from a ``netsh`` prompt using the ``-f`` switch. That's what
this function does.
Args:
content (str):
The contents of the file that will be run by the ``netsh -f``
command
Returns:
str: The text returned by the netsh command
'''
with tempfile.NamedTemporaryFile(mode='w',
prefix='salt-',
suffix='.netsh',
delete=False) as fp:
fp.write(content)
try:
log.debug('%s:\n%s', fp.name, content)
return salt.modules.cmdmod.run('netsh -f {0}'.format(fp.name), python_shell=True)
finally:
os.remove(fp.name) | python | def _netsh_file(content):
'''
helper function to get the results of ``netsh -f content.txt``
Running ``netsh`` will drop you into a ``netsh`` prompt where you can issue
``netsh`` commands. You can put a series of commands in an external file and
run them as if from a ``netsh`` prompt using the ``-f`` switch. That's what
this function does.
Args:
content (str):
The contents of the file that will be run by the ``netsh -f``
command
Returns:
str: The text returned by the netsh command
'''
with tempfile.NamedTemporaryFile(mode='w',
prefix='salt-',
suffix='.netsh',
delete=False) as fp:
fp.write(content)
try:
log.debug('%s:\n%s', fp.name, content)
return salt.modules.cmdmod.run('netsh -f {0}'.format(fp.name), python_shell=True)
finally:
os.remove(fp.name) | [
"def",
"_netsh_file",
"(",
"content",
")",
":",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"mode",
"=",
"'w'",
",",
"prefix",
"=",
"'salt-'",
",",
"suffix",
"=",
"'.netsh'",
",",
"delete",
"=",
"False",
")",
"as",
"fp",
":",
"fp",
".",
"write"... | helper function to get the results of ``netsh -f content.txt``
Running ``netsh`` will drop you into a ``netsh`` prompt where you can issue
``netsh`` commands. You can put a series of commands in an external file and
run them as if from a ``netsh`` prompt using the ``-f`` switch. That's what
this function does.
Args:
content (str):
The contents of the file that will be run by the ``netsh -f``
command
Returns:
str: The text returned by the netsh command | [
"helper",
"function",
"to",
"get",
"the",
"results",
"of",
"netsh",
"-",
"f",
"content",
".",
"txt"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_lgpo_netsh.py#L99-L126 | train |
saltstack/salt | salt/utils/win_lgpo_netsh.py | get_settings | def get_settings(profile, section, store='local'):
'''
Get the firewall property from the specified profile in the specified store
as returned by ``netsh advfirewall``.
Args:
profile (str):
The firewall profile to query. Valid options are:
- domain
- public
- private
section (str):
The property to query within the selected profile. Valid options
are:
- firewallpolicy : inbound/outbound behavior
- logging : firewall logging settings
- settings : firewall properties
- state : firewalls state (on | off)
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
dict: A dictionary containing the properties for the specified profile
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect
'''
# validate input
if profile.lower() not in ('domain', 'public', 'private'):
raise ValueError('Incorrect profile: {0}'.format(profile))
if section.lower() not in ('state', 'firewallpolicy', 'settings', 'logging'):
raise ValueError('Incorrect section: {0}'.format(section))
if store.lower() not in ('local', 'lgpo'):
raise ValueError('Incorrect store: {0}'.format(store))
command = 'show {0}profile {1}'.format(profile, section)
# run it
results = _netsh_command(command=command, store=store)
# sample output:
# Domain Profile Settings:
# ----------------------------------------------------------------------
# LocalFirewallRules N/A (GPO-store only)
# LocalConSecRules N/A (GPO-store only)
# InboundUserNotification Disable
# RemoteManagement Disable
# UnicastResponseToMulticast Enable
# if it's less than 3 lines it failed
if len(results) < 3:
raise CommandExecutionError('Invalid results: {0}'.format(results))
ret = {}
# Skip the first 2 lines. Add everything else to a dictionary
for line in results[3:]:
ret.update(dict(list(zip(*[iter(re.split(r"\s{2,}", line))]*2))))
# Remove spaces from the values so that `Not Configured` is detected
# correctly
for item in ret:
ret[item] = ret[item].replace(' ', '')
# special handling for firewallpolicy
if section == 'firewallpolicy':
inbound, outbound = ret['Firewall Policy'].split(',')
return {'Inbound': inbound, 'Outbound': outbound}
return ret | python | def get_settings(profile, section, store='local'):
'''
Get the firewall property from the specified profile in the specified store
as returned by ``netsh advfirewall``.
Args:
profile (str):
The firewall profile to query. Valid options are:
- domain
- public
- private
section (str):
The property to query within the selected profile. Valid options
are:
- firewallpolicy : inbound/outbound behavior
- logging : firewall logging settings
- settings : firewall properties
- state : firewalls state (on | off)
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
dict: A dictionary containing the properties for the specified profile
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect
'''
# validate input
if profile.lower() not in ('domain', 'public', 'private'):
raise ValueError('Incorrect profile: {0}'.format(profile))
if section.lower() not in ('state', 'firewallpolicy', 'settings', 'logging'):
raise ValueError('Incorrect section: {0}'.format(section))
if store.lower() not in ('local', 'lgpo'):
raise ValueError('Incorrect store: {0}'.format(store))
command = 'show {0}profile {1}'.format(profile, section)
# run it
results = _netsh_command(command=command, store=store)
# sample output:
# Domain Profile Settings:
# ----------------------------------------------------------------------
# LocalFirewallRules N/A (GPO-store only)
# LocalConSecRules N/A (GPO-store only)
# InboundUserNotification Disable
# RemoteManagement Disable
# UnicastResponseToMulticast Enable
# if it's less than 3 lines it failed
if len(results) < 3:
raise CommandExecutionError('Invalid results: {0}'.format(results))
ret = {}
# Skip the first 2 lines. Add everything else to a dictionary
for line in results[3:]:
ret.update(dict(list(zip(*[iter(re.split(r"\s{2,}", line))]*2))))
# Remove spaces from the values so that `Not Configured` is detected
# correctly
for item in ret:
ret[item] = ret[item].replace(' ', '')
# special handling for firewallpolicy
if section == 'firewallpolicy':
inbound, outbound = ret['Firewall Policy'].split(',')
return {'Inbound': inbound, 'Outbound': outbound}
return ret | [
"def",
"get_settings",
"(",
"profile",
",",
"section",
",",
"store",
"=",
"'local'",
")",
":",
"# validate input",
"if",
"profile",
".",
"lower",
"(",
")",
"not",
"in",
"(",
"'domain'",
",",
"'public'",
",",
"'private'",
")",
":",
"raise",
"ValueError",
... | Get the firewall property from the specified profile in the specified store
as returned by ``netsh advfirewall``.
Args:
profile (str):
The firewall profile to query. Valid options are:
- domain
- public
- private
section (str):
The property to query within the selected profile. Valid options
are:
- firewallpolicy : inbound/outbound behavior
- logging : firewall logging settings
- settings : firewall properties
- state : firewalls state (on | off)
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
dict: A dictionary containing the properties for the specified profile
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect | [
"Get",
"the",
"firewall",
"property",
"from",
"the",
"specified",
"profile",
"in",
"the",
"specified",
"store",
"as",
"returned",
"by",
"netsh",
"advfirewall",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_lgpo_netsh.py#L148-L224 | train |
saltstack/salt | salt/utils/win_lgpo_netsh.py | get_all_settings | def get_all_settings(profile, store='local'):
'''
Gets all the properties for the specified profile in the specified store
Args:
profile (str):
The firewall profile to query. Valid options are:
- domain
- public
- private
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
dict: A dictionary containing the specified settings
'''
ret = dict()
ret.update(get_settings(profile=profile, section='state', store=store))
ret.update(get_settings(profile=profile, section='firewallpolicy', store=store))
ret.update(get_settings(profile=profile, section='settings', store=store))
ret.update(get_settings(profile=profile, section='logging', store=store))
return ret | python | def get_all_settings(profile, store='local'):
'''
Gets all the properties for the specified profile in the specified store
Args:
profile (str):
The firewall profile to query. Valid options are:
- domain
- public
- private
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
dict: A dictionary containing the specified settings
'''
ret = dict()
ret.update(get_settings(profile=profile, section='state', store=store))
ret.update(get_settings(profile=profile, section='firewallpolicy', store=store))
ret.update(get_settings(profile=profile, section='settings', store=store))
ret.update(get_settings(profile=profile, section='logging', store=store))
return ret | [
"def",
"get_all_settings",
"(",
"profile",
",",
"store",
"=",
"'local'",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"ret",
".",
"update",
"(",
"get_settings",
"(",
"profile",
"=",
"profile",
",",
"section",
"=",
"'state'",
",",
"store",
"=",
"store",
")",... | Gets all the properties for the specified profile in the specified store
Args:
profile (str):
The firewall profile to query. Valid options are:
- domain
- public
- private
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
dict: A dictionary containing the specified settings | [
"Gets",
"all",
"the",
"properties",
"for",
"the",
"specified",
"profile",
"in",
"the",
"specified",
"store"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_lgpo_netsh.py#L227-L257 | train |
saltstack/salt | salt/utils/win_lgpo_netsh.py | get_all_profiles | def get_all_profiles(store='local'):
'''
Gets all properties for all profiles in the specified store
Args:
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
dict: A dictionary containing the specified settings for each profile
'''
return {
'Domain Profile': get_all_settings(profile='domain', store=store),
'Private Profile': get_all_settings(profile='private', store=store),
'Public Profile': get_all_settings(profile='public', store=store)
} | python | def get_all_profiles(store='local'):
'''
Gets all properties for all profiles in the specified store
Args:
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
dict: A dictionary containing the specified settings for each profile
'''
return {
'Domain Profile': get_all_settings(profile='domain', store=store),
'Private Profile': get_all_settings(profile='private', store=store),
'Public Profile': get_all_settings(profile='public', store=store)
} | [
"def",
"get_all_profiles",
"(",
"store",
"=",
"'local'",
")",
":",
"return",
"{",
"'Domain Profile'",
":",
"get_all_settings",
"(",
"profile",
"=",
"'domain'",
",",
"store",
"=",
"store",
")",
",",
"'Private Profile'",
":",
"get_all_settings",
"(",
"profile",
... | Gets all properties for all profiles in the specified store
Args:
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
dict: A dictionary containing the specified settings for each profile | [
"Gets",
"all",
"properties",
"for",
"all",
"profiles",
"in",
"the",
"specified",
"store"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_lgpo_netsh.py#L260-L282 | train |
saltstack/salt | salt/utils/win_lgpo_netsh.py | set_firewall_settings | def set_firewall_settings(profile,
inbound=None,
outbound=None,
store='local'):
'''
Set the firewall inbound/outbound settings for the specified profile and
store
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
inbound (str):
The inbound setting. If ``None`` is passed, the setting will remain
unchanged. Valid values are:
- blockinbound
- blockinboundalways
- allowinbound
- notconfigured
Default is ``None``
outbound (str):
The outbound setting. If ``None`` is passed, the setting will remain
unchanged. Valid values are:
- allowoutbound
- blockoutbound
- notconfigured
Default is ``None``
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
bool: ``True`` if successful
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect
'''
# Input validation
if profile.lower() not in ('domain', 'public', 'private'):
raise ValueError('Incorrect profile: {0}'.format(profile))
if inbound and inbound.lower() not in ('blockinbound',
'blockinboundalways',
'allowinbound',
'notconfigured'):
raise ValueError('Incorrect inbound value: {0}'.format(inbound))
if outbound and outbound.lower() not in ('allowoutbound',
'blockoutbound',
'notconfigured'):
raise ValueError('Incorrect outbound value: {0}'.format(outbound))
if not inbound and not outbound:
raise ValueError('Must set inbound or outbound')
# You have to specify inbound and outbound setting at the same time
# If you're only specifying one, you have to get the current setting for the
# other
if not inbound or not outbound:
ret = get_settings(profile=profile,
section='firewallpolicy',
store=store)
if not inbound:
inbound = ret['Inbound']
if not outbound:
outbound = ret['Outbound']
command = 'set {0}profile firewallpolicy {1},{2}' \
''.format(profile, inbound, outbound)
results = _netsh_command(command=command, store=store)
if results:
raise CommandExecutionError('An error occurred: {0}'.format(results))
return True | python | def set_firewall_settings(profile,
inbound=None,
outbound=None,
store='local'):
'''
Set the firewall inbound/outbound settings for the specified profile and
store
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
inbound (str):
The inbound setting. If ``None`` is passed, the setting will remain
unchanged. Valid values are:
- blockinbound
- blockinboundalways
- allowinbound
- notconfigured
Default is ``None``
outbound (str):
The outbound setting. If ``None`` is passed, the setting will remain
unchanged. Valid values are:
- allowoutbound
- blockoutbound
- notconfigured
Default is ``None``
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
bool: ``True`` if successful
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect
'''
# Input validation
if profile.lower() not in ('domain', 'public', 'private'):
raise ValueError('Incorrect profile: {0}'.format(profile))
if inbound and inbound.lower() not in ('blockinbound',
'blockinboundalways',
'allowinbound',
'notconfigured'):
raise ValueError('Incorrect inbound value: {0}'.format(inbound))
if outbound and outbound.lower() not in ('allowoutbound',
'blockoutbound',
'notconfigured'):
raise ValueError('Incorrect outbound value: {0}'.format(outbound))
if not inbound and not outbound:
raise ValueError('Must set inbound or outbound')
# You have to specify inbound and outbound setting at the same time
# If you're only specifying one, you have to get the current setting for the
# other
if not inbound or not outbound:
ret = get_settings(profile=profile,
section='firewallpolicy',
store=store)
if not inbound:
inbound = ret['Inbound']
if not outbound:
outbound = ret['Outbound']
command = 'set {0}profile firewallpolicy {1},{2}' \
''.format(profile, inbound, outbound)
results = _netsh_command(command=command, store=store)
if results:
raise CommandExecutionError('An error occurred: {0}'.format(results))
return True | [
"def",
"set_firewall_settings",
"(",
"profile",
",",
"inbound",
"=",
"None",
",",
"outbound",
"=",
"None",
",",
"store",
"=",
"'local'",
")",
":",
"# Input validation",
"if",
"profile",
".",
"lower",
"(",
")",
"not",
"in",
"(",
"'domain'",
",",
"'public'",... | Set the firewall inbound/outbound settings for the specified profile and
store
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
inbound (str):
The inbound setting. If ``None`` is passed, the setting will remain
unchanged. Valid values are:
- blockinbound
- blockinboundalways
- allowinbound
- notconfigured
Default is ``None``
outbound (str):
The outbound setting. If ``None`` is passed, the setting will remain
unchanged. Valid values are:
- allowoutbound
- blockoutbound
- notconfigured
Default is ``None``
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
bool: ``True`` if successful
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect | [
"Set",
"the",
"firewall",
"inbound",
"/",
"outbound",
"settings",
"for",
"the",
"specified",
"profile",
"and",
"store"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_lgpo_netsh.py#L285-L374 | train |
saltstack/salt | salt/utils/win_lgpo_netsh.py | set_logging_settings | def set_logging_settings(profile, setting, value, store='local'):
'''
Configure logging settings for the Windows firewall.
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
setting (str):
The logging setting to configure. Valid options are:
- allowedconnections
- droppedconnections
- filename
- maxfilesize
value (str):
The value to apply to the setting. Valid values are dependent upon
the setting being configured. Valid options are:
allowedconnections:
- enable
- disable
- notconfigured
droppedconnections:
- enable
- disable
- notconfigured
filename:
- Full path and name of the firewall log file
- notconfigured
maxfilesize:
- 1 - 32767 (Kb)
- notconfigured
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
bool: ``True`` if successful
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect
'''
# Input validation
if profile.lower() not in ('domain', 'public', 'private'):
raise ValueError('Incorrect profile: {0}'.format(profile))
if setting.lower() not in ('allowedconnections',
'droppedconnections',
'filename',
'maxfilesize'):
raise ValueError('Incorrect setting: {0}'.format(setting))
if setting.lower() in ('allowedconnections', 'droppedconnections'):
if value.lower() not in ('enable', 'disable', 'notconfigured'):
raise ValueError('Incorrect value: {0}'.format(value))
# TODO: Consider adding something like the following to validate filename
# https://stackoverflow.com/questions/9532499/check-whether-a-path-is-valid-in-python-without-creating-a-file-at-the-paths-ta
if setting.lower() == 'maxfilesize':
if value.lower() != 'notconfigured':
# Must be a number between 1 and 32767
try:
int(value)
except ValueError:
raise ValueError('Incorrect value: {0}'.format(value))
if not 1 <= int(value) <= 32767:
raise ValueError('Incorrect value: {0}'.format(value))
# Run the command
command = 'set {0}profile logging {1} {2}'.format(profile, setting, value)
results = _netsh_command(command=command, store=store)
# A successful run should return an empty list
if results:
raise CommandExecutionError('An error occurred: {0}'.format(results))
return True | python | def set_logging_settings(profile, setting, value, store='local'):
'''
Configure logging settings for the Windows firewall.
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
setting (str):
The logging setting to configure. Valid options are:
- allowedconnections
- droppedconnections
- filename
- maxfilesize
value (str):
The value to apply to the setting. Valid values are dependent upon
the setting being configured. Valid options are:
allowedconnections:
- enable
- disable
- notconfigured
droppedconnections:
- enable
- disable
- notconfigured
filename:
- Full path and name of the firewall log file
- notconfigured
maxfilesize:
- 1 - 32767 (Kb)
- notconfigured
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
bool: ``True`` if successful
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect
'''
# Input validation
if profile.lower() not in ('domain', 'public', 'private'):
raise ValueError('Incorrect profile: {0}'.format(profile))
if setting.lower() not in ('allowedconnections',
'droppedconnections',
'filename',
'maxfilesize'):
raise ValueError('Incorrect setting: {0}'.format(setting))
if setting.lower() in ('allowedconnections', 'droppedconnections'):
if value.lower() not in ('enable', 'disable', 'notconfigured'):
raise ValueError('Incorrect value: {0}'.format(value))
# TODO: Consider adding something like the following to validate filename
# https://stackoverflow.com/questions/9532499/check-whether-a-path-is-valid-in-python-without-creating-a-file-at-the-paths-ta
if setting.lower() == 'maxfilesize':
if value.lower() != 'notconfigured':
# Must be a number between 1 and 32767
try:
int(value)
except ValueError:
raise ValueError('Incorrect value: {0}'.format(value))
if not 1 <= int(value) <= 32767:
raise ValueError('Incorrect value: {0}'.format(value))
# Run the command
command = 'set {0}profile logging {1} {2}'.format(profile, setting, value)
results = _netsh_command(command=command, store=store)
# A successful run should return an empty list
if results:
raise CommandExecutionError('An error occurred: {0}'.format(results))
return True | [
"def",
"set_logging_settings",
"(",
"profile",
",",
"setting",
",",
"value",
",",
"store",
"=",
"'local'",
")",
":",
"# Input validation",
"if",
"profile",
".",
"lower",
"(",
")",
"not",
"in",
"(",
"'domain'",
",",
"'public'",
",",
"'private'",
")",
":",
... | Configure logging settings for the Windows firewall.
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
setting (str):
The logging setting to configure. Valid options are:
- allowedconnections
- droppedconnections
- filename
- maxfilesize
value (str):
The value to apply to the setting. Valid values are dependent upon
the setting being configured. Valid options are:
allowedconnections:
- enable
- disable
- notconfigured
droppedconnections:
- enable
- disable
- notconfigured
filename:
- Full path and name of the firewall log file
- notconfigured
maxfilesize:
- 1 - 32767 (Kb)
- notconfigured
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
bool: ``True`` if successful
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect | [
"Configure",
"logging",
"settings",
"for",
"the",
"Windows",
"firewall",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_lgpo_netsh.py#L377-L470 | train |
saltstack/salt | salt/utils/win_lgpo_netsh.py | set_settings | def set_settings(profile, setting, value, store='local'):
'''
Configure firewall settings.
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
setting (str):
The firewall setting to configure. Valid options are:
- localfirewallrules
- localconsecrules
- inboundusernotification
- remotemanagement
- unicastresponsetomulticast
value (str):
The value to apply to the setting. Valid options are
- enable
- disable
- notconfigured
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
bool: ``True`` if successful
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect
'''
# Input validation
if profile.lower() not in ('domain', 'public', 'private'):
raise ValueError('Incorrect profile: {0}'.format(profile))
if setting.lower() not in ('localfirewallrules',
'localconsecrules',
'inboundusernotification',
'remotemanagement',
'unicastresponsetomulticast'):
raise ValueError('Incorrect setting: {0}'.format(setting))
if value.lower() not in ('enable', 'disable', 'notconfigured'):
raise ValueError('Incorrect value: {0}'.format(value))
# Run the command
command = 'set {0}profile settings {1} {2}'.format(profile, setting, value)
results = _netsh_command(command=command, store=store)
# A successful run should return an empty list
if results:
raise CommandExecutionError('An error occurred: {0}'.format(results))
return True | python | def set_settings(profile, setting, value, store='local'):
'''
Configure firewall settings.
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
setting (str):
The firewall setting to configure. Valid options are:
- localfirewallrules
- localconsecrules
- inboundusernotification
- remotemanagement
- unicastresponsetomulticast
value (str):
The value to apply to the setting. Valid options are
- enable
- disable
- notconfigured
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
bool: ``True`` if successful
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect
'''
# Input validation
if profile.lower() not in ('domain', 'public', 'private'):
raise ValueError('Incorrect profile: {0}'.format(profile))
if setting.lower() not in ('localfirewallrules',
'localconsecrules',
'inboundusernotification',
'remotemanagement',
'unicastresponsetomulticast'):
raise ValueError('Incorrect setting: {0}'.format(setting))
if value.lower() not in ('enable', 'disable', 'notconfigured'):
raise ValueError('Incorrect value: {0}'.format(value))
# Run the command
command = 'set {0}profile settings {1} {2}'.format(profile, setting, value)
results = _netsh_command(command=command, store=store)
# A successful run should return an empty list
if results:
raise CommandExecutionError('An error occurred: {0}'.format(results))
return True | [
"def",
"set_settings",
"(",
"profile",
",",
"setting",
",",
"value",
",",
"store",
"=",
"'local'",
")",
":",
"# Input validation",
"if",
"profile",
".",
"lower",
"(",
")",
"not",
"in",
"(",
"'domain'",
",",
"'public'",
",",
"'private'",
")",
":",
"raise"... | Configure firewall settings.
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
setting (str):
The firewall setting to configure. Valid options are:
- localfirewallrules
- localconsecrules
- inboundusernotification
- remotemanagement
- unicastresponsetomulticast
value (str):
The value to apply to the setting. Valid options are
- enable
- disable
- notconfigured
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
bool: ``True`` if successful
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect | [
"Configure",
"firewall",
"settings",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_lgpo_netsh.py#L473-L538 | train |
saltstack/salt | salt/utils/win_lgpo_netsh.py | set_state | def set_state(profile, state, store='local'):
'''
Configure the firewall state.
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
state (str):
The firewall state. Valid options are:
- on
- off
- notconfigured
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
bool: ``True`` if successful
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect
'''
# Input validation
if profile.lower() not in ('domain', 'public', 'private'):
raise ValueError('Incorrect profile: {0}'.format(profile))
if state.lower() not in ('on', 'off', 'notconfigured'):
raise ValueError('Incorrect state: {0}'.format(state))
# Run the command
command = 'set {0}profile state {1}'.format(profile, state)
results = _netsh_command(command=command, store=store)
# A successful run should return an empty list
if results:
raise CommandExecutionError('An error occurred: {0}'.format(results))
return True | python | def set_state(profile, state, store='local'):
'''
Configure the firewall state.
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
state (str):
The firewall state. Valid options are:
- on
- off
- notconfigured
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
bool: ``True`` if successful
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect
'''
# Input validation
if profile.lower() not in ('domain', 'public', 'private'):
raise ValueError('Incorrect profile: {0}'.format(profile))
if state.lower() not in ('on', 'off', 'notconfigured'):
raise ValueError('Incorrect state: {0}'.format(state))
# Run the command
command = 'set {0}profile state {1}'.format(profile, state)
results = _netsh_command(command=command, store=store)
# A successful run should return an empty list
if results:
raise CommandExecutionError('An error occurred: {0}'.format(results))
return True | [
"def",
"set_state",
"(",
"profile",
",",
"state",
",",
"store",
"=",
"'local'",
")",
":",
"# Input validation",
"if",
"profile",
".",
"lower",
"(",
")",
"not",
"in",
"(",
"'domain'",
",",
"'public'",
",",
"'private'",
")",
":",
"raise",
"ValueError",
"("... | Configure the firewall state.
Args:
profile (str):
The firewall profile to configure. Valid options are:
- domain
- public
- private
state (str):
The firewall state. Valid options are:
- on
- off
- notconfigured
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
Returns:
bool: ``True`` if successful
Raises:
CommandExecutionError: If an error occurs
ValueError: If the parameters are incorrect | [
"Configure",
"the",
"firewall",
"state",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_lgpo_netsh.py#L541-L591 | train |
saltstack/salt | salt/modules/aliases.py | __parse_aliases | def __parse_aliases():
'''
Parse the aliases file, and return a list of line components:
[
(alias1, target1, comment1),
(alias2, target2, comment2),
]
'''
afn = __get_aliases_filename()
ret = []
if not os.path.isfile(afn):
return ret
with salt.utils.files.fopen(afn, 'r') as ifile:
for line in ifile:
line = salt.utils.stringutils.to_unicode(line)
match = __ALIAS_RE.match(line)
if match:
ret.append(match.groups())
else:
ret.append((None, None, line.strip()))
return ret | python | def __parse_aliases():
'''
Parse the aliases file, and return a list of line components:
[
(alias1, target1, comment1),
(alias2, target2, comment2),
]
'''
afn = __get_aliases_filename()
ret = []
if not os.path.isfile(afn):
return ret
with salt.utils.files.fopen(afn, 'r') as ifile:
for line in ifile:
line = salt.utils.stringutils.to_unicode(line)
match = __ALIAS_RE.match(line)
if match:
ret.append(match.groups())
else:
ret.append((None, None, line.strip()))
return ret | [
"def",
"__parse_aliases",
"(",
")",
":",
"afn",
"=",
"__get_aliases_filename",
"(",
")",
"ret",
"=",
"[",
"]",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"afn",
")",
":",
"return",
"ret",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"f... | Parse the aliases file, and return a list of line components:
[
(alias1, target1, comment1),
(alias2, target2, comment2),
] | [
"Parse",
"the",
"aliases",
"file",
"and",
"return",
"a",
"list",
"of",
"line",
"components",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aliases.py#L40-L61 | train |
saltstack/salt | salt/modules/aliases.py | __write_aliases_file | def __write_aliases_file(lines):
'''
Write a new copy of the aliases file. Lines is a list of lines
as returned by __parse_aliases.
'''
afn = __get_aliases_filename()
adir = os.path.dirname(afn)
out = tempfile.NamedTemporaryFile(dir=adir, delete=False)
if not __opts__.get('integration.test', False):
if os.path.isfile(afn):
afn_st = os.stat(afn)
os.chmod(out.name, stat.S_IMODE(afn_st.st_mode))
os.chown(out.name, afn_st.st_uid, afn_st.st_gid)
else:
os.chmod(out.name, 0o644)
os.chown(out.name, 0, 0)
for (line_alias, line_target, line_comment) in lines:
if isinstance(line_target, list):
line_target = ', '.join(line_target)
if not line_comment:
line_comment = ''
if line_alias and line_target:
write_line = '{0}: {1}{2}\n'.format(
line_alias, line_target, line_comment
)
else:
write_line = '{0}\n'.format(line_comment)
if six.PY3:
write_line = write_line.encode(__salt_system_encoding__)
out.write(write_line)
out.close()
os.rename(out.name, afn)
# Search $PATH for the newalises command
newaliases = salt.utils.path.which('newaliases')
if newaliases is not None:
__salt__['cmd.run'](newaliases)
return True | python | def __write_aliases_file(lines):
'''
Write a new copy of the aliases file. Lines is a list of lines
as returned by __parse_aliases.
'''
afn = __get_aliases_filename()
adir = os.path.dirname(afn)
out = tempfile.NamedTemporaryFile(dir=adir, delete=False)
if not __opts__.get('integration.test', False):
if os.path.isfile(afn):
afn_st = os.stat(afn)
os.chmod(out.name, stat.S_IMODE(afn_st.st_mode))
os.chown(out.name, afn_st.st_uid, afn_st.st_gid)
else:
os.chmod(out.name, 0o644)
os.chown(out.name, 0, 0)
for (line_alias, line_target, line_comment) in lines:
if isinstance(line_target, list):
line_target = ', '.join(line_target)
if not line_comment:
line_comment = ''
if line_alias and line_target:
write_line = '{0}: {1}{2}\n'.format(
line_alias, line_target, line_comment
)
else:
write_line = '{0}\n'.format(line_comment)
if six.PY3:
write_line = write_line.encode(__salt_system_encoding__)
out.write(write_line)
out.close()
os.rename(out.name, afn)
# Search $PATH for the newalises command
newaliases = salt.utils.path.which('newaliases')
if newaliases is not None:
__salt__['cmd.run'](newaliases)
return True | [
"def",
"__write_aliases_file",
"(",
"lines",
")",
":",
"afn",
"=",
"__get_aliases_filename",
"(",
")",
"adir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"afn",
")",
"out",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"dir",
"=",
"adir",
",",
"dele... | Write a new copy of the aliases file. Lines is a list of lines
as returned by __parse_aliases. | [
"Write",
"a",
"new",
"copy",
"of",
"the",
"aliases",
"file",
".",
"Lines",
"is",
"a",
"list",
"of",
"lines",
"as",
"returned",
"by",
"__parse_aliases",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aliases.py#L64-L106 | train |
saltstack/salt | salt/modules/aliases.py | list_aliases | def list_aliases():
'''
Return the aliases found in the aliases file in this format::
{'alias': 'target'}
CLI Example:
.. code-block:: bash
salt '*' aliases.list_aliases
'''
ret = dict((alias, target) for alias, target, comment in __parse_aliases() if alias)
return ret | python | def list_aliases():
'''
Return the aliases found in the aliases file in this format::
{'alias': 'target'}
CLI Example:
.. code-block:: bash
salt '*' aliases.list_aliases
'''
ret = dict((alias, target) for alias, target, comment in __parse_aliases() if alias)
return ret | [
"def",
"list_aliases",
"(",
")",
":",
"ret",
"=",
"dict",
"(",
"(",
"alias",
",",
"target",
")",
"for",
"alias",
",",
"target",
",",
"comment",
"in",
"__parse_aliases",
"(",
")",
"if",
"alias",
")",
"return",
"ret"
] | Return the aliases found in the aliases file in this format::
{'alias': 'target'}
CLI Example:
.. code-block:: bash
salt '*' aliases.list_aliases | [
"Return",
"the",
"aliases",
"found",
"in",
"the",
"aliases",
"file",
"in",
"this",
"format",
"::"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aliases.py#L109-L122 | train |
saltstack/salt | salt/modules/aliases.py | has_target | def has_target(alias, target):
'''
Return true if the alias/target is set
CLI Example:
.. code-block:: bash
salt '*' aliases.has_target alias target
'''
if target == '':
raise SaltInvocationError('target can not be an empty string')
aliases = list_aliases()
if alias not in aliases:
return False
if isinstance(target, list):
target = ', '.join(target)
return target == aliases[alias] | python | def has_target(alias, target):
'''
Return true if the alias/target is set
CLI Example:
.. code-block:: bash
salt '*' aliases.has_target alias target
'''
if target == '':
raise SaltInvocationError('target can not be an empty string')
aliases = list_aliases()
if alias not in aliases:
return False
if isinstance(target, list):
target = ', '.join(target)
return target == aliases[alias] | [
"def",
"has_target",
"(",
"alias",
",",
"target",
")",
":",
"if",
"target",
"==",
"''",
":",
"raise",
"SaltInvocationError",
"(",
"'target can not be an empty string'",
")",
"aliases",
"=",
"list_aliases",
"(",
")",
"if",
"alias",
"not",
"in",
"aliases",
":",
... | Return true if the alias/target is set
CLI Example:
.. code-block:: bash
salt '*' aliases.has_target alias target | [
"Return",
"true",
"if",
"the",
"alias",
"/",
"target",
"is",
"set"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aliases.py#L141-L158 | train |
saltstack/salt | salt/modules/aliases.py | set_target | def set_target(alias, target):
'''
Set the entry in the aliases file for the given alias, this will overwrite
any previous entry for the given alias or create a new one if it does not
exist.
CLI Example:
.. code-block:: bash
salt '*' aliases.set_target alias target
'''
if alias == '':
raise SaltInvocationError('alias can not be an empty string')
if target == '':
raise SaltInvocationError('target can not be an empty string')
if get_target(alias) == target:
return True
lines = __parse_aliases()
out = []
ovr = False
for (line_alias, line_target, line_comment) in lines:
if line_alias == alias:
if not ovr:
out.append((alias, target, line_comment))
ovr = True
else:
out.append((line_alias, line_target, line_comment))
if not ovr:
out.append((alias, target, ''))
__write_aliases_file(out)
return True | python | def set_target(alias, target):
'''
Set the entry in the aliases file for the given alias, this will overwrite
any previous entry for the given alias or create a new one if it does not
exist.
CLI Example:
.. code-block:: bash
salt '*' aliases.set_target alias target
'''
if alias == '':
raise SaltInvocationError('alias can not be an empty string')
if target == '':
raise SaltInvocationError('target can not be an empty string')
if get_target(alias) == target:
return True
lines = __parse_aliases()
out = []
ovr = False
for (line_alias, line_target, line_comment) in lines:
if line_alias == alias:
if not ovr:
out.append((alias, target, line_comment))
ovr = True
else:
out.append((line_alias, line_target, line_comment))
if not ovr:
out.append((alias, target, ''))
__write_aliases_file(out)
return True | [
"def",
"set_target",
"(",
"alias",
",",
"target",
")",
":",
"if",
"alias",
"==",
"''",
":",
"raise",
"SaltInvocationError",
"(",
"'alias can not be an empty string'",
")",
"if",
"target",
"==",
"''",
":",
"raise",
"SaltInvocationError",
"(",
"'target can not be an... | Set the entry in the aliases file for the given alias, this will overwrite
any previous entry for the given alias or create a new one if it does not
exist.
CLI Example:
.. code-block:: bash
salt '*' aliases.set_target alias target | [
"Set",
"the",
"entry",
"in",
"the",
"aliases",
"file",
"for",
"the",
"given",
"alias",
"this",
"will",
"overwrite",
"any",
"previous",
"entry",
"for",
"the",
"given",
"alias",
"or",
"create",
"a",
"new",
"one",
"if",
"it",
"does",
"not",
"exist",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aliases.py#L161-L197 | train |
saltstack/salt | salt/modules/aliases.py | rm_alias | def rm_alias(alias):
'''
Remove an entry from the aliases file
CLI Example:
.. code-block:: bash
salt '*' aliases.rm_alias alias
'''
if not get_target(alias):
return True
lines = __parse_aliases()
out = []
for (line_alias, line_target, line_comment) in lines:
if line_alias != alias:
out.append((line_alias, line_target, line_comment))
__write_aliases_file(out)
return True | python | def rm_alias(alias):
'''
Remove an entry from the aliases file
CLI Example:
.. code-block:: bash
salt '*' aliases.rm_alias alias
'''
if not get_target(alias):
return True
lines = __parse_aliases()
out = []
for (line_alias, line_target, line_comment) in lines:
if line_alias != alias:
out.append((line_alias, line_target, line_comment))
__write_aliases_file(out)
return True | [
"def",
"rm_alias",
"(",
"alias",
")",
":",
"if",
"not",
"get_target",
"(",
"alias",
")",
":",
"return",
"True",
"lines",
"=",
"__parse_aliases",
"(",
")",
"out",
"=",
"[",
"]",
"for",
"(",
"line_alias",
",",
"line_target",
",",
"line_comment",
")",
"in... | Remove an entry from the aliases file
CLI Example:
.. code-block:: bash
salt '*' aliases.rm_alias alias | [
"Remove",
"an",
"entry",
"from",
"the",
"aliases",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aliases.py#L200-L220 | train |
saltstack/salt | salt/thorium/__init__.py | ThorState.gather_cache | def gather_cache(self):
'''
Gather the specified data from the minion data cache
'''
cache = {'grains': {}, 'pillar': {}}
if self.grains or self.pillar:
if self.opts.get('minion_data_cache'):
minions = self.cache.list('minions')
if not minions:
return cache
for minion in minions:
total = self.cache.fetch('minions/{0}'.format(minion), 'data')
if 'pillar' in total:
if self.pillar_keys:
for key in self.pillar_keys:
if key in total['pillar']:
cache['pillar'][minion][key] = total['pillar'][key]
else:
cache['pillar'][minion] = total['pillar']
else:
cache['pillar'][minion] = {}
if 'grains' in total:
if self.grain_keys:
for key in self.grain_keys:
if key in total['grains']:
cache['grains'][minion][key] = total['grains'][key]
else:
cache['grains'][minion] = total['grains']
else:
cache['grains'][minion] = {}
return cache | python | def gather_cache(self):
'''
Gather the specified data from the minion data cache
'''
cache = {'grains': {}, 'pillar': {}}
if self.grains or self.pillar:
if self.opts.get('minion_data_cache'):
minions = self.cache.list('minions')
if not minions:
return cache
for minion in minions:
total = self.cache.fetch('minions/{0}'.format(minion), 'data')
if 'pillar' in total:
if self.pillar_keys:
for key in self.pillar_keys:
if key in total['pillar']:
cache['pillar'][minion][key] = total['pillar'][key]
else:
cache['pillar'][minion] = total['pillar']
else:
cache['pillar'][minion] = {}
if 'grains' in total:
if self.grain_keys:
for key in self.grain_keys:
if key in total['grains']:
cache['grains'][minion][key] = total['grains'][key]
else:
cache['grains'][minion] = total['grains']
else:
cache['grains'][minion] = {}
return cache | [
"def",
"gather_cache",
"(",
"self",
")",
":",
"cache",
"=",
"{",
"'grains'",
":",
"{",
"}",
",",
"'pillar'",
":",
"{",
"}",
"}",
"if",
"self",
".",
"grains",
"or",
"self",
".",
"pillar",
":",
"if",
"self",
".",
"opts",
".",
"get",
"(",
"'minion_d... | Gather the specified data from the minion data cache | [
"Gather",
"the",
"specified",
"data",
"from",
"the",
"minion",
"data",
"cache"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/__init__.py#L70-L102 | train |
saltstack/salt | salt/thorium/__init__.py | ThorState.start_runtime | def start_runtime(self):
'''
Start the system!
'''
while True:
try:
self.call_runtime()
except Exception:
log.error('Exception in Thorium: ', exc_info=True)
time.sleep(self.opts['thorium_interval']) | python | def start_runtime(self):
'''
Start the system!
'''
while True:
try:
self.call_runtime()
except Exception:
log.error('Exception in Thorium: ', exc_info=True)
time.sleep(self.opts['thorium_interval']) | [
"def",
"start_runtime",
"(",
"self",
")",
":",
"while",
"True",
":",
"try",
":",
"self",
".",
"call_runtime",
"(",
")",
"except",
"Exception",
":",
"log",
".",
"error",
"(",
"'Exception in Thorium: '",
",",
"exc_info",
"=",
"True",
")",
"time",
".",
"sle... | Start the system! | [
"Start",
"the",
"system!"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/__init__.py#L104-L113 | train |
saltstack/salt | salt/thorium/__init__.py | ThorState.get_chunks | def get_chunks(self, exclude=None, whitelist=None):
'''
Compile the top file and return the lowstate for the thorium runtime
to iterate over
'''
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:
msg = 'No Top file found!'
raise SaltRenderError(msg)
matches = self.matches_whitelist(matches, whitelist)
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
high, ext_errors = self.state.reconcile_extend(high)
err += ext_errors
err += self.state.verify_high(high)
if err:
raise SaltRenderError(err)
return self.state.compile_high_data(high) | python | def get_chunks(self, exclude=None, whitelist=None):
'''
Compile the top file and return the lowstate for the thorium runtime
to iterate over
'''
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:
msg = 'No Top file found!'
raise SaltRenderError(msg)
matches = self.matches_whitelist(matches, whitelist)
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
high, ext_errors = self.state.reconcile_extend(high)
err += ext_errors
err += self.state.verify_high(high)
if err:
raise SaltRenderError(err)
return self.state.compile_high_data(high) | [
"def",
"get_chunks",
"(",
"self",
",",
"exclude",
"=",
"None",
",",
"whitelist",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"err",
"=",
"[",
"]",
"try",
":",
"top",
"=",
"self",
".",
"get_top",
"(",
")",
"except",
"SaltRenderError",
"as",
"err",
... | Compile the top file and return the lowstate for the thorium runtime
to iterate over | [
"Compile",
"the",
"top",
"file",
"and",
"return",
"the",
"lowstate",
"for",
"the",
"thorium",
"runtime",
"to",
"iterate",
"over"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/__init__.py#L115-L150 | train |
saltstack/salt | salt/thorium/__init__.py | ThorState.get_events | def get_events(self):
'''
iterate over the available events and return a list of events
'''
ret = []
while True:
event = self.event.get_event(wait=1, full=True)
if event is None:
return ret
ret.append(event) | python | def get_events(self):
'''
iterate over the available events and return a list of events
'''
ret = []
while True:
event = self.event.get_event(wait=1, full=True)
if event is None:
return ret
ret.append(event) | [
"def",
"get_events",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"]",
"while",
"True",
":",
"event",
"=",
"self",
".",
"event",
".",
"get_event",
"(",
"wait",
"=",
"1",
",",
"full",
"=",
"True",
")",
"if",
"event",
"is",
"None",
":",
"return",
"ret",... | iterate over the available events and return a list of events | [
"iterate",
"over",
"the",
"available",
"events",
"and",
"return",
"a",
"list",
"of",
"events"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/__init__.py#L152-L161 | train |
saltstack/salt | salt/thorium/__init__.py | ThorState.call_runtime | def call_runtime(self):
'''
Execute the runtime
'''
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
start = time.time()
self.state.inject_globals['__events__'] = events
self.state.call_chunks(chunks)
elapsed = time.time() - start
left = interval - elapsed
if left > 0:
time.sleep(left)
self.state.reset_run_num()
if (start - r_start) > recompile:
cache = self.gather_cache()
chunks = self.get_chunks()
if self.reg_ret is not None:
self.returners['{0}.save_reg'.format(self.reg_ret)](chunks)
r_start = time.time() | python | def call_runtime(self):
'''
Execute the runtime
'''
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
start = time.time()
self.state.inject_globals['__events__'] = events
self.state.call_chunks(chunks)
elapsed = time.time() - start
left = interval - elapsed
if left > 0:
time.sleep(left)
self.state.reset_run_num()
if (start - r_start) > recompile:
cache = self.gather_cache()
chunks = self.get_chunks()
if self.reg_ret is not None:
self.returners['{0}.save_reg'.format(self.reg_ret)](chunks)
r_start = time.time() | [
"def",
"call_runtime",
"(",
"self",
")",
":",
"cache",
"=",
"self",
".",
"gather_cache",
"(",
")",
"chunks",
"=",
"self",
".",
"get_chunks",
"(",
")",
"interval",
"=",
"self",
".",
"opts",
"[",
"'thorium_interval'",
"]",
"recompile",
"=",
"self",
".",
... | Execute the runtime | [
"Execute",
"the",
"runtime"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/__init__.py#L163-L190 | train |
saltstack/salt | salt/modules/container_resource.py | _validate | def _validate(wrapped):
'''
Decorator for common function argument validation
'''
@functools.wraps(wrapped)
def wrapper(*args, **kwargs):
container_type = kwargs.get('container_type')
exec_driver = kwargs.get('exec_driver')
valid_driver = {
'docker': ('lxc-attach', 'nsenter', 'docker-exec'),
'lxc': ('lxc-attach',),
'nspawn': ('nsenter',),
}
if container_type not in valid_driver:
raise SaltInvocationError(
'Invalid container type \'{0}\'. Valid types are: {1}'
.format(container_type, ', '.join(sorted(valid_driver)))
)
if exec_driver not in valid_driver[container_type]:
raise SaltInvocationError(
'Invalid command execution driver. Valid drivers are: {0}'
.format(', '.join(valid_driver[container_type]))
)
if exec_driver == 'lxc-attach' and not salt.utils.path.which('lxc-attach'):
raise SaltInvocationError(
'The \'lxc-attach\' execution driver has been chosen, but '
'lxc-attach is not available. LXC may not be installed.'
)
return wrapped(*args, **salt.utils.args.clean_kwargs(**kwargs))
return wrapper | python | def _validate(wrapped):
'''
Decorator for common function argument validation
'''
@functools.wraps(wrapped)
def wrapper(*args, **kwargs):
container_type = kwargs.get('container_type')
exec_driver = kwargs.get('exec_driver')
valid_driver = {
'docker': ('lxc-attach', 'nsenter', 'docker-exec'),
'lxc': ('lxc-attach',),
'nspawn': ('nsenter',),
}
if container_type not in valid_driver:
raise SaltInvocationError(
'Invalid container type \'{0}\'. Valid types are: {1}'
.format(container_type, ', '.join(sorted(valid_driver)))
)
if exec_driver not in valid_driver[container_type]:
raise SaltInvocationError(
'Invalid command execution driver. Valid drivers are: {0}'
.format(', '.join(valid_driver[container_type]))
)
if exec_driver == 'lxc-attach' and not salt.utils.path.which('lxc-attach'):
raise SaltInvocationError(
'The \'lxc-attach\' execution driver has been chosen, but '
'lxc-attach is not available. LXC may not be installed.'
)
return wrapped(*args, **salt.utils.args.clean_kwargs(**kwargs))
return wrapper | [
"def",
"_validate",
"(",
"wrapped",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"wrapped",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"container_type",
"=",
"kwargs",
".",
"get",
"(",
"'container_type'",
")",
"exec_d... | Decorator for common function argument validation | [
"Decorator",
"for",
"common",
"function",
"argument",
"validation"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/container_resource.py#L35-L64 | train |
saltstack/salt | salt/modules/container_resource.py | cache_file | def cache_file(source):
'''
Wrapper for cp.cache_file which raises an error if the file was unable to
be cached.
CLI Example:
.. code-block:: bash
salt myminion container_resource.cache_file salt://foo/bar/baz.txt
'''
try:
# Don't just use cp.cache_file for this. Docker has its own code to
# pull down images from the web.
if source.startswith('salt://'):
cached_source = __salt__['cp.cache_file'](source)
if not cached_source:
raise CommandExecutionError(
'Unable to cache {0}'.format(source)
)
return cached_source
except AttributeError:
raise SaltInvocationError('Invalid source file {0}'.format(source))
return source | python | def cache_file(source):
'''
Wrapper for cp.cache_file which raises an error if the file was unable to
be cached.
CLI Example:
.. code-block:: bash
salt myminion container_resource.cache_file salt://foo/bar/baz.txt
'''
try:
# Don't just use cp.cache_file for this. Docker has its own code to
# pull down images from the web.
if source.startswith('salt://'):
cached_source = __salt__['cp.cache_file'](source)
if not cached_source:
raise CommandExecutionError(
'Unable to cache {0}'.format(source)
)
return cached_source
except AttributeError:
raise SaltInvocationError('Invalid source file {0}'.format(source))
return source | [
"def",
"cache_file",
"(",
"source",
")",
":",
"try",
":",
"# Don't just use cp.cache_file for this. Docker has its own code to",
"# pull down images from the web.",
"if",
"source",
".",
"startswith",
"(",
"'salt://'",
")",
":",
"cached_source",
"=",
"__salt__",
"[",
"'cp.... | Wrapper for cp.cache_file which raises an error if the file was unable to
be cached.
CLI Example:
.. code-block:: bash
salt myminion container_resource.cache_file salt://foo/bar/baz.txt | [
"Wrapper",
"for",
"cp",
".",
"cache_file",
"which",
"raises",
"an",
"error",
"if",
"the",
"file",
"was",
"unable",
"to",
"be",
"cached",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/container_resource.py#L91-L114 | train |
saltstack/salt | salt/modules/container_resource.py | run | def run(name,
cmd,
container_type=None,
exec_driver=None,
output=None,
no_start=False,
stdin=None,
python_shell=True,
output_loglevel='debug',
ignore_retcode=False,
path=None,
use_vt=False,
keep_env=None):
'''
Common logic for running shell commands in containers
path
path to the container parent (for LXC only)
default: /var/lib/lxc (system default)
CLI Example:
.. code-block:: bash
salt myminion container_resource.run mycontainer 'ps aux' container_type=docker exec_driver=nsenter output=stdout
'''
valid_output = ('stdout', 'stderr', 'retcode', 'all')
if output is None:
cmd_func = 'cmd.run'
elif output not in valid_output:
raise SaltInvocationError(
'\'output\' param must be one of the following: {0}'
.format(', '.join(valid_output))
)
else:
cmd_func = 'cmd.run_all'
if keep_env is None or isinstance(keep_env, bool):
to_keep = []
elif not isinstance(keep_env, (list, tuple)):
try:
to_keep = keep_env.split(',')
except AttributeError:
log.warning('Invalid keep_env value, ignoring')
to_keep = []
else:
to_keep = keep_env
if exec_driver == 'lxc-attach':
full_cmd = 'lxc-attach '
if path:
full_cmd += '-P {0} '.format(pipes.quote(path))
if keep_env is not True:
full_cmd += '--clear-env '
if 'PATH' not in to_keep:
full_cmd += '--set-var {0} '.format(PATH)
# --clear-env results in a very restrictive PATH
# (/bin:/usr/bin), use a good fallback.
full_cmd += ' '.join(
['--set-var {0}={1}'.format(x, pipes.quote(os.environ[x]))
for x in to_keep
if x in os.environ]
)
full_cmd += ' -n {0} -- {1}'.format(pipes.quote(name), cmd)
elif exec_driver == 'nsenter':
pid = __salt__['{0}.pid'.format(container_type)](name)
full_cmd = (
'nsenter --target {0} --mount --uts --ipc --net --pid -- '
.format(pid)
)
if keep_env is not True:
full_cmd += 'env -i '
if 'PATH' not in to_keep:
full_cmd += '{0} '.format(PATH)
full_cmd += ' '.join(
['{0}={1}'.format(x, pipes.quote(os.environ[x]))
for x in to_keep
if x in os.environ]
)
full_cmd += ' {0}'.format(cmd)
elif exec_driver == 'docker-exec':
# We're using docker exec on the CLI as opposed to via docker-py, since
# the Docker API doesn't return stdout and stderr separately.
full_cmd = 'docker exec '
if stdin:
full_cmd += '-i '
full_cmd += '{0} '.format(name)
if keep_env is not True:
full_cmd += 'env -i '
if 'PATH' not in to_keep:
full_cmd += '{0} '.format(PATH)
full_cmd += ' '.join(
['{0}={1}'.format(x, pipes.quote(os.environ[x]))
for x in to_keep
if x in os.environ]
)
full_cmd += ' {0}'.format(cmd)
if not use_vt:
ret = __salt__[cmd_func](full_cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
else:
stdout, stderr = '', ''
proc = salt.utils.vt.Terminal(
full_cmd,
shell=python_shell,
log_stdin_level='quiet' if output_loglevel == 'quiet' else 'info',
log_stdout_level=output_loglevel,
log_stderr_level=output_loglevel,
log_stdout=True,
log_stderr=True,
stream_stdout=False,
stream_stderr=False
)
# Consume output
try:
while proc.has_unread_data:
try:
cstdout, cstderr = proc.recv()
if cstdout:
stdout += cstdout
if cstderr:
if output is None:
stdout += cstderr
else:
stderr += cstderr
time.sleep(0.5)
except KeyboardInterrupt:
break
ret = stdout if output is None \
else {'retcode': proc.exitstatus,
'pid': 2,
'stdout': stdout,
'stderr': stderr}
except salt.utils.vt.TerminalException:
trace = traceback.format_exc()
log.error(trace)
ret = stdout if output is None \
else {'retcode': 127,
'pid': 2,
'stdout': stdout,
'stderr': stderr}
finally:
proc.terminate()
return ret | python | def run(name,
cmd,
container_type=None,
exec_driver=None,
output=None,
no_start=False,
stdin=None,
python_shell=True,
output_loglevel='debug',
ignore_retcode=False,
path=None,
use_vt=False,
keep_env=None):
'''
Common logic for running shell commands in containers
path
path to the container parent (for LXC only)
default: /var/lib/lxc (system default)
CLI Example:
.. code-block:: bash
salt myminion container_resource.run mycontainer 'ps aux' container_type=docker exec_driver=nsenter output=stdout
'''
valid_output = ('stdout', 'stderr', 'retcode', 'all')
if output is None:
cmd_func = 'cmd.run'
elif output not in valid_output:
raise SaltInvocationError(
'\'output\' param must be one of the following: {0}'
.format(', '.join(valid_output))
)
else:
cmd_func = 'cmd.run_all'
if keep_env is None or isinstance(keep_env, bool):
to_keep = []
elif not isinstance(keep_env, (list, tuple)):
try:
to_keep = keep_env.split(',')
except AttributeError:
log.warning('Invalid keep_env value, ignoring')
to_keep = []
else:
to_keep = keep_env
if exec_driver == 'lxc-attach':
full_cmd = 'lxc-attach '
if path:
full_cmd += '-P {0} '.format(pipes.quote(path))
if keep_env is not True:
full_cmd += '--clear-env '
if 'PATH' not in to_keep:
full_cmd += '--set-var {0} '.format(PATH)
# --clear-env results in a very restrictive PATH
# (/bin:/usr/bin), use a good fallback.
full_cmd += ' '.join(
['--set-var {0}={1}'.format(x, pipes.quote(os.environ[x]))
for x in to_keep
if x in os.environ]
)
full_cmd += ' -n {0} -- {1}'.format(pipes.quote(name), cmd)
elif exec_driver == 'nsenter':
pid = __salt__['{0}.pid'.format(container_type)](name)
full_cmd = (
'nsenter --target {0} --mount --uts --ipc --net --pid -- '
.format(pid)
)
if keep_env is not True:
full_cmd += 'env -i '
if 'PATH' not in to_keep:
full_cmd += '{0} '.format(PATH)
full_cmd += ' '.join(
['{0}={1}'.format(x, pipes.quote(os.environ[x]))
for x in to_keep
if x in os.environ]
)
full_cmd += ' {0}'.format(cmd)
elif exec_driver == 'docker-exec':
# We're using docker exec on the CLI as opposed to via docker-py, since
# the Docker API doesn't return stdout and stderr separately.
full_cmd = 'docker exec '
if stdin:
full_cmd += '-i '
full_cmd += '{0} '.format(name)
if keep_env is not True:
full_cmd += 'env -i '
if 'PATH' not in to_keep:
full_cmd += '{0} '.format(PATH)
full_cmd += ' '.join(
['{0}={1}'.format(x, pipes.quote(os.environ[x]))
for x in to_keep
if x in os.environ]
)
full_cmd += ' {0}'.format(cmd)
if not use_vt:
ret = __salt__[cmd_func](full_cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
else:
stdout, stderr = '', ''
proc = salt.utils.vt.Terminal(
full_cmd,
shell=python_shell,
log_stdin_level='quiet' if output_loglevel == 'quiet' else 'info',
log_stdout_level=output_loglevel,
log_stderr_level=output_loglevel,
log_stdout=True,
log_stderr=True,
stream_stdout=False,
stream_stderr=False
)
# Consume output
try:
while proc.has_unread_data:
try:
cstdout, cstderr = proc.recv()
if cstdout:
stdout += cstdout
if cstderr:
if output is None:
stdout += cstderr
else:
stderr += cstderr
time.sleep(0.5)
except KeyboardInterrupt:
break
ret = stdout if output is None \
else {'retcode': proc.exitstatus,
'pid': 2,
'stdout': stdout,
'stderr': stderr}
except salt.utils.vt.TerminalException:
trace = traceback.format_exc()
log.error(trace)
ret = stdout if output is None \
else {'retcode': 127,
'pid': 2,
'stdout': stdout,
'stderr': stderr}
finally:
proc.terminate()
return ret | [
"def",
"run",
"(",
"name",
",",
"cmd",
",",
"container_type",
"=",
"None",
",",
"exec_driver",
"=",
"None",
",",
"output",
"=",
"None",
",",
"no_start",
"=",
"False",
",",
"stdin",
"=",
"None",
",",
"python_shell",
"=",
"True",
",",
"output_loglevel",
... | Common logic for running shell commands in containers
path
path to the container parent (for LXC only)
default: /var/lib/lxc (system default)
CLI Example:
.. code-block:: bash
salt myminion container_resource.run mycontainer 'ps aux' container_type=docker exec_driver=nsenter output=stdout | [
"Common",
"logic",
"for",
"running",
"shell",
"commands",
"in",
"containers"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/container_resource.py#L118-L266 | train |
saltstack/salt | salt/modules/container_resource.py | copy_to | def copy_to(name,
source,
dest,
container_type=None,
path=None,
exec_driver=None,
overwrite=False,
makedirs=False):
'''
Common logic for copying files to containers
path
path to the container parent (for LXC only)
default: /var/lib/lxc (system default)
CLI Example:
.. code-block:: bash
salt myminion container_resource.copy_to mycontainer /local/file/path /container/file/path container_type=docker exec_driver=nsenter
'''
# Get the appropriate functions
state = __salt__['{0}.state'.format(container_type)]
def run_all(*args, **akwargs):
akwargs = copy.deepcopy(akwargs)
if container_type in ['lxc'] and 'path' not in akwargs:
akwargs['path'] = path
return __salt__['{0}.run_all'.format(container_type)](
*args, **akwargs)
state_kwargs = {}
cmd_kwargs = {'ignore_retcode': True}
if container_type in ['lxc']:
cmd_kwargs['path'] = path
state_kwargs['path'] = path
def _state(name):
if state_kwargs:
return state(name, **state_kwargs)
else:
return state(name)
c_state = _state(name)
if c_state != 'running':
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
local_file = cache_file(source)
source_dir, source_name = os.path.split(local_file)
# Source file sanity checks
if not os.path.isabs(local_file):
raise SaltInvocationError('Source path must be absolute')
elif not os.path.exists(local_file):
raise SaltInvocationError(
'Source file {0} does not exist'.format(local_file)
)
elif not os.path.isfile(local_file):
raise SaltInvocationError('Source must be a regular file')
# Destination file sanity checks
if not os.path.isabs(dest):
raise SaltInvocationError('Destination path must be absolute')
if run_all(name,
'test -d {0}'.format(pipes.quote(dest)),
**cmd_kwargs)['retcode'] == 0:
# Destination is a directory, full path to dest file will include the
# basename of the source file.
dest = os.path.join(dest, source_name)
else:
# Destination was not a directory. We will check to see if the parent
# dir is a directory, and then (if makedirs=True) attempt to create the
# parent directory.
dest_dir, dest_name = os.path.split(dest)
if run_all(name,
'test -d {0}'.format(pipes.quote(dest_dir)),
**cmd_kwargs)['retcode'] != 0:
if makedirs:
result = run_all(name,
'mkdir -p {0}'.format(pipes.quote(dest_dir)),
**cmd_kwargs)
if result['retcode'] != 0:
error = ('Unable to create destination directory {0} in '
'container \'{1}\''.format(dest_dir, name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
else:
raise SaltInvocationError(
'Directory {0} does not exist on {1} container \'{2}\''
.format(dest_dir, container_type, name)
)
if not overwrite and run_all(name,
'test -e {0}'.format(pipes.quote(dest)),
**cmd_kwargs)['retcode'] == 0:
raise CommandExecutionError(
'Destination path {0} already exists. Use overwrite=True to '
'overwrite it'.format(dest)
)
# Before we try to replace the file, compare checksums.
source_md5 = __salt__['file.get_sum'](local_file, 'md5')
if source_md5 == _get_md5(name, dest, run_all):
log.debug('%s and %s:%s are the same file, skipping copy', source, name, dest)
return True
log.debug('Copying %s to %s container \'%s\' as %s',
source, container_type, name, dest)
# Using cat here instead of opening the file, reading it into memory,
# and passing it as stdin to run(). This will keep down memory
# usage for the minion and make the operation run quicker.
if exec_driver == 'lxc-attach':
lxcattach = 'lxc-attach'
if path:
lxcattach += ' -P {0}'.format(pipes.quote(path))
copy_cmd = (
'cat "{0}" | {4} --clear-env --set-var {1} -n {2} -- '
'tee "{3}"'.format(local_file, PATH, name, dest, lxcattach)
)
elif exec_driver == 'nsenter':
pid = __salt__['{0}.pid'.format(container_type)](name)
copy_cmd = (
'cat "{0}" | {1} env -i {2} tee "{3}"'
.format(local_file, _nsenter(pid), PATH, dest)
)
elif exec_driver == 'docker-exec':
copy_cmd = (
'cat "{0}" | docker exec -i {1} env -i {2} tee "{3}"'
.format(local_file, name, PATH, dest)
)
__salt__['cmd.run'](copy_cmd, python_shell=True, output_loglevel='quiet')
return source_md5 == _get_md5(name, dest, run_all) | python | def copy_to(name,
source,
dest,
container_type=None,
path=None,
exec_driver=None,
overwrite=False,
makedirs=False):
'''
Common logic for copying files to containers
path
path to the container parent (for LXC only)
default: /var/lib/lxc (system default)
CLI Example:
.. code-block:: bash
salt myminion container_resource.copy_to mycontainer /local/file/path /container/file/path container_type=docker exec_driver=nsenter
'''
# Get the appropriate functions
state = __salt__['{0}.state'.format(container_type)]
def run_all(*args, **akwargs):
akwargs = copy.deepcopy(akwargs)
if container_type in ['lxc'] and 'path' not in akwargs:
akwargs['path'] = path
return __salt__['{0}.run_all'.format(container_type)](
*args, **akwargs)
state_kwargs = {}
cmd_kwargs = {'ignore_retcode': True}
if container_type in ['lxc']:
cmd_kwargs['path'] = path
state_kwargs['path'] = path
def _state(name):
if state_kwargs:
return state(name, **state_kwargs)
else:
return state(name)
c_state = _state(name)
if c_state != 'running':
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
local_file = cache_file(source)
source_dir, source_name = os.path.split(local_file)
# Source file sanity checks
if not os.path.isabs(local_file):
raise SaltInvocationError('Source path must be absolute')
elif not os.path.exists(local_file):
raise SaltInvocationError(
'Source file {0} does not exist'.format(local_file)
)
elif not os.path.isfile(local_file):
raise SaltInvocationError('Source must be a regular file')
# Destination file sanity checks
if not os.path.isabs(dest):
raise SaltInvocationError('Destination path must be absolute')
if run_all(name,
'test -d {0}'.format(pipes.quote(dest)),
**cmd_kwargs)['retcode'] == 0:
# Destination is a directory, full path to dest file will include the
# basename of the source file.
dest = os.path.join(dest, source_name)
else:
# Destination was not a directory. We will check to see if the parent
# dir is a directory, and then (if makedirs=True) attempt to create the
# parent directory.
dest_dir, dest_name = os.path.split(dest)
if run_all(name,
'test -d {0}'.format(pipes.quote(dest_dir)),
**cmd_kwargs)['retcode'] != 0:
if makedirs:
result = run_all(name,
'mkdir -p {0}'.format(pipes.quote(dest_dir)),
**cmd_kwargs)
if result['retcode'] != 0:
error = ('Unable to create destination directory {0} in '
'container \'{1}\''.format(dest_dir, name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
else:
raise SaltInvocationError(
'Directory {0} does not exist on {1} container \'{2}\''
.format(dest_dir, container_type, name)
)
if not overwrite and run_all(name,
'test -e {0}'.format(pipes.quote(dest)),
**cmd_kwargs)['retcode'] == 0:
raise CommandExecutionError(
'Destination path {0} already exists. Use overwrite=True to '
'overwrite it'.format(dest)
)
# Before we try to replace the file, compare checksums.
source_md5 = __salt__['file.get_sum'](local_file, 'md5')
if source_md5 == _get_md5(name, dest, run_all):
log.debug('%s and %s:%s are the same file, skipping copy', source, name, dest)
return True
log.debug('Copying %s to %s container \'%s\' as %s',
source, container_type, name, dest)
# Using cat here instead of opening the file, reading it into memory,
# and passing it as stdin to run(). This will keep down memory
# usage for the minion and make the operation run quicker.
if exec_driver == 'lxc-attach':
lxcattach = 'lxc-attach'
if path:
lxcattach += ' -P {0}'.format(pipes.quote(path))
copy_cmd = (
'cat "{0}" | {4} --clear-env --set-var {1} -n {2} -- '
'tee "{3}"'.format(local_file, PATH, name, dest, lxcattach)
)
elif exec_driver == 'nsenter':
pid = __salt__['{0}.pid'.format(container_type)](name)
copy_cmd = (
'cat "{0}" | {1} env -i {2} tee "{3}"'
.format(local_file, _nsenter(pid), PATH, dest)
)
elif exec_driver == 'docker-exec':
copy_cmd = (
'cat "{0}" | docker exec -i {1} env -i {2} tee "{3}"'
.format(local_file, name, PATH, dest)
)
__salt__['cmd.run'](copy_cmd, python_shell=True, output_loglevel='quiet')
return source_md5 == _get_md5(name, dest, run_all) | [
"def",
"copy_to",
"(",
"name",
",",
"source",
",",
"dest",
",",
"container_type",
"=",
"None",
",",
"path",
"=",
"None",
",",
"exec_driver",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"makedirs",
"=",
"False",
")",
":",
"# Get the appropriate functi... | Common logic for copying files to containers
path
path to the container parent (for LXC only)
default: /var/lib/lxc (system default)
CLI Example:
.. code-block:: bash
salt myminion container_resource.copy_to mycontainer /local/file/path /container/file/path container_type=docker exec_driver=nsenter | [
"Common",
"logic",
"for",
"copying",
"files",
"to",
"containers"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/container_resource.py#L270-L404 | train |
saltstack/salt | salt/executors/docker.py | execute | def execute(opts, data, func, args, kwargs):
'''
Directly calls the given function with arguments
'''
if data['fun'] == 'saltutil.find_job':
return __executors__['direct_call.execute'](opts, data, func, args, kwargs)
if data['fun'] in DOCKER_MOD_MAP:
return __executors__['direct_call.execute'](opts, data, __salt__[DOCKER_MOD_MAP[data['fun']]], [opts['proxy']['name']] + args, kwargs)
return __salt__['docker.call'](opts['proxy']['name'], data['fun'], *args, **kwargs) | python | def execute(opts, data, func, args, kwargs):
'''
Directly calls the given function with arguments
'''
if data['fun'] == 'saltutil.find_job':
return __executors__['direct_call.execute'](opts, data, func, args, kwargs)
if data['fun'] in DOCKER_MOD_MAP:
return __executors__['direct_call.execute'](opts, data, __salt__[DOCKER_MOD_MAP[data['fun']]], [opts['proxy']['name']] + args, kwargs)
return __salt__['docker.call'](opts['proxy']['name'], data['fun'], *args, **kwargs) | [
"def",
"execute",
"(",
"opts",
",",
"data",
",",
"func",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"data",
"[",
"'fun'",
"]",
"==",
"'saltutil.find_job'",
":",
"return",
"__executors__",
"[",
"'direct_call.execute'",
"]",
"(",
"opts",
",",
"data",
",",... | Directly calls the given function with arguments | [
"Directly",
"calls",
"the",
"given",
"function",
"with",
"arguments"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/executors/docker.py#L28-L36 | train |
saltstack/salt | salt/cli/salt.py | SaltCMD.run | def run(self):
'''
Execute the salt command line
'''
import salt.client
self.parse_args()
if self.config['log_level'] not in ('quiet', ):
# Setup file logging!
self.setup_logfile_logger()
verify_log(self.config)
try:
# We don't need to bail on config file permission errors
# if the CLI process is run with the -a flag
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 SaltClientError as exc:
self.exit(2, '{0}\n'.format(exc))
return
if self.options.batch or self.options.static:
# _run_batch() will handle all output and
# exit with the appropriate error condition
# Execution will not continue past this point
# in batch mode.
self._run_batch()
return
if self.options.preview_target:
minion_list = self._preview_target()
self._output_ret(minion_list, self.config.get('output', 'nested'))
return
if self.options.timeout <= 0:
self.options.timeout = self.local_client.opts['timeout']
kwargs = {
'tgt': self.config['tgt'],
'fun': self.config['fun'],
'arg': self.config['arg'],
'timeout': self.options.timeout,
'show_timeout': self.options.show_timeout,
'show_jid': self.options.show_jid}
if 'token' in self.config:
import salt.utils.files
try:
with salt.utils.files.fopen(os.path.join(self.config['cachedir'], '.root_key'), 'r') as fp_:
kwargs['key'] = fp_.readline()
except IOError:
kwargs['token'] = self.config['token']
kwargs['delimiter'] = self.options.delimiter
if self.selected_target_option:
kwargs['tgt_type'] = self.selected_target_option
else:
kwargs['tgt_type'] = 'glob'
# If batch_safe_limit is set, check minions matching target and
# potentially switch to batch execution
if self.options.batch_safe_limit > 1:
if len(self._preview_target()) >= self.options.batch_safe_limit:
salt.utils.stringutils.print_cli('\nNOTICE: Too many minions targeted, switching to batch execution.')
self.options.batch = self.options.batch_safe_size
self._run_batch()
return
if getattr(self.options, 'return'):
kwargs['ret'] = getattr(self.options, 'return')
if getattr(self.options, 'return_config'):
kwargs['ret_config'] = getattr(self.options, 'return_config')
if getattr(self.options, 'return_kwargs'):
kwargs['ret_kwargs'] = yamlify_arg(
getattr(self.options, 'return_kwargs'))
if getattr(self.options, 'module_executors'):
kwargs['module_executors'] = yamlify_arg(getattr(self.options, 'module_executors'))
if getattr(self.options, 'executor_opts'):
kwargs['executor_opts'] = yamlify_arg(getattr(self.options, 'executor_opts'))
if getattr(self.options, 'metadata'):
kwargs['metadata'] = yamlify_arg(
getattr(self.options, 'metadata'))
# If using eauth and a token hasn't already been loaded into
# kwargs, prompt the user to enter auth credentials
if 'token' not in kwargs and 'key' not in kwargs and self.options.eauth:
# This is expensive. Don't do it unless we need to.
import salt.auth
resolver = salt.auth.Resolver(self.config)
res = resolver.cli(self.options.eauth)
if self.options.mktoken and res:
tok = resolver.token_cli(
self.options.eauth,
res
)
if tok:
kwargs['token'] = tok.get('token', '')
if not res:
sys.stderr.write('ERROR: Authentication failed\n')
sys.exit(2)
kwargs.update(res)
kwargs['eauth'] = self.options.eauth
if self.config['async']:
jid = self.local_client.cmd_async(**kwargs)
salt.utils.stringutils.print_cli('Executed command with job ID: {0}'.format(jid))
return
# local will be None when there was an error
if not self.local_client:
return
retcodes = []
errors = []
try:
if self.options.subset:
cmd_func = self.local_client.cmd_subset
kwargs['sub'] = self.options.subset
kwargs['cli'] = True
else:
cmd_func = self.local_client.cmd_cli
if self.options.progress:
kwargs['progress'] = True
self.config['progress'] = True
ret = {}
for progress in cmd_func(**kwargs):
out = 'progress'
try:
self._progress_ret(progress, out)
except LoaderError as exc:
raise SaltSystemExit(exc)
if 'return_count' not in progress:
ret.update(progress)
self._progress_end(out)
self._print_returns_summary(ret)
elif self.config['fun'] == 'sys.doc':
ret = {}
out = ''
for full_ret in self.local_client.cmd_cli(**kwargs):
ret_, out, retcode = self._format_ret(full_ret)
ret.update(ret_)
self._output_ret(ret, out, retcode=retcode)
else:
if self.options.verbose:
kwargs['verbose'] = True
ret = {}
for full_ret in cmd_func(**kwargs):
try:
ret_, out, retcode = self._format_ret(full_ret)
retcodes.append(retcode)
self._output_ret(ret_, out, retcode=retcode)
ret.update(full_ret)
except KeyError:
errors.append(full_ret)
# Returns summary
if self.config['cli_summary'] is True:
if self.config['fun'] != 'sys.doc':
if self.options.output is None:
self._print_returns_summary(ret)
self._print_errors_summary(errors)
# NOTE: Return code is set here based on if all minions
# returned 'ok' with a retcode of 0.
# This is the final point before the 'salt' cmd returns,
# which is why we set the retcode here.
if not all(exit_code == salt.defaults.exitcodes.EX_OK for exit_code in retcodes):
sys.stderr.write('ERROR: Minions returned with non-zero exit code\n')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except (AuthenticationError,
AuthorizationError,
SaltInvocationError,
EauthAuthenticationError,
SaltClientError) as exc:
ret = six.text_type(exc)
self._output_ret(ret, '', retcode=1) | python | def run(self):
'''
Execute the salt command line
'''
import salt.client
self.parse_args()
if self.config['log_level'] not in ('quiet', ):
# Setup file logging!
self.setup_logfile_logger()
verify_log(self.config)
try:
# We don't need to bail on config file permission errors
# if the CLI process is run with the -a flag
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 SaltClientError as exc:
self.exit(2, '{0}\n'.format(exc))
return
if self.options.batch or self.options.static:
# _run_batch() will handle all output and
# exit with the appropriate error condition
# Execution will not continue past this point
# in batch mode.
self._run_batch()
return
if self.options.preview_target:
minion_list = self._preview_target()
self._output_ret(minion_list, self.config.get('output', 'nested'))
return
if self.options.timeout <= 0:
self.options.timeout = self.local_client.opts['timeout']
kwargs = {
'tgt': self.config['tgt'],
'fun': self.config['fun'],
'arg': self.config['arg'],
'timeout': self.options.timeout,
'show_timeout': self.options.show_timeout,
'show_jid': self.options.show_jid}
if 'token' in self.config:
import salt.utils.files
try:
with salt.utils.files.fopen(os.path.join(self.config['cachedir'], '.root_key'), 'r') as fp_:
kwargs['key'] = fp_.readline()
except IOError:
kwargs['token'] = self.config['token']
kwargs['delimiter'] = self.options.delimiter
if self.selected_target_option:
kwargs['tgt_type'] = self.selected_target_option
else:
kwargs['tgt_type'] = 'glob'
# If batch_safe_limit is set, check minions matching target and
# potentially switch to batch execution
if self.options.batch_safe_limit > 1:
if len(self._preview_target()) >= self.options.batch_safe_limit:
salt.utils.stringutils.print_cli('\nNOTICE: Too many minions targeted, switching to batch execution.')
self.options.batch = self.options.batch_safe_size
self._run_batch()
return
if getattr(self.options, 'return'):
kwargs['ret'] = getattr(self.options, 'return')
if getattr(self.options, 'return_config'):
kwargs['ret_config'] = getattr(self.options, 'return_config')
if getattr(self.options, 'return_kwargs'):
kwargs['ret_kwargs'] = yamlify_arg(
getattr(self.options, 'return_kwargs'))
if getattr(self.options, 'module_executors'):
kwargs['module_executors'] = yamlify_arg(getattr(self.options, 'module_executors'))
if getattr(self.options, 'executor_opts'):
kwargs['executor_opts'] = yamlify_arg(getattr(self.options, 'executor_opts'))
if getattr(self.options, 'metadata'):
kwargs['metadata'] = yamlify_arg(
getattr(self.options, 'metadata'))
# If using eauth and a token hasn't already been loaded into
# kwargs, prompt the user to enter auth credentials
if 'token' not in kwargs and 'key' not in kwargs and self.options.eauth:
# This is expensive. Don't do it unless we need to.
import salt.auth
resolver = salt.auth.Resolver(self.config)
res = resolver.cli(self.options.eauth)
if self.options.mktoken and res:
tok = resolver.token_cli(
self.options.eauth,
res
)
if tok:
kwargs['token'] = tok.get('token', '')
if not res:
sys.stderr.write('ERROR: Authentication failed\n')
sys.exit(2)
kwargs.update(res)
kwargs['eauth'] = self.options.eauth
if self.config['async']:
jid = self.local_client.cmd_async(**kwargs)
salt.utils.stringutils.print_cli('Executed command with job ID: {0}'.format(jid))
return
# local will be None when there was an error
if not self.local_client:
return
retcodes = []
errors = []
try:
if self.options.subset:
cmd_func = self.local_client.cmd_subset
kwargs['sub'] = self.options.subset
kwargs['cli'] = True
else:
cmd_func = self.local_client.cmd_cli
if self.options.progress:
kwargs['progress'] = True
self.config['progress'] = True
ret = {}
for progress in cmd_func(**kwargs):
out = 'progress'
try:
self._progress_ret(progress, out)
except LoaderError as exc:
raise SaltSystemExit(exc)
if 'return_count' not in progress:
ret.update(progress)
self._progress_end(out)
self._print_returns_summary(ret)
elif self.config['fun'] == 'sys.doc':
ret = {}
out = ''
for full_ret in self.local_client.cmd_cli(**kwargs):
ret_, out, retcode = self._format_ret(full_ret)
ret.update(ret_)
self._output_ret(ret, out, retcode=retcode)
else:
if self.options.verbose:
kwargs['verbose'] = True
ret = {}
for full_ret in cmd_func(**kwargs):
try:
ret_, out, retcode = self._format_ret(full_ret)
retcodes.append(retcode)
self._output_ret(ret_, out, retcode=retcode)
ret.update(full_ret)
except KeyError:
errors.append(full_ret)
# Returns summary
if self.config['cli_summary'] is True:
if self.config['fun'] != 'sys.doc':
if self.options.output is None:
self._print_returns_summary(ret)
self._print_errors_summary(errors)
# NOTE: Return code is set here based on if all minions
# returned 'ok' with a retcode of 0.
# This is the final point before the 'salt' cmd returns,
# which is why we set the retcode here.
if not all(exit_code == salt.defaults.exitcodes.EX_OK for exit_code in retcodes):
sys.stderr.write('ERROR: Minions returned with non-zero exit code\n')
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except (AuthenticationError,
AuthorizationError,
SaltInvocationError,
EauthAuthenticationError,
SaltClientError) as exc:
ret = six.text_type(exc)
self._output_ret(ret, '', retcode=1) | [
"def",
"run",
"(",
"self",
")",
":",
"import",
"salt",
".",
"client",
"self",
".",
"parse_args",
"(",
")",
"if",
"self",
".",
"config",
"[",
"'log_level'",
"]",
"not",
"in",
"(",
"'quiet'",
",",
")",
":",
"# Setup file logging!",
"self",
".",
"setup_lo... | Execute the salt command line | [
"Execute",
"the",
"salt",
"command",
"line"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/salt.py#L36-L224 | train |
saltstack/salt | salt/cli/salt.py | SaltCMD._print_returns_summary | def _print_returns_summary(self, ret):
'''
Display returns summary
'''
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 = ret[each_minion].get('ret')
if (
isinstance(minion_ret, six.string_types)
and minion_ret.startswith("Minion did not return")
):
if "Not connected" in minion_ret:
not_connected_minions.append(each_minion)
elif "No response" in minion_ret:
not_response_minions.append(each_minion)
not_return_counter += 1
not_return_minions.append(each_minion)
else:
return_counter += 1
if self._get_retcode(ret[each_minion]):
failed_minions.append(each_minion)
salt.utils.stringutils.print_cli('\n')
salt.utils.stringutils.print_cli('-------------------------------------------')
salt.utils.stringutils.print_cli('Summary')
salt.utils.stringutils.print_cli('-------------------------------------------')
salt.utils.stringutils.print_cli('# of minions targeted: {0}'.format(return_counter + not_return_counter))
salt.utils.stringutils.print_cli('# of minions returned: {0}'.format(return_counter))
salt.utils.stringutils.print_cli('# of minions that did not return: {0}'.format(not_return_counter))
salt.utils.stringutils.print_cli('# of minions with errors: {0}'.format(len(failed_minions)))
if self.options.verbose:
if not_connected_minions:
salt.utils.stringutils.print_cli('Minions not connected: {0}'.format(" ".join(not_connected_minions)))
if not_response_minions:
salt.utils.stringutils.print_cli('Minions not responding: {0}'.format(" ".join(not_response_minions)))
if failed_minions:
salt.utils.stringutils.print_cli('Minions with failures: {0}'.format(" ".join(failed_minions)))
salt.utils.stringutils.print_cli('-------------------------------------------') | python | def _print_returns_summary(self, ret):
'''
Display returns summary
'''
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 = ret[each_minion].get('ret')
if (
isinstance(minion_ret, six.string_types)
and minion_ret.startswith("Minion did not return")
):
if "Not connected" in minion_ret:
not_connected_minions.append(each_minion)
elif "No response" in minion_ret:
not_response_minions.append(each_minion)
not_return_counter += 1
not_return_minions.append(each_minion)
else:
return_counter += 1
if self._get_retcode(ret[each_minion]):
failed_minions.append(each_minion)
salt.utils.stringutils.print_cli('\n')
salt.utils.stringutils.print_cli('-------------------------------------------')
salt.utils.stringutils.print_cli('Summary')
salt.utils.stringutils.print_cli('-------------------------------------------')
salt.utils.stringutils.print_cli('# of minions targeted: {0}'.format(return_counter + not_return_counter))
salt.utils.stringutils.print_cli('# of minions returned: {0}'.format(return_counter))
salt.utils.stringutils.print_cli('# of minions that did not return: {0}'.format(not_return_counter))
salt.utils.stringutils.print_cli('# of minions with errors: {0}'.format(len(failed_minions)))
if self.options.verbose:
if not_connected_minions:
salt.utils.stringutils.print_cli('Minions not connected: {0}'.format(" ".join(not_connected_minions)))
if not_response_minions:
salt.utils.stringutils.print_cli('Minions not responding: {0}'.format(" ".join(not_response_minions)))
if failed_minions:
salt.utils.stringutils.print_cli('Minions with failures: {0}'.format(" ".join(failed_minions)))
salt.utils.stringutils.print_cli('-------------------------------------------') | [
"def",
"_print_returns_summary",
"(",
"self",
",",
"ret",
")",
":",
"return_counter",
"=",
"0",
"not_return_counter",
"=",
"0",
"not_return_minions",
"=",
"[",
"]",
"not_response_minions",
"=",
"[",
"]",
"not_connected_minions",
"=",
"[",
"]",
"failed_minions",
... | Display returns summary | [
"Display",
"returns",
"summary"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/salt.py#L301-L344 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.