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/modules/selinux.py | install_semod | def install_semod(module_path):
'''
Install custom SELinux module from file
CLI Example:
.. code-block:: bash
salt '*' selinux.install_semod [salt://]path/to/module.pp
.. versionadded:: 2016.11.6
'''
if module_path.find('salt://') == 0:
module_path = __salt__['cp.cache_file'](module_path)
cmd = 'semodule -i {0}'.format(module_path)
return not __salt__['cmd.retcode'](cmd) | python | def install_semod(module_path):
'''
Install custom SELinux module from file
CLI Example:
.. code-block:: bash
salt '*' selinux.install_semod [salt://]path/to/module.pp
.. versionadded:: 2016.11.6
'''
if module_path.find('salt://') == 0:
module_path = __salt__['cp.cache_file'](module_path)
cmd = 'semodule -i {0}'.format(module_path)
return not __salt__['cmd.retcode'](cmd) | [
"def",
"install_semod",
"(",
"module_path",
")",
":",
"if",
"module_path",
".",
"find",
"(",
"'salt://'",
")",
"==",
"0",
":",
"module_path",
"=",
"__salt__",
"[",
"'cp.cache_file'",
"]",
"(",
"module_path",
")",
"cmd",
"=",
"'semodule -i {0}'",
".",
"format... | Install custom SELinux module from file
CLI Example:
.. code-block:: bash
salt '*' selinux.install_semod [salt://]path/to/module.pp
.. versionadded:: 2016.11.6 | [
"Install",
"custom",
"SELinux",
"module",
"from",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L297-L312 | train |
saltstack/salt | salt/modules/selinux.py | list_semod | def list_semod():
'''
Return a structure listing all of the selinux modules on the system and
what state they are in
CLI Example:
.. code-block:: bash
salt '*' selinux.list_semod
.. versionadded:: 2016.3.0
'''
helptext = __salt__['cmd.run']('semodule -h').splitlines()
semodule_version = ''
for line in helptext:
if line.strip().startswith('full'):
semodule_version = 'new'
if semodule_version == 'new':
mdata = __salt__['cmd.run']('semodule -lfull').splitlines()
ret = {}
for line in mdata:
if not line.strip():
continue
comps = line.split()
if len(comps) == 4:
ret[comps[1]] = {'Enabled': False,
'Version': None}
else:
ret[comps[1]] = {'Enabled': True,
'Version': None}
else:
mdata = __salt__['cmd.run']('semodule -l').splitlines()
ret = {}
for line in mdata:
if not line.strip():
continue
comps = line.split()
if len(comps) == 3:
ret[comps[0]] = {'Enabled': False,
'Version': comps[1]}
else:
ret[comps[0]] = {'Enabled': True,
'Version': comps[1]}
return ret | python | def list_semod():
'''
Return a structure listing all of the selinux modules on the system and
what state they are in
CLI Example:
.. code-block:: bash
salt '*' selinux.list_semod
.. versionadded:: 2016.3.0
'''
helptext = __salt__['cmd.run']('semodule -h').splitlines()
semodule_version = ''
for line in helptext:
if line.strip().startswith('full'):
semodule_version = 'new'
if semodule_version == 'new':
mdata = __salt__['cmd.run']('semodule -lfull').splitlines()
ret = {}
for line in mdata:
if not line.strip():
continue
comps = line.split()
if len(comps) == 4:
ret[comps[1]] = {'Enabled': False,
'Version': None}
else:
ret[comps[1]] = {'Enabled': True,
'Version': None}
else:
mdata = __salt__['cmd.run']('semodule -l').splitlines()
ret = {}
for line in mdata:
if not line.strip():
continue
comps = line.split()
if len(comps) == 3:
ret[comps[0]] = {'Enabled': False,
'Version': comps[1]}
else:
ret[comps[0]] = {'Enabled': True,
'Version': comps[1]}
return ret | [
"def",
"list_semod",
"(",
")",
":",
"helptext",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'semodule -h'",
")",
".",
"splitlines",
"(",
")",
"semodule_version",
"=",
"''",
"for",
"line",
"in",
"helptext",
":",
"if",
"line",
".",
"strip",
"(",
")",
"... | Return a structure listing all of the selinux modules on the system and
what state they are in
CLI Example:
.. code-block:: bash
salt '*' selinux.list_semod
.. versionadded:: 2016.3.0 | [
"Return",
"a",
"structure",
"listing",
"all",
"of",
"the",
"selinux",
"modules",
"on",
"the",
"system",
"and",
"what",
"state",
"they",
"are",
"in"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L331-L376 | train |
saltstack/salt | salt/modules/selinux.py | _parse_protocol_port | def _parse_protocol_port(name, protocol, port):
'''
.. versionadded:: 2019.2.0
Validates and parses the protocol and port/port range from the name
if both protocol and port are not provided.
If the name is in a valid format, the protocol and port are ignored if provided
Examples: tcp/8080 or udp/20-21
'''
protocol_port_pattern = r'^(tcp|udp)\/(([\d]+)\-?[\d]+)$'
name_parts = re.match(protocol_port_pattern, name)
if not name_parts:
name_parts = re.match(protocol_port_pattern, '{0}/{1}'.format(protocol, port))
if not name_parts:
raise SaltInvocationError(
'Invalid name "{0}" format and protocol and port not provided or invalid: "{1}" "{2}".'.format(
name, protocol, port))
return name_parts.group(1), name_parts.group(2) | python | def _parse_protocol_port(name, protocol, port):
'''
.. versionadded:: 2019.2.0
Validates and parses the protocol and port/port range from the name
if both protocol and port are not provided.
If the name is in a valid format, the protocol and port are ignored if provided
Examples: tcp/8080 or udp/20-21
'''
protocol_port_pattern = r'^(tcp|udp)\/(([\d]+)\-?[\d]+)$'
name_parts = re.match(protocol_port_pattern, name)
if not name_parts:
name_parts = re.match(protocol_port_pattern, '{0}/{1}'.format(protocol, port))
if not name_parts:
raise SaltInvocationError(
'Invalid name "{0}" format and protocol and port not provided or invalid: "{1}" "{2}".'.format(
name, protocol, port))
return name_parts.group(1), name_parts.group(2) | [
"def",
"_parse_protocol_port",
"(",
"name",
",",
"protocol",
",",
"port",
")",
":",
"protocol_port_pattern",
"=",
"r'^(tcp|udp)\\/(([\\d]+)\\-?[\\d]+)$'",
"name_parts",
"=",
"re",
".",
"match",
"(",
"protocol_port_pattern",
",",
"name",
")",
"if",
"not",
"name_parts... | .. versionadded:: 2019.2.0
Validates and parses the protocol and port/port range from the name
if both protocol and port are not provided.
If the name is in a valid format, the protocol and port are ignored if provided
Examples: tcp/8080 or udp/20-21 | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L391-L410 | train |
saltstack/salt | salt/modules/selinux.py | _context_string_to_dict | def _context_string_to_dict(context):
'''
.. versionadded:: 2017.7.0
Converts an SELinux file context from string to dict.
'''
if not re.match('[^:]+:[^:]+:[^:]+:[^:]+$', context):
raise SaltInvocationError('Invalid SELinux context string: {0}. ' +
'Expected "sel_user:sel_role:sel_type:sel_level"')
context_list = context.split(':', 3)
ret = {}
for index, value in enumerate(['sel_user', 'sel_role', 'sel_type', 'sel_level']):
ret[value] = context_list[index]
return ret | python | def _context_string_to_dict(context):
'''
.. versionadded:: 2017.7.0
Converts an SELinux file context from string to dict.
'''
if not re.match('[^:]+:[^:]+:[^:]+:[^:]+$', context):
raise SaltInvocationError('Invalid SELinux context string: {0}. ' +
'Expected "sel_user:sel_role:sel_type:sel_level"')
context_list = context.split(':', 3)
ret = {}
for index, value in enumerate(['sel_user', 'sel_role', 'sel_type', 'sel_level']):
ret[value] = context_list[index]
return ret | [
"def",
"_context_string_to_dict",
"(",
"context",
")",
":",
"if",
"not",
"re",
".",
"match",
"(",
"'[^:]+:[^:]+:[^:]+:[^:]+$'",
",",
"context",
")",
":",
"raise",
"SaltInvocationError",
"(",
"'Invalid SELinux context string: {0}. '",
"+",
"'Expected \"sel_user:sel_role:se... | .. versionadded:: 2017.7.0
Converts an SELinux file context from string to dict. | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L422-L435 | train |
saltstack/salt | salt/modules/selinux.py | fcontext_get_policy | def fcontext_get_policy(name, filetype=None, sel_type=None, sel_user=None, sel_level=None):
'''
.. versionadded:: 2017.7.0
Returns the current entry in the SELinux policy list as a
dictionary. Returns None if no exact match was found.
Returned keys are:
* filespec (the name supplied and matched)
* filetype (the descriptive name of the filetype supplied)
* sel_user, sel_role, sel_type, sel_level (the selinux context)
For a more in-depth explanation of the selinux context, go to
https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Security-Enhanced_Linux/chap-Security-Enhanced_Linux-SELinux_Contexts.html
name
filespec of the file or directory. Regex syntax is allowed.
filetype
The SELinux filetype specification. Use one of [a, f, d, c, b,
s, l, p]. See also `man semanage-fcontext`. Defaults to 'a'
(all files).
CLI Example:
.. code-block:: bash
salt '*' selinux.fcontext_get_policy my-policy
'''
if filetype:
_validate_filetype(filetype)
re_spacer = '[ ]+'
cmd_kwargs = {'spacer': re_spacer,
'filespec': re.escape(name),
'sel_user': sel_user or '[^:]+',
'sel_role': '[^:]+', # se_role for file context is always object_r
'sel_type': sel_type or '[^:]+',
'sel_level': sel_level or '[^:]+'}
cmd_kwargs['filetype'] = '[[:alpha:] ]+' if filetype is None else filetype_id_to_string(filetype)
cmd = 'semanage fcontext -l | egrep ' + \
"'^{filespec}{spacer}{filetype}{spacer}{sel_user}:{sel_role}:{sel_type}:{sel_level}$'".format(**cmd_kwargs)
current_entry_text = __salt__['cmd.shell'](cmd, ignore_retcode=True)
if current_entry_text == '':
return None
parts = re.match(r'^({filespec}) +([a-z ]+) (.*)$'.format(**{'filespec': re.escape(name)}), current_entry_text)
ret = {
'filespec': parts.group(1).strip(),
'filetype': parts.group(2).strip(),
}
ret.update(_context_string_to_dict(parts.group(3).strip()))
return ret | python | def fcontext_get_policy(name, filetype=None, sel_type=None, sel_user=None, sel_level=None):
'''
.. versionadded:: 2017.7.0
Returns the current entry in the SELinux policy list as a
dictionary. Returns None if no exact match was found.
Returned keys are:
* filespec (the name supplied and matched)
* filetype (the descriptive name of the filetype supplied)
* sel_user, sel_role, sel_type, sel_level (the selinux context)
For a more in-depth explanation of the selinux context, go to
https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Security-Enhanced_Linux/chap-Security-Enhanced_Linux-SELinux_Contexts.html
name
filespec of the file or directory. Regex syntax is allowed.
filetype
The SELinux filetype specification. Use one of [a, f, d, c, b,
s, l, p]. See also `man semanage-fcontext`. Defaults to 'a'
(all files).
CLI Example:
.. code-block:: bash
salt '*' selinux.fcontext_get_policy my-policy
'''
if filetype:
_validate_filetype(filetype)
re_spacer = '[ ]+'
cmd_kwargs = {'spacer': re_spacer,
'filespec': re.escape(name),
'sel_user': sel_user or '[^:]+',
'sel_role': '[^:]+', # se_role for file context is always object_r
'sel_type': sel_type or '[^:]+',
'sel_level': sel_level or '[^:]+'}
cmd_kwargs['filetype'] = '[[:alpha:] ]+' if filetype is None else filetype_id_to_string(filetype)
cmd = 'semanage fcontext -l | egrep ' + \
"'^{filespec}{spacer}{filetype}{spacer}{sel_user}:{sel_role}:{sel_type}:{sel_level}$'".format(**cmd_kwargs)
current_entry_text = __salt__['cmd.shell'](cmd, ignore_retcode=True)
if current_entry_text == '':
return None
parts = re.match(r'^({filespec}) +([a-z ]+) (.*)$'.format(**{'filespec': re.escape(name)}), current_entry_text)
ret = {
'filespec': parts.group(1).strip(),
'filetype': parts.group(2).strip(),
}
ret.update(_context_string_to_dict(parts.group(3).strip()))
return ret | [
"def",
"fcontext_get_policy",
"(",
"name",
",",
"filetype",
"=",
"None",
",",
"sel_type",
"=",
"None",
",",
"sel_user",
"=",
"None",
",",
"sel_level",
"=",
"None",
")",
":",
"if",
"filetype",
":",
"_validate_filetype",
"(",
"filetype",
")",
"re_spacer",
"=... | .. versionadded:: 2017.7.0
Returns the current entry in the SELinux policy list as a
dictionary. Returns None if no exact match was found.
Returned keys are:
* filespec (the name supplied and matched)
* filetype (the descriptive name of the filetype supplied)
* sel_user, sel_role, sel_type, sel_level (the selinux context)
For a more in-depth explanation of the selinux context, go to
https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Security-Enhanced_Linux/chap-Security-Enhanced_Linux-SELinux_Contexts.html
name
filespec of the file or directory. Regex syntax is allowed.
filetype
The SELinux filetype specification. Use one of [a, f, d, c, b,
s, l, p]. See also `man semanage-fcontext`. Defaults to 'a'
(all files).
CLI Example:
.. code-block:: bash
salt '*' selinux.fcontext_get_policy my-policy | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L450-L503 | train |
saltstack/salt | salt/modules/selinux.py | fcontext_add_policy | def fcontext_add_policy(name, filetype=None, sel_type=None, sel_user=None, sel_level=None):
'''
.. versionadded:: 2019.2.0
Adds the SELinux policy for a given filespec and other optional parameters.
Returns the result of the call to semanage.
Note that you don't have to remove an entry before setting a new
one for a given filespec and filetype, as adding one with semanage
automatically overwrites a previously configured SELinux context.
name
filespec of the file or directory. Regex syntax is allowed.
file_type
The SELinux filetype specification. Use one of [a, f, d, c, b,
s, l, p]. See also ``man semanage-fcontext``. Defaults to 'a'
(all files).
sel_type
SELinux context type. There are many.
sel_user
SELinux user. Use ``semanage login -l`` to determine which ones
are available to you.
sel_level
The MLS range of the SELinux context.
CLI Example:
.. code-block:: bash
salt '*' selinux.fcontext_add_policy my-policy
'''
return _fcontext_add_or_delete_policy('add', name, filetype, sel_type, sel_user, sel_level) | python | def fcontext_add_policy(name, filetype=None, sel_type=None, sel_user=None, sel_level=None):
'''
.. versionadded:: 2019.2.0
Adds the SELinux policy for a given filespec and other optional parameters.
Returns the result of the call to semanage.
Note that you don't have to remove an entry before setting a new
one for a given filespec and filetype, as adding one with semanage
automatically overwrites a previously configured SELinux context.
name
filespec of the file or directory. Regex syntax is allowed.
file_type
The SELinux filetype specification. Use one of [a, f, d, c, b,
s, l, p]. See also ``man semanage-fcontext``. Defaults to 'a'
(all files).
sel_type
SELinux context type. There are many.
sel_user
SELinux user. Use ``semanage login -l`` to determine which ones
are available to you.
sel_level
The MLS range of the SELinux context.
CLI Example:
.. code-block:: bash
salt '*' selinux.fcontext_add_policy my-policy
'''
return _fcontext_add_or_delete_policy('add', name, filetype, sel_type, sel_user, sel_level) | [
"def",
"fcontext_add_policy",
"(",
"name",
",",
"filetype",
"=",
"None",
",",
"sel_type",
"=",
"None",
",",
"sel_user",
"=",
"None",
",",
"sel_level",
"=",
"None",
")",
":",
"return",
"_fcontext_add_or_delete_policy",
"(",
"'add'",
",",
"name",
",",
"filetyp... | .. versionadded:: 2019.2.0
Adds the SELinux policy for a given filespec and other optional parameters.
Returns the result of the call to semanage.
Note that you don't have to remove an entry before setting a new
one for a given filespec and filetype, as adding one with semanage
automatically overwrites a previously configured SELinux context.
name
filespec of the file or directory. Regex syntax is allowed.
file_type
The SELinux filetype specification. Use one of [a, f, d, c, b,
s, l, p]. See also ``man semanage-fcontext``. Defaults to 'a'
(all files).
sel_type
SELinux context type. There are many.
sel_user
SELinux user. Use ``semanage login -l`` to determine which ones
are available to you.
sel_level
The MLS range of the SELinux context.
CLI Example:
.. code-block:: bash
salt '*' selinux.fcontext_add_policy my-policy | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L506-L542 | train |
saltstack/salt | salt/modules/selinux.py | fcontext_delete_policy | def fcontext_delete_policy(name, filetype=None, sel_type=None, sel_user=None, sel_level=None):
'''
.. versionadded:: 2019.2.0
Deletes the SELinux policy for a given filespec and other optional parameters.
Returns the result of the call to semanage.
Note that you don't have to remove an entry before setting a new
one for a given filespec and filetype, as adding one with semanage
automatically overwrites a previously configured SELinux context.
name
filespec of the file or directory. Regex syntax is allowed.
file_type
The SELinux filetype specification. Use one of [a, f, d, c, b,
s, l, p]. See also ``man semanage-fcontext``. Defaults to 'a'
(all files).
sel_type
SELinux context type. There are many.
sel_user
SELinux user. Use ``semanage login -l`` to determine which ones
are available to you.
sel_level
The MLS range of the SELinux context.
CLI Example:
.. code-block:: bash
salt '*' selinux.fcontext_delete_policy my-policy
'''
return _fcontext_add_or_delete_policy('delete', name, filetype, sel_type, sel_user, sel_level) | python | def fcontext_delete_policy(name, filetype=None, sel_type=None, sel_user=None, sel_level=None):
'''
.. versionadded:: 2019.2.0
Deletes the SELinux policy for a given filespec and other optional parameters.
Returns the result of the call to semanage.
Note that you don't have to remove an entry before setting a new
one for a given filespec and filetype, as adding one with semanage
automatically overwrites a previously configured SELinux context.
name
filespec of the file or directory. Regex syntax is allowed.
file_type
The SELinux filetype specification. Use one of [a, f, d, c, b,
s, l, p]. See also ``man semanage-fcontext``. Defaults to 'a'
(all files).
sel_type
SELinux context type. There are many.
sel_user
SELinux user. Use ``semanage login -l`` to determine which ones
are available to you.
sel_level
The MLS range of the SELinux context.
CLI Example:
.. code-block:: bash
salt '*' selinux.fcontext_delete_policy my-policy
'''
return _fcontext_add_or_delete_policy('delete', name, filetype, sel_type, sel_user, sel_level) | [
"def",
"fcontext_delete_policy",
"(",
"name",
",",
"filetype",
"=",
"None",
",",
"sel_type",
"=",
"None",
",",
"sel_user",
"=",
"None",
",",
"sel_level",
"=",
"None",
")",
":",
"return",
"_fcontext_add_or_delete_policy",
"(",
"'delete'",
",",
"name",
",",
"f... | .. versionadded:: 2019.2.0
Deletes the SELinux policy for a given filespec and other optional parameters.
Returns the result of the call to semanage.
Note that you don't have to remove an entry before setting a new
one for a given filespec and filetype, as adding one with semanage
automatically overwrites a previously configured SELinux context.
name
filespec of the file or directory. Regex syntax is allowed.
file_type
The SELinux filetype specification. Use one of [a, f, d, c, b,
s, l, p]. See also ``man semanage-fcontext``. Defaults to 'a'
(all files).
sel_type
SELinux context type. There are many.
sel_user
SELinux user. Use ``semanage login -l`` to determine which ones
are available to you.
sel_level
The MLS range of the SELinux context.
CLI Example:
.. code-block:: bash
salt '*' selinux.fcontext_delete_policy my-policy | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L545-L581 | train |
saltstack/salt | salt/modules/selinux.py | fcontext_add_or_delete_policy | def fcontext_add_or_delete_policy(action, name, filetype=None, sel_type=None, sel_user=None, sel_level=None):
'''
.. versionadded:: 2017.7.0
Adds or deletes the SELinux policy for a given filespec and other optional parameters.
Returns the result of the call to semanage.
Note that you don't have to remove an entry before setting a new
one for a given filespec and filetype, as adding one with semanage
automatically overwrites a previously configured SELinux context.
.. warning::
Use :mod:`selinux.fcontext_add_policy()<salt.modules.selinux.fcontext_add_policy>`,
or :mod:`selinux.fcontext_delete_policy()<salt.modules.selinux.fcontext_delete_policy>`.
.. deprecated:: 2019.2.0
action
The action to perform. Either ``add`` or ``delete``.
name
filespec of the file or directory. Regex syntax is allowed.
file_type
The SELinux filetype specification. Use one of [a, f, d, c, b,
s, l, p]. See also ``man semanage-fcontext``. Defaults to 'a'
(all files).
sel_type
SELinux context type. There are many.
sel_user
SELinux user. Use ``semanage login -l`` to determine which ones
are available to you.
sel_level
The MLS range of the SELinux context.
CLI Example:
.. code-block:: bash
salt '*' selinux.fcontext_add_or_delete_policy add my-policy
'''
salt.utils.versions.warn_until(
'Sodium',
'The \'selinux.fcontext_add_or_delete_policy\' module has been deprecated. Please use the '
'\'selinux.fcontext_add_policy\' and \'selinux.fcontext_delete_policy\' modules instead. '
'Support for the \'selinux.fcontext_add_or_delete_policy\' module will be removed in Salt '
'{version}.'
)
return _fcontext_add_or_delete_policy(action, name, filetype, sel_type, sel_user, sel_level) | python | def fcontext_add_or_delete_policy(action, name, filetype=None, sel_type=None, sel_user=None, sel_level=None):
'''
.. versionadded:: 2017.7.0
Adds or deletes the SELinux policy for a given filespec and other optional parameters.
Returns the result of the call to semanage.
Note that you don't have to remove an entry before setting a new
one for a given filespec and filetype, as adding one with semanage
automatically overwrites a previously configured SELinux context.
.. warning::
Use :mod:`selinux.fcontext_add_policy()<salt.modules.selinux.fcontext_add_policy>`,
or :mod:`selinux.fcontext_delete_policy()<salt.modules.selinux.fcontext_delete_policy>`.
.. deprecated:: 2019.2.0
action
The action to perform. Either ``add`` or ``delete``.
name
filespec of the file or directory. Regex syntax is allowed.
file_type
The SELinux filetype specification. Use one of [a, f, d, c, b,
s, l, p]. See also ``man semanage-fcontext``. Defaults to 'a'
(all files).
sel_type
SELinux context type. There are many.
sel_user
SELinux user. Use ``semanage login -l`` to determine which ones
are available to you.
sel_level
The MLS range of the SELinux context.
CLI Example:
.. code-block:: bash
salt '*' selinux.fcontext_add_or_delete_policy add my-policy
'''
salt.utils.versions.warn_until(
'Sodium',
'The \'selinux.fcontext_add_or_delete_policy\' module has been deprecated. Please use the '
'\'selinux.fcontext_add_policy\' and \'selinux.fcontext_delete_policy\' modules instead. '
'Support for the \'selinux.fcontext_add_or_delete_policy\' module will be removed in Salt '
'{version}.'
)
return _fcontext_add_or_delete_policy(action, name, filetype, sel_type, sel_user, sel_level) | [
"def",
"fcontext_add_or_delete_policy",
"(",
"action",
",",
"name",
",",
"filetype",
"=",
"None",
",",
"sel_type",
"=",
"None",
",",
"sel_user",
"=",
"None",
",",
"sel_level",
"=",
"None",
")",
":",
"salt",
".",
"utils",
".",
"versions",
".",
"warn_until",... | .. versionadded:: 2017.7.0
Adds or deletes the SELinux policy for a given filespec and other optional parameters.
Returns the result of the call to semanage.
Note that you don't have to remove an entry before setting a new
one for a given filespec and filetype, as adding one with semanage
automatically overwrites a previously configured SELinux context.
.. warning::
Use :mod:`selinux.fcontext_add_policy()<salt.modules.selinux.fcontext_add_policy>`,
or :mod:`selinux.fcontext_delete_policy()<salt.modules.selinux.fcontext_delete_policy>`.
.. deprecated:: 2019.2.0
action
The action to perform. Either ``add`` or ``delete``.
name
filespec of the file or directory. Regex syntax is allowed.
file_type
The SELinux filetype specification. Use one of [a, f, d, c, b,
s, l, p]. See also ``man semanage-fcontext``. Defaults to 'a'
(all files).
sel_type
SELinux context type. There are many.
sel_user
SELinux user. Use ``semanage login -l`` to determine which ones
are available to you.
sel_level
The MLS range of the SELinux context.
CLI Example:
.. code-block:: bash
salt '*' selinux.fcontext_add_or_delete_policy add my-policy | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L584-L637 | train |
saltstack/salt | salt/modules/selinux.py | _fcontext_add_or_delete_policy | def _fcontext_add_or_delete_policy(action, name, filetype=None, sel_type=None, sel_user=None, sel_level=None):
'''
.. versionadded:: 2019.2.0
Performs the action as called from ``fcontext_add_policy`` or ``fcontext_delete_policy``.
Returns the result of the call to semanage.
'''
if action not in ['add', 'delete']:
raise SaltInvocationError('Actions supported are "add" and "delete", not "{0}".'.format(action))
cmd = 'semanage fcontext --{0}'.format(action)
# "semanage --ftype a" isn't valid on Centos 6,
# don't pass --ftype since "a" is the default filetype.
if filetype is not None and filetype != 'a':
_validate_filetype(filetype)
cmd += ' --ftype {0}'.format(filetype)
if sel_type is not None:
cmd += ' --type {0}'.format(sel_type)
if sel_user is not None:
cmd += ' --seuser {0}'.format(sel_user)
if sel_level is not None:
cmd += ' --range {0}'.format(sel_level)
cmd += ' ' + re.escape(name)
return __salt__['cmd.run_all'](cmd) | python | def _fcontext_add_or_delete_policy(action, name, filetype=None, sel_type=None, sel_user=None, sel_level=None):
'''
.. versionadded:: 2019.2.0
Performs the action as called from ``fcontext_add_policy`` or ``fcontext_delete_policy``.
Returns the result of the call to semanage.
'''
if action not in ['add', 'delete']:
raise SaltInvocationError('Actions supported are "add" and "delete", not "{0}".'.format(action))
cmd = 'semanage fcontext --{0}'.format(action)
# "semanage --ftype a" isn't valid on Centos 6,
# don't pass --ftype since "a" is the default filetype.
if filetype is not None and filetype != 'a':
_validate_filetype(filetype)
cmd += ' --ftype {0}'.format(filetype)
if sel_type is not None:
cmd += ' --type {0}'.format(sel_type)
if sel_user is not None:
cmd += ' --seuser {0}'.format(sel_user)
if sel_level is not None:
cmd += ' --range {0}'.format(sel_level)
cmd += ' ' + re.escape(name)
return __salt__['cmd.run_all'](cmd) | [
"def",
"_fcontext_add_or_delete_policy",
"(",
"action",
",",
"name",
",",
"filetype",
"=",
"None",
",",
"sel_type",
"=",
"None",
",",
"sel_user",
"=",
"None",
",",
"sel_level",
"=",
"None",
")",
":",
"if",
"action",
"not",
"in",
"[",
"'add'",
",",
"'dele... | .. versionadded:: 2019.2.0
Performs the action as called from ``fcontext_add_policy`` or ``fcontext_delete_policy``.
Returns the result of the call to semanage. | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L640-L663 | train |
saltstack/salt | salt/modules/selinux.py | fcontext_policy_is_applied | def fcontext_policy_is_applied(name, recursive=False):
'''
.. versionadded:: 2017.7.0
Returns an empty string if the SELinux policy for a given filespec
is applied, returns string with differences in policy and actual
situation otherwise.
name
filespec of the file or directory. Regex syntax is allowed.
CLI Example:
.. code-block:: bash
salt '*' selinux.fcontext_policy_is_applied my-policy
'''
cmd = 'restorecon -n -v '
if recursive:
cmd += '-R '
cmd += re.escape(name)
return __salt__['cmd.run_all'](cmd).get('stdout') | python | def fcontext_policy_is_applied(name, recursive=False):
'''
.. versionadded:: 2017.7.0
Returns an empty string if the SELinux policy for a given filespec
is applied, returns string with differences in policy and actual
situation otherwise.
name
filespec of the file or directory. Regex syntax is allowed.
CLI Example:
.. code-block:: bash
salt '*' selinux.fcontext_policy_is_applied my-policy
'''
cmd = 'restorecon -n -v '
if recursive:
cmd += '-R '
cmd += re.escape(name)
return __salt__['cmd.run_all'](cmd).get('stdout') | [
"def",
"fcontext_policy_is_applied",
"(",
"name",
",",
"recursive",
"=",
"False",
")",
":",
"cmd",
"=",
"'restorecon -n -v '",
"if",
"recursive",
":",
"cmd",
"+=",
"'-R '",
"cmd",
"+=",
"re",
".",
"escape",
"(",
"name",
")",
"return",
"__salt__",
"[",
"'cm... | .. versionadded:: 2017.7.0
Returns an empty string if the SELinux policy for a given filespec
is applied, returns string with differences in policy and actual
situation otherwise.
name
filespec of the file or directory. Regex syntax is allowed.
CLI Example:
.. code-block:: bash
salt '*' selinux.fcontext_policy_is_applied my-policy | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L666-L687 | train |
saltstack/salt | salt/modules/selinux.py | fcontext_apply_policy | def fcontext_apply_policy(name, recursive=False):
'''
.. versionadded:: 2017.7.0
Applies SElinux policies to filespec using `restorecon [-R]
filespec`. Returns dict with changes if successful, the output of
the restorecon command otherwise.
name
filespec of the file or directory. Regex syntax is allowed.
recursive
Recursively apply SELinux policies.
CLI Example:
.. code-block:: bash
salt '*' selinux.fcontext_apply_policy my-policy
'''
ret = {}
changes_text = fcontext_policy_is_applied(name, recursive)
cmd = 'restorecon -v -F '
if recursive:
cmd += '-R '
cmd += re.escape(name)
apply_ret = __salt__['cmd.run_all'](cmd)
ret.update(apply_ret)
if apply_ret['retcode'] == 0:
changes_list = re.findall('restorecon reset (.*) context (.*)->(.*)$', changes_text, re.M)
if changes_list:
ret.update({'changes': {}})
for item in changes_list:
filespec = item[0]
old = _context_string_to_dict(item[1])
new = _context_string_to_dict(item[2])
intersect = {}
for key, value in six.iteritems(old):
if new.get(key) == value:
intersect.update({key: value})
for key in intersect:
del old[key]
del new[key]
ret['changes'].update({filespec: {'old': old, 'new': new}})
return ret | python | def fcontext_apply_policy(name, recursive=False):
'''
.. versionadded:: 2017.7.0
Applies SElinux policies to filespec using `restorecon [-R]
filespec`. Returns dict with changes if successful, the output of
the restorecon command otherwise.
name
filespec of the file or directory. Regex syntax is allowed.
recursive
Recursively apply SELinux policies.
CLI Example:
.. code-block:: bash
salt '*' selinux.fcontext_apply_policy my-policy
'''
ret = {}
changes_text = fcontext_policy_is_applied(name, recursive)
cmd = 'restorecon -v -F '
if recursive:
cmd += '-R '
cmd += re.escape(name)
apply_ret = __salt__['cmd.run_all'](cmd)
ret.update(apply_ret)
if apply_ret['retcode'] == 0:
changes_list = re.findall('restorecon reset (.*) context (.*)->(.*)$', changes_text, re.M)
if changes_list:
ret.update({'changes': {}})
for item in changes_list:
filespec = item[0]
old = _context_string_to_dict(item[1])
new = _context_string_to_dict(item[2])
intersect = {}
for key, value in six.iteritems(old):
if new.get(key) == value:
intersect.update({key: value})
for key in intersect:
del old[key]
del new[key]
ret['changes'].update({filespec: {'old': old, 'new': new}})
return ret | [
"def",
"fcontext_apply_policy",
"(",
"name",
",",
"recursive",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"}",
"changes_text",
"=",
"fcontext_policy_is_applied",
"(",
"name",
",",
"recursive",
")",
"cmd",
"=",
"'restorecon -v -F '",
"if",
"recursive",
":",
"cmd"... | .. versionadded:: 2017.7.0
Applies SElinux policies to filespec using `restorecon [-R]
filespec`. Returns dict with changes if successful, the output of
the restorecon command otherwise.
name
filespec of the file or directory. Regex syntax is allowed.
recursive
Recursively apply SELinux policies.
CLI Example:
.. code-block:: bash
salt '*' selinux.fcontext_apply_policy my-policy | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L690-L734 | train |
saltstack/salt | salt/modules/selinux.py | port_get_policy | def port_get_policy(name, sel_type=None, protocol=None, port=None):
'''
.. versionadded:: 2019.2.0
Returns the current entry in the SELinux policy list as a
dictionary. Returns None if no exact match was found.
Returned keys are:
* sel_type (the selinux type)
* proto (the protocol)
* port (the port(s) and/or port range(s))
name
The protocol and port spec. Can be formatted as ``(tcp|udp)/(port|port-range)``.
sel_type
The SELinux Type.
protocol
The protocol for the port, ``tcp`` or ``udp``. Required if name is not formatted.
port
The port or port range. Required if name is not formatted.
CLI Example:
.. code-block:: bash
salt '*' selinux.port_get_policy tcp/80
salt '*' selinux.port_get_policy foobar protocol=tcp port=80
'''
(protocol, port) = _parse_protocol_port(name, protocol, port)
re_spacer = '[ ]+'
re_sel_type = sel_type if sel_type else r'\w+'
cmd_kwargs = {'spacer': re_spacer,
'sel_type': re_sel_type,
'protocol': protocol,
'port': port, }
cmd = 'semanage port -l | egrep ' + \
"'^{sel_type}{spacer}{protocol}{spacer}((.*)*)[ ]{port}($|,)'".format(**cmd_kwargs)
port_policy = __salt__['cmd.shell'](cmd, ignore_retcode=True)
if port_policy == '':
return None
parts = re.match(r'^(\w+)[ ]+(\w+)[ ]+([\d\-, ]+)', port_policy)
return {
'sel_type': parts.group(1).strip(),
'protocol': parts.group(2).strip(),
'port': parts.group(3).strip(), } | python | def port_get_policy(name, sel_type=None, protocol=None, port=None):
'''
.. versionadded:: 2019.2.0
Returns the current entry in the SELinux policy list as a
dictionary. Returns None if no exact match was found.
Returned keys are:
* sel_type (the selinux type)
* proto (the protocol)
* port (the port(s) and/or port range(s))
name
The protocol and port spec. Can be formatted as ``(tcp|udp)/(port|port-range)``.
sel_type
The SELinux Type.
protocol
The protocol for the port, ``tcp`` or ``udp``. Required if name is not formatted.
port
The port or port range. Required if name is not formatted.
CLI Example:
.. code-block:: bash
salt '*' selinux.port_get_policy tcp/80
salt '*' selinux.port_get_policy foobar protocol=tcp port=80
'''
(protocol, port) = _parse_protocol_port(name, protocol, port)
re_spacer = '[ ]+'
re_sel_type = sel_type if sel_type else r'\w+'
cmd_kwargs = {'spacer': re_spacer,
'sel_type': re_sel_type,
'protocol': protocol,
'port': port, }
cmd = 'semanage port -l | egrep ' + \
"'^{sel_type}{spacer}{protocol}{spacer}((.*)*)[ ]{port}($|,)'".format(**cmd_kwargs)
port_policy = __salt__['cmd.shell'](cmd, ignore_retcode=True)
if port_policy == '':
return None
parts = re.match(r'^(\w+)[ ]+(\w+)[ ]+([\d\-, ]+)', port_policy)
return {
'sel_type': parts.group(1).strip(),
'protocol': parts.group(2).strip(),
'port': parts.group(3).strip(), } | [
"def",
"port_get_policy",
"(",
"name",
",",
"sel_type",
"=",
"None",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"(",
"protocol",
",",
"port",
")",
"=",
"_parse_protocol_port",
"(",
"name",
",",
"protocol",
",",
"port",
")",
"re_s... | .. versionadded:: 2019.2.0
Returns the current entry in the SELinux policy list as a
dictionary. Returns None if no exact match was found.
Returned keys are:
* sel_type (the selinux type)
* proto (the protocol)
* port (the port(s) and/or port range(s))
name
The protocol and port spec. Can be formatted as ``(tcp|udp)/(port|port-range)``.
sel_type
The SELinux Type.
protocol
The protocol for the port, ``tcp`` or ``udp``. Required if name is not formatted.
port
The port or port range. Required if name is not formatted.
CLI Example:
.. code-block:: bash
salt '*' selinux.port_get_policy tcp/80
salt '*' selinux.port_get_policy foobar protocol=tcp port=80 | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L737-L786 | train |
saltstack/salt | salt/modules/selinux.py | port_add_policy | def port_add_policy(name, sel_type=None, protocol=None, port=None, sel_range=None):
'''
.. versionadded:: 2019.2.0
Adds the SELinux policy for a given protocol and port.
Returns the result of the call to semanage.
name
The protocol and port spec. Can be formatted as ``(tcp|udp)/(port|port-range)``.
sel_type
The SELinux Type. Required.
protocol
The protocol for the port, ``tcp`` or ``udp``. Required if name is not formatted.
port
The port or port range. Required if name is not formatted.
sel_range
The SELinux MLS/MCS Security Range.
CLI Example:
.. code-block:: bash
salt '*' selinux.port_add_policy add tcp/8080 http_port_t
salt '*' selinux.port_add_policy add foobar http_port_t protocol=tcp port=8091
'''
return _port_add_or_delete_policy('add', name, sel_type, protocol, port, sel_range) | python | def port_add_policy(name, sel_type=None, protocol=None, port=None, sel_range=None):
'''
.. versionadded:: 2019.2.0
Adds the SELinux policy for a given protocol and port.
Returns the result of the call to semanage.
name
The protocol and port spec. Can be formatted as ``(tcp|udp)/(port|port-range)``.
sel_type
The SELinux Type. Required.
protocol
The protocol for the port, ``tcp`` or ``udp``. Required if name is not formatted.
port
The port or port range. Required if name is not formatted.
sel_range
The SELinux MLS/MCS Security Range.
CLI Example:
.. code-block:: bash
salt '*' selinux.port_add_policy add tcp/8080 http_port_t
salt '*' selinux.port_add_policy add foobar http_port_t protocol=tcp port=8091
'''
return _port_add_or_delete_policy('add', name, sel_type, protocol, port, sel_range) | [
"def",
"port_add_policy",
"(",
"name",
",",
"sel_type",
"=",
"None",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"sel_range",
"=",
"None",
")",
":",
"return",
"_port_add_or_delete_policy",
"(",
"'add'",
",",
"name",
",",
"sel_type",
",",
... | .. versionadded:: 2019.2.0
Adds the SELinux policy for a given protocol and port.
Returns the result of the call to semanage.
name
The protocol and port spec. Can be formatted as ``(tcp|udp)/(port|port-range)``.
sel_type
The SELinux Type. Required.
protocol
The protocol for the port, ``tcp`` or ``udp``. Required if name is not formatted.
port
The port or port range. Required if name is not formatted.
sel_range
The SELinux MLS/MCS Security Range.
CLI Example:
.. code-block:: bash
salt '*' selinux.port_add_policy add tcp/8080 http_port_t
salt '*' selinux.port_add_policy add foobar http_port_t protocol=tcp port=8091 | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L789-L819 | train |
saltstack/salt | salt/modules/selinux.py | _port_add_or_delete_policy | def _port_add_or_delete_policy(action, name, sel_type=None, protocol=None, port=None, sel_range=None):
'''
.. versionadded:: 2019.2.0
Performs the action as called from ``port_add_policy`` or ``port_delete_policy``.
Returns the result of the call to semanage.
'''
if action not in ['add', 'delete']:
raise SaltInvocationError('Actions supported are "add" and "delete", not "{0}".'.format(action))
if action == 'add' and not sel_type:
raise SaltInvocationError('SELinux Type is required to add a policy')
(protocol, port) = _parse_protocol_port(name, protocol, port)
cmd = 'semanage port --{0} --proto {1}'.format(action, protocol)
if sel_type:
cmd += ' --type {0}'.format(sel_type)
if sel_range:
cmd += ' --range {0}'.format(sel_range)
cmd += ' {0}'.format(port)
return __salt__['cmd.run_all'](cmd) | python | def _port_add_or_delete_policy(action, name, sel_type=None, protocol=None, port=None, sel_range=None):
'''
.. versionadded:: 2019.2.0
Performs the action as called from ``port_add_policy`` or ``port_delete_policy``.
Returns the result of the call to semanage.
'''
if action not in ['add', 'delete']:
raise SaltInvocationError('Actions supported are "add" and "delete", not "{0}".'.format(action))
if action == 'add' and not sel_type:
raise SaltInvocationError('SELinux Type is required to add a policy')
(protocol, port) = _parse_protocol_port(name, protocol, port)
cmd = 'semanage port --{0} --proto {1}'.format(action, protocol)
if sel_type:
cmd += ' --type {0}'.format(sel_type)
if sel_range:
cmd += ' --range {0}'.format(sel_range)
cmd += ' {0}'.format(port)
return __salt__['cmd.run_all'](cmd) | [
"def",
"_port_add_or_delete_policy",
"(",
"action",
",",
"name",
",",
"sel_type",
"=",
"None",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"sel_range",
"=",
"None",
")",
":",
"if",
"action",
"not",
"in",
"[",
"'add'",
",",
"'delete'",
... | .. versionadded:: 2019.2.0
Performs the action as called from ``port_add_policy`` or ``port_delete_policy``.
Returns the result of the call to semanage. | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/selinux.py#L849-L868 | train |
saltstack/salt | salt/returners/etcd_return.py | _get_conn | def _get_conn(opts, profile=None):
'''
Establish a connection to etcd
'''
if profile is None:
profile = opts.get('etcd.returner')
path = opts.get('etcd.returner_root', '/salt/return')
return salt.utils.etcd_util.get_conn(opts, profile), path | python | def _get_conn(opts, profile=None):
'''
Establish a connection to etcd
'''
if profile is None:
profile = opts.get('etcd.returner')
path = opts.get('etcd.returner_root', '/salt/return')
return salt.utils.etcd_util.get_conn(opts, profile), path | [
"def",
"_get_conn",
"(",
"opts",
",",
"profile",
"=",
"None",
")",
":",
"if",
"profile",
"is",
"None",
":",
"profile",
"=",
"opts",
".",
"get",
"(",
"'etcd.returner'",
")",
"path",
"=",
"opts",
".",
"get",
"(",
"'etcd.returner_root'",
",",
"'/salt/return... | Establish a connection to etcd | [
"Establish",
"a",
"connection",
"to",
"etcd"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/etcd_return.py#L97-L104 | train |
saltstack/salt | salt/returners/etcd_return.py | returner | def returner(ret):
'''
Return data to an etcd server or cluster
'''
write_profile = __opts__.get('etcd.returner_write_profile')
if write_profile:
ttl = __opts__.get(write_profile, {}).get('etcd.ttl')
else:
ttl = __opts__.get('etcd.ttl')
client, path = _get_conn(__opts__, write_profile)
# Make a note of this minion for the external job cache
client.set(
'/'.join((path, 'minions', ret['id'])),
ret['jid'],
ttl=ttl,
)
for field in ret:
# Not using os.path.join because we're not dealing with file paths
dest = '/'.join((
path,
'jobs',
ret['jid'],
ret['id'],
field
))
client.set(dest, salt.utils.json.dumps(ret[field]), ttl=ttl) | python | def returner(ret):
'''
Return data to an etcd server or cluster
'''
write_profile = __opts__.get('etcd.returner_write_profile')
if write_profile:
ttl = __opts__.get(write_profile, {}).get('etcd.ttl')
else:
ttl = __opts__.get('etcd.ttl')
client, path = _get_conn(__opts__, write_profile)
# Make a note of this minion for the external job cache
client.set(
'/'.join((path, 'minions', ret['id'])),
ret['jid'],
ttl=ttl,
)
for field in ret:
# Not using os.path.join because we're not dealing with file paths
dest = '/'.join((
path,
'jobs',
ret['jid'],
ret['id'],
field
))
client.set(dest, salt.utils.json.dumps(ret[field]), ttl=ttl) | [
"def",
"returner",
"(",
"ret",
")",
":",
"write_profile",
"=",
"__opts__",
".",
"get",
"(",
"'etcd.returner_write_profile'",
")",
"if",
"write_profile",
":",
"ttl",
"=",
"__opts__",
".",
"get",
"(",
"write_profile",
",",
"{",
"}",
")",
".",
"get",
"(",
"... | Return data to an etcd server or cluster | [
"Return",
"data",
"to",
"an",
"etcd",
"server",
"or",
"cluster"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/etcd_return.py#L107-L134 | train |
saltstack/salt | salt/returners/etcd_return.py | save_load | def save_load(jid, load, minions=None):
'''
Save the load to the specified jid
'''
log.debug('sdstack_etcd returner <save_load> called jid: %s', jid)
write_profile = __opts__.get('etcd.returner_write_profile')
client, path = _get_conn(__opts__, write_profile)
if write_profile:
ttl = __opts__.get(write_profile, {}).get('etcd.ttl')
else:
ttl = __opts__.get('etcd.ttl')
client.set(
'/'.join((path, 'jobs', jid, '.load.p')),
salt.utils.json.dumps(load),
ttl=ttl,
) | python | def save_load(jid, load, minions=None):
'''
Save the load to the specified jid
'''
log.debug('sdstack_etcd returner <save_load> called jid: %s', jid)
write_profile = __opts__.get('etcd.returner_write_profile')
client, path = _get_conn(__opts__, write_profile)
if write_profile:
ttl = __opts__.get(write_profile, {}).get('etcd.ttl')
else:
ttl = __opts__.get('etcd.ttl')
client.set(
'/'.join((path, 'jobs', jid, '.load.p')),
salt.utils.json.dumps(load),
ttl=ttl,
) | [
"def",
"save_load",
"(",
"jid",
",",
"load",
",",
"minions",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"'sdstack_etcd returner <save_load> called jid: %s'",
",",
"jid",
")",
"write_profile",
"=",
"__opts__",
".",
"get",
"(",
"'etcd.returner_write_profile'",... | Save the load to the specified jid | [
"Save",
"the",
"load",
"to",
"the",
"specified",
"jid"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/etcd_return.py#L137-L152 | train |
saltstack/salt | salt/returners/etcd_return.py | get_load | def get_load(jid):
'''
Return the load data that marks a specified jid
'''
log.debug('sdstack_etcd returner <get_load> called jid: %s', jid)
read_profile = __opts__.get('etcd.returner_read_profile')
client, path = _get_conn(__opts__, read_profile)
return salt.utils.json.loads(client.get('/'.join((path, 'jobs', jid, '.load.p'))).value) | python | def get_load(jid):
'''
Return the load data that marks a specified jid
'''
log.debug('sdstack_etcd returner <get_load> called jid: %s', jid)
read_profile = __opts__.get('etcd.returner_read_profile')
client, path = _get_conn(__opts__, read_profile)
return salt.utils.json.loads(client.get('/'.join((path, 'jobs', jid, '.load.p'))).value) | [
"def",
"get_load",
"(",
"jid",
")",
":",
"log",
".",
"debug",
"(",
"'sdstack_etcd returner <get_load> called jid: %s'",
",",
"jid",
")",
"read_profile",
"=",
"__opts__",
".",
"get",
"(",
"'etcd.returner_read_profile'",
")",
"client",
",",
"path",
"=",
"_get_conn",... | Return the load data that marks a specified jid | [
"Return",
"the",
"load",
"data",
"that",
"marks",
"a",
"specified",
"jid"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/etcd_return.py#L169-L176 | train |
saltstack/salt | salt/returners/etcd_return.py | get_jid | def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
log.debug('sdstack_etcd returner <get_jid> called jid: %s', jid)
ret = {}
client, path = _get_conn(__opts__)
items = client.get('/'.join((path, 'jobs', jid)))
for item in items.children:
if str(item.key).endswith('.load.p'):
continue
comps = str(item.key).split('/')
data = client.get('/'.join((path, 'jobs', jid, comps[-1], 'return'))).value
ret[comps[-1]] = {'return': salt.utils.json.loads(data)}
return ret | python | def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
log.debug('sdstack_etcd returner <get_jid> called jid: %s', jid)
ret = {}
client, path = _get_conn(__opts__)
items = client.get('/'.join((path, 'jobs', jid)))
for item in items.children:
if str(item.key).endswith('.load.p'):
continue
comps = str(item.key).split('/')
data = client.get('/'.join((path, 'jobs', jid, comps[-1], 'return'))).value
ret[comps[-1]] = {'return': salt.utils.json.loads(data)}
return ret | [
"def",
"get_jid",
"(",
"jid",
")",
":",
"log",
".",
"debug",
"(",
"'sdstack_etcd returner <get_jid> called jid: %s'",
",",
"jid",
")",
"ret",
"=",
"{",
"}",
"client",
",",
"path",
"=",
"_get_conn",
"(",
"__opts__",
")",
"items",
"=",
"client",
".",
"get",
... | Return the information returned when the specified job id was executed | [
"Return",
"the",
"information",
"returned",
"when",
"the",
"specified",
"job",
"id",
"was",
"executed"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/etcd_return.py#L179-L193 | train |
saltstack/salt | salt/returners/etcd_return.py | get_fun | def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
log.debug('sdstack_etcd returner <get_fun> called fun: %s', fun)
ret = {}
client, path = _get_conn(__opts__)
items = client.get('/'.join((path, 'minions')))
for item in items.children:
comps = str(item.key).split('/')
efun = salt.utils.json.loads(client.get('/'.join((path, 'jobs', str(item.value), comps[-1], 'fun'))).value)
if efun == fun:
ret[comps[-1]] = str(efun)
return ret | python | def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
log.debug('sdstack_etcd returner <get_fun> called fun: %s', fun)
ret = {}
client, path = _get_conn(__opts__)
items = client.get('/'.join((path, 'minions')))
for item in items.children:
comps = str(item.key).split('/')
efun = salt.utils.json.loads(client.get('/'.join((path, 'jobs', str(item.value), comps[-1], 'fun'))).value)
if efun == fun:
ret[comps[-1]] = str(efun)
return ret | [
"def",
"get_fun",
"(",
"fun",
")",
":",
"log",
".",
"debug",
"(",
"'sdstack_etcd returner <get_fun> called fun: %s'",
",",
"fun",
")",
"ret",
"=",
"{",
"}",
"client",
",",
"path",
"=",
"_get_conn",
"(",
"__opts__",
")",
"items",
"=",
"client",
".",
"get",
... | Return a dict of the last function called for all minions | [
"Return",
"a",
"dict",
"of",
"the",
"last",
"function",
"called",
"for",
"all",
"minions"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/etcd_return.py#L196-L209 | train |
saltstack/salt | salt/returners/etcd_return.py | get_jids | def get_jids():
'''
Return a list of all job ids
'''
log.debug('sdstack_etcd returner <get_jids> called')
ret = []
client, path = _get_conn(__opts__)
items = client.get('/'.join((path, 'jobs')))
for item in items.children:
if item.dir is True:
jid = str(item.key).split('/')[-1]
ret.append(jid)
return ret | python | def get_jids():
'''
Return a list of all job ids
'''
log.debug('sdstack_etcd returner <get_jids> called')
ret = []
client, path = _get_conn(__opts__)
items = client.get('/'.join((path, 'jobs')))
for item in items.children:
if item.dir is True:
jid = str(item.key).split('/')[-1]
ret.append(jid)
return ret | [
"def",
"get_jids",
"(",
")",
":",
"log",
".",
"debug",
"(",
"'sdstack_etcd returner <get_jids> called'",
")",
"ret",
"=",
"[",
"]",
"client",
",",
"path",
"=",
"_get_conn",
"(",
"__opts__",
")",
"items",
"=",
"client",
".",
"get",
"(",
"'/'",
".",
"join"... | Return a list of all job ids | [
"Return",
"a",
"list",
"of",
"all",
"job",
"ids"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/etcd_return.py#L212-L224 | train |
saltstack/salt | salt/returners/etcd_return.py | get_minions | def get_minions():
'''
Return a list of minions
'''
log.debug('sdstack_etcd returner <get_minions> called')
ret = []
client, path = _get_conn(__opts__)
items = client.get('/'.join((path, 'minions')))
for item in items.children:
comps = str(item.key).split('/')
ret.append(comps[-1])
return ret | python | def get_minions():
'''
Return a list of minions
'''
log.debug('sdstack_etcd returner <get_minions> called')
ret = []
client, path = _get_conn(__opts__)
items = client.get('/'.join((path, 'minions')))
for item in items.children:
comps = str(item.key).split('/')
ret.append(comps[-1])
return ret | [
"def",
"get_minions",
"(",
")",
":",
"log",
".",
"debug",
"(",
"'sdstack_etcd returner <get_minions> called'",
")",
"ret",
"=",
"[",
"]",
"client",
",",
"path",
"=",
"_get_conn",
"(",
"__opts__",
")",
"items",
"=",
"client",
".",
"get",
"(",
"'/'",
".",
... | Return a list of minions | [
"Return",
"a",
"list",
"of",
"minions"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/etcd_return.py#L227-L238 | train |
saltstack/salt | salt/states/linux_acl.py | present | def present(name, acl_type, acl_name='', perms='', recurse=False, force=False):
'''
Ensure a Linux ACL is present
name
The acl path
acl_type
The type of the acl is used for it can be 'user' or 'group'
acl_name
The user or group
perms
Set the permissions eg.: rwx
recurse
Set the permissions recursive in the path
force
Wipe out old permissions and ensure only the new permissions are set
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
_octal = {'r': 4, 'w': 2, 'x': 1, '-': 0}
if not os.path.exists(name):
ret['comment'] = '{0} does not exist'.format(name)
ret['result'] = False
return ret
__current_perms = __salt__['acl.getfacl'](name, recursive=recurse)
if acl_type.startswith(('d:', 'default:')):
_acl_type = ':'.join(acl_type.split(':')[1:])
_current_perms = __current_perms[name].get('defaults', {})
_default = True
else:
_acl_type = acl_type
_current_perms = __current_perms[name]
_default = False
# The getfacl execution module lists default with empty names as being
# applied to the user/group that owns the file, e.g.,
# default:group::rwx would be listed as default:group:root:rwx
# In this case, if acl_name is empty, we really want to search for root
# but still uses '' for other
# We search through the dictionary getfacl returns for the owner of the
# file if acl_name is empty.
if acl_name == '':
_search_name = __current_perms[name].get('comment').get(_acl_type, '')
else:
_search_name = acl_name
if _current_perms.get(_acl_type, None) or _default:
try:
user = [i for i in _current_perms[_acl_type] if next(six.iterkeys(i)) == _search_name].pop()
except (AttributeError, IndexError, StopIteration, KeyError):
user = None
if user:
octal_sum = sum([_octal.get(i, i) for i in perms])
need_refresh = False
for path in __current_perms:
acl_found = False
for user_acl in __current_perms[path].get(_acl_type, []):
if _search_name in user_acl and user_acl[_search_name]['octal'] == octal_sum:
acl_found = True
break
if not acl_found:
need_refresh = True
break
if not need_refresh:
ret['comment'] = 'Permissions are in the desired state'
else:
changes = {'new': {'acl_name': acl_name,
'acl_type': acl_type,
'perms': perms},
'old': {'acl_name': acl_name,
'acl_type': acl_type,
'perms': six.text_type(user[_search_name]['octal'])}}
if __opts__['test']:
ret.update({'comment': 'Updated permissions will be applied for '
'{0}: {1} -> {2}'.format(
acl_name,
six.text_type(user[_search_name]['octal']),
perms),
'result': None, 'changes': changes})
return ret
try:
if force:
__salt__['acl.wipefacls'](name, recursive=recurse, raise_err=True)
__salt__['acl.modfacl'](acl_type, acl_name, perms, name,
recursive=recurse, raise_err=True)
ret.update({'comment': 'Updated permissions for '
'{0}'.format(acl_name),
'result': True, 'changes': changes})
except CommandExecutionError as exc:
ret.update({'comment': 'Error updating permissions for '
'{0}: {1}'.format(acl_name, exc.strerror),
'result': False})
else:
changes = {'new': {'acl_name': acl_name,
'acl_type': acl_type,
'perms': perms}}
if __opts__['test']:
ret.update({'comment': 'New permissions will be applied for '
'{0}: {1}'.format(acl_name, perms),
'result': None, 'changes': changes})
ret['result'] = None
return ret
try:
if force:
__salt__['acl.wipefacls'](name, recursive=recurse, raise_err=True)
__salt__['acl.modfacl'](acl_type, acl_name, perms, name,
recursive=recurse, raise_err=True)
ret.update({'comment': 'Applied new permissions for '
'{0}'.format(acl_name),
'result': True, 'changes': changes})
except CommandExecutionError as exc:
ret.update({'comment': 'Error updating permissions for {0}: '
'{1}'.format(acl_name, exc.strerror),
'result': False})
else:
ret['comment'] = 'ACL Type does not exist'
ret['result'] = False
return ret | python | def present(name, acl_type, acl_name='', perms='', recurse=False, force=False):
'''
Ensure a Linux ACL is present
name
The acl path
acl_type
The type of the acl is used for it can be 'user' or 'group'
acl_name
The user or group
perms
Set the permissions eg.: rwx
recurse
Set the permissions recursive in the path
force
Wipe out old permissions and ensure only the new permissions are set
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
_octal = {'r': 4, 'w': 2, 'x': 1, '-': 0}
if not os.path.exists(name):
ret['comment'] = '{0} does not exist'.format(name)
ret['result'] = False
return ret
__current_perms = __salt__['acl.getfacl'](name, recursive=recurse)
if acl_type.startswith(('d:', 'default:')):
_acl_type = ':'.join(acl_type.split(':')[1:])
_current_perms = __current_perms[name].get('defaults', {})
_default = True
else:
_acl_type = acl_type
_current_perms = __current_perms[name]
_default = False
# The getfacl execution module lists default with empty names as being
# applied to the user/group that owns the file, e.g.,
# default:group::rwx would be listed as default:group:root:rwx
# In this case, if acl_name is empty, we really want to search for root
# but still uses '' for other
# We search through the dictionary getfacl returns for the owner of the
# file if acl_name is empty.
if acl_name == '':
_search_name = __current_perms[name].get('comment').get(_acl_type, '')
else:
_search_name = acl_name
if _current_perms.get(_acl_type, None) or _default:
try:
user = [i for i in _current_perms[_acl_type] if next(six.iterkeys(i)) == _search_name].pop()
except (AttributeError, IndexError, StopIteration, KeyError):
user = None
if user:
octal_sum = sum([_octal.get(i, i) for i in perms])
need_refresh = False
for path in __current_perms:
acl_found = False
for user_acl in __current_perms[path].get(_acl_type, []):
if _search_name in user_acl and user_acl[_search_name]['octal'] == octal_sum:
acl_found = True
break
if not acl_found:
need_refresh = True
break
if not need_refresh:
ret['comment'] = 'Permissions are in the desired state'
else:
changes = {'new': {'acl_name': acl_name,
'acl_type': acl_type,
'perms': perms},
'old': {'acl_name': acl_name,
'acl_type': acl_type,
'perms': six.text_type(user[_search_name]['octal'])}}
if __opts__['test']:
ret.update({'comment': 'Updated permissions will be applied for '
'{0}: {1} -> {2}'.format(
acl_name,
six.text_type(user[_search_name]['octal']),
perms),
'result': None, 'changes': changes})
return ret
try:
if force:
__salt__['acl.wipefacls'](name, recursive=recurse, raise_err=True)
__salt__['acl.modfacl'](acl_type, acl_name, perms, name,
recursive=recurse, raise_err=True)
ret.update({'comment': 'Updated permissions for '
'{0}'.format(acl_name),
'result': True, 'changes': changes})
except CommandExecutionError as exc:
ret.update({'comment': 'Error updating permissions for '
'{0}: {1}'.format(acl_name, exc.strerror),
'result': False})
else:
changes = {'new': {'acl_name': acl_name,
'acl_type': acl_type,
'perms': perms}}
if __opts__['test']:
ret.update({'comment': 'New permissions will be applied for '
'{0}: {1}'.format(acl_name, perms),
'result': None, 'changes': changes})
ret['result'] = None
return ret
try:
if force:
__salt__['acl.wipefacls'](name, recursive=recurse, raise_err=True)
__salt__['acl.modfacl'](acl_type, acl_name, perms, name,
recursive=recurse, raise_err=True)
ret.update({'comment': 'Applied new permissions for '
'{0}'.format(acl_name),
'result': True, 'changes': changes})
except CommandExecutionError as exc:
ret.update({'comment': 'Error updating permissions for {0}: '
'{1}'.format(acl_name, exc.strerror),
'result': False})
else:
ret['comment'] = 'ACL Type does not exist'
ret['result'] = False
return ret | [
"def",
"present",
"(",
"name",
",",
"acl_type",
",",
"acl_name",
"=",
"''",
",",
"perms",
"=",
"''",
",",
"recurse",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'... | Ensure a Linux ACL is present
name
The acl path
acl_type
The type of the acl is used for it can be 'user' or 'group'
acl_name
The user or group
perms
Set the permissions eg.: rwx
recurse
Set the permissions recursive in the path
force
Wipe out old permissions and ensure only the new permissions are set | [
"Ensure",
"a",
"Linux",
"ACL",
"is",
"present"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/linux_acl.py#L82-L219 | train |
saltstack/salt | salt/states/linux_acl.py | absent | def absent(name, acl_type, acl_name='', perms='', recurse=False):
'''
Ensure a Linux ACL does not exist
name
The acl path
acl_type
The type of the acl is used for, it can be 'user' or 'group'
acl_names
The user or group
perms
Remove the permissions eg.: rwx
recurse
Set the permissions recursive in the path
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if not os.path.exists(name):
ret['comment'] = '{0} does not exist'.format(name)
ret['result'] = False
return ret
__current_perms = __salt__['acl.getfacl'](name, recursive=recurse)
if acl_type.startswith(('d:', 'default:')):
_acl_type = ':'.join(acl_type.split(':')[1:])
_current_perms = __current_perms[name].get('defaults', {})
_default = True
else:
_acl_type = acl_type
_current_perms = __current_perms[name]
_default = False
# The getfacl execution module lists default with empty names as being
# applied to the user/group that owns the file, e.g.,
# default:group::rwx would be listed as default:group:root:rwx
# In this case, if acl_name is empty, we really want to search for root
# but still uses '' for other
# We search through the dictionary getfacl returns for the owner of the
# file if acl_name is empty.
if acl_name == '':
_search_name = __current_perms[name].get('comment').get(_acl_type, '')
else:
_search_name = acl_name
if _current_perms.get(_acl_type, None) or _default:
try:
user = [i for i in _current_perms[_acl_type] if next(six.iterkeys(i)) == _search_name].pop()
except (AttributeError, IndexError, StopIteration, KeyError):
user = None
need_refresh = False
for path in __current_perms:
acl_found = False
for user_acl in __current_perms[path].get(_acl_type, []):
if _search_name in user_acl:
acl_found = True
break
if acl_found:
need_refresh = True
break
if user or need_refresh:
ret['comment'] = 'Removing permissions'
if __opts__['test']:
ret['result'] = None
return ret
__salt__['acl.delfacl'](acl_type, acl_name, perms, name, recursive=recurse)
else:
ret['comment'] = 'Permissions are in the desired state'
else:
ret['comment'] = 'ACL Type does not exist'
ret['result'] = False
return ret | python | def absent(name, acl_type, acl_name='', perms='', recurse=False):
'''
Ensure a Linux ACL does not exist
name
The acl path
acl_type
The type of the acl is used for, it can be 'user' or 'group'
acl_names
The user or group
perms
Remove the permissions eg.: rwx
recurse
Set the permissions recursive in the path
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if not os.path.exists(name):
ret['comment'] = '{0} does not exist'.format(name)
ret['result'] = False
return ret
__current_perms = __salt__['acl.getfacl'](name, recursive=recurse)
if acl_type.startswith(('d:', 'default:')):
_acl_type = ':'.join(acl_type.split(':')[1:])
_current_perms = __current_perms[name].get('defaults', {})
_default = True
else:
_acl_type = acl_type
_current_perms = __current_perms[name]
_default = False
# The getfacl execution module lists default with empty names as being
# applied to the user/group that owns the file, e.g.,
# default:group::rwx would be listed as default:group:root:rwx
# In this case, if acl_name is empty, we really want to search for root
# but still uses '' for other
# We search through the dictionary getfacl returns for the owner of the
# file if acl_name is empty.
if acl_name == '':
_search_name = __current_perms[name].get('comment').get(_acl_type, '')
else:
_search_name = acl_name
if _current_perms.get(_acl_type, None) or _default:
try:
user = [i for i in _current_perms[_acl_type] if next(six.iterkeys(i)) == _search_name].pop()
except (AttributeError, IndexError, StopIteration, KeyError):
user = None
need_refresh = False
for path in __current_perms:
acl_found = False
for user_acl in __current_perms[path].get(_acl_type, []):
if _search_name in user_acl:
acl_found = True
break
if acl_found:
need_refresh = True
break
if user or need_refresh:
ret['comment'] = 'Removing permissions'
if __opts__['test']:
ret['result'] = None
return ret
__salt__['acl.delfacl'](acl_type, acl_name, perms, name, recursive=recurse)
else:
ret['comment'] = 'Permissions are in the desired state'
else:
ret['comment'] = 'ACL Type does not exist'
ret['result'] = False
return ret | [
"def",
"absent",
"(",
"name",
",",
"acl_type",
",",
"acl_name",
"=",
"''",
",",
"perms",
"=",
"''",
",",
"recurse",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'changes'",
":",
"{",
"}",
","... | Ensure a Linux ACL does not exist
name
The acl path
acl_type
The type of the acl is used for, it can be 'user' or 'group'
acl_names
The user or group
perms
Remove the permissions eg.: rwx
recurse
Set the permissions recursive in the path | [
"Ensure",
"a",
"Linux",
"ACL",
"does",
"not",
"exist"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/linux_acl.py#L222-L307 | train |
saltstack/salt | salt/states/linux_acl.py | list_present | def list_present(name, acl_type, acl_names=None, perms='', recurse=False, force=False):
'''
Ensure a Linux ACL list is present
Takes a list of acl names and add them to the given path
name
The acl path
acl_type
The type of the acl is used for it can be 'user' or 'group'
acl_names
The list of users or groups
perms
Set the permissions eg.: rwx
recurse
Set the permissions recursive in the path
force
Wipe out old permissions and ensure only the new permissions are set
'''
if acl_names is None:
acl_names = []
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
_octal = {'r': 4, 'w': 2, 'x': 1, '-': 0}
_octal_perms = sum([_octal.get(i, i) for i in perms])
if not os.path.exists(name):
ret['comment'] = '{0} does not exist'.format(name)
ret['result'] = False
return ret
__current_perms = __salt__['acl.getfacl'](name)
if acl_type.startswith(('d:', 'default:')):
_acl_type = ':'.join(acl_type.split(':')[1:])
_current_perms = __current_perms[name].get('defaults', {})
_default = True
else:
_acl_type = acl_type
_current_perms = __current_perms[name]
_default = False
_origin_group = _current_perms.get('comment', {}).get('group', None)
_origin_owner = _current_perms.get('comment', {}).get('owner', None)
_current_acl_types = []
diff_perms = False
for key in _current_perms[acl_type]:
for current_acl_name in key.keys():
_current_acl_types.append(current_acl_name.encode('utf-8'))
diff_perms = _octal_perms == key[current_acl_name]['octal']
if acl_type == 'user':
try:
_current_acl_types.remove(_origin_owner)
except ValueError:
pass
else:
try:
_current_acl_types.remove(_origin_group)
except ValueError:
pass
diff_acls = set(_current_acl_types) ^ set(acl_names)
if not diff_acls and diff_perms and not force:
ret = {'name': name,
'result': True,
'changes': {},
'comment': 'Permissions and {}s are in the desired state'.format(acl_type)}
return ret
# The getfacl execution module lists default with empty names as being
# applied to the user/group that owns the file, e.g.,
# default:group::rwx would be listed as default:group:root:rwx
# In this case, if acl_name is empty, we really want to search for root
# but still uses '' for other
# We search through the dictionary getfacl returns for the owner of the
# file if acl_name is empty.
if acl_names == '':
_search_names = __current_perms[name].get('comment').get(_acl_type, '')
else:
_search_names = acl_names
if _current_perms.get(_acl_type, None) or _default:
try:
users = {}
for i in _current_perms[_acl_type]:
if i and next(six.iterkeys(i)) in _search_names:
users.update(i)
except (AttributeError, KeyError):
users = None
if users:
changes = {}
for count, search_name in enumerate(_search_names):
if search_name in users:
if users[search_name]['octal'] == sum([_octal.get(i, i) for i in perms]):
ret['comment'] = 'Permissions are in the desired state'
else:
changes.update({'new': {'acl_name': ', '.join(acl_names),
'acl_type': acl_type,
'perms': _octal_perms},
'old': {'acl_name': ', '.join(acl_names),
'acl_type': acl_type,
'perms': six.text_type(users[search_name]['octal'])}})
if __opts__['test']:
ret.update({'comment': 'Updated permissions will be applied for '
'{0}: {1} -> {2}'.format(
acl_names,
six.text_type(users[search_name]['octal']),
perms),
'result': None, 'changes': changes})
return ret
try:
if force:
__salt__['acl.wipefacls'](name, recursive=recurse, raise_err=True)
for acl_name in acl_names:
__salt__['acl.modfacl'](acl_type, acl_name, perms, name,
recursive=recurse, raise_err=True)
ret.update({'comment': 'Updated permissions for '
'{0}'.format(acl_names),
'result': True, 'changes': changes})
except CommandExecutionError as exc:
ret.update({'comment': 'Error updating permissions for '
'{0}: {1}'.format(acl_names, exc.strerror),
'result': False})
else:
changes = {'new': {'acl_name': ', '.join(acl_names),
'acl_type': acl_type,
'perms': perms}}
if __opts__['test']:
ret.update({'comment': 'New permissions will be applied for '
'{0}: {1}'.format(acl_names, perms),
'result': None, 'changes': changes})
ret['result'] = None
return ret
try:
if force:
__salt__['acl.wipefacls'](name, recursive=recurse, raise_err=True)
for acl_name in acl_names:
__salt__['acl.modfacl'](acl_type, acl_name, perms, name,
recursive=recurse, raise_err=True)
ret.update({'comment': 'Applied new permissions for '
'{0}'.format(', '.join(acl_names)),
'result': True, 'changes': changes})
except CommandExecutionError as exc:
ret.update({'comment': 'Error updating permissions for {0}: '
'{1}'.format(acl_names, exc.strerror),
'result': False})
else:
changes = {'new': {'acl_name': ', '.join(acl_names),
'acl_type': acl_type,
'perms': perms}}
if __opts__['test']:
ret.update({'comment': 'New permissions will be applied for '
'{0}: {1}'.format(acl_names, perms),
'result': None, 'changes': changes})
ret['result'] = None
return ret
try:
if force:
__salt__['acl.wipefacls'](name, recursive=recurse, raise_err=True)
for acl_name in acl_names:
__salt__['acl.modfacl'](acl_type, acl_name, perms, name,
recursive=recurse, raise_err=True)
ret.update({'comment': 'Applied new permissions for '
'{0}'.format(', '.join(acl_names)),
'result': True, 'changes': changes})
except CommandExecutionError as exc:
ret.update({'comment': 'Error updating permissions for {0}: '
'{1}'.format(acl_names, exc.strerror),
'result': False})
else:
ret['comment'] = 'ACL Type does not exist'
ret['result'] = False
return ret | python | def list_present(name, acl_type, acl_names=None, perms='', recurse=False, force=False):
'''
Ensure a Linux ACL list is present
Takes a list of acl names and add them to the given path
name
The acl path
acl_type
The type of the acl is used for it can be 'user' or 'group'
acl_names
The list of users or groups
perms
Set the permissions eg.: rwx
recurse
Set the permissions recursive in the path
force
Wipe out old permissions and ensure only the new permissions are set
'''
if acl_names is None:
acl_names = []
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
_octal = {'r': 4, 'w': 2, 'x': 1, '-': 0}
_octal_perms = sum([_octal.get(i, i) for i in perms])
if not os.path.exists(name):
ret['comment'] = '{0} does not exist'.format(name)
ret['result'] = False
return ret
__current_perms = __salt__['acl.getfacl'](name)
if acl_type.startswith(('d:', 'default:')):
_acl_type = ':'.join(acl_type.split(':')[1:])
_current_perms = __current_perms[name].get('defaults', {})
_default = True
else:
_acl_type = acl_type
_current_perms = __current_perms[name]
_default = False
_origin_group = _current_perms.get('comment', {}).get('group', None)
_origin_owner = _current_perms.get('comment', {}).get('owner', None)
_current_acl_types = []
diff_perms = False
for key in _current_perms[acl_type]:
for current_acl_name in key.keys():
_current_acl_types.append(current_acl_name.encode('utf-8'))
diff_perms = _octal_perms == key[current_acl_name]['octal']
if acl_type == 'user':
try:
_current_acl_types.remove(_origin_owner)
except ValueError:
pass
else:
try:
_current_acl_types.remove(_origin_group)
except ValueError:
pass
diff_acls = set(_current_acl_types) ^ set(acl_names)
if not diff_acls and diff_perms and not force:
ret = {'name': name,
'result': True,
'changes': {},
'comment': 'Permissions and {}s are in the desired state'.format(acl_type)}
return ret
# The getfacl execution module lists default with empty names as being
# applied to the user/group that owns the file, e.g.,
# default:group::rwx would be listed as default:group:root:rwx
# In this case, if acl_name is empty, we really want to search for root
# but still uses '' for other
# We search through the dictionary getfacl returns for the owner of the
# file if acl_name is empty.
if acl_names == '':
_search_names = __current_perms[name].get('comment').get(_acl_type, '')
else:
_search_names = acl_names
if _current_perms.get(_acl_type, None) or _default:
try:
users = {}
for i in _current_perms[_acl_type]:
if i and next(six.iterkeys(i)) in _search_names:
users.update(i)
except (AttributeError, KeyError):
users = None
if users:
changes = {}
for count, search_name in enumerate(_search_names):
if search_name in users:
if users[search_name]['octal'] == sum([_octal.get(i, i) for i in perms]):
ret['comment'] = 'Permissions are in the desired state'
else:
changes.update({'new': {'acl_name': ', '.join(acl_names),
'acl_type': acl_type,
'perms': _octal_perms},
'old': {'acl_name': ', '.join(acl_names),
'acl_type': acl_type,
'perms': six.text_type(users[search_name]['octal'])}})
if __opts__['test']:
ret.update({'comment': 'Updated permissions will be applied for '
'{0}: {1} -> {2}'.format(
acl_names,
six.text_type(users[search_name]['octal']),
perms),
'result': None, 'changes': changes})
return ret
try:
if force:
__salt__['acl.wipefacls'](name, recursive=recurse, raise_err=True)
for acl_name in acl_names:
__salt__['acl.modfacl'](acl_type, acl_name, perms, name,
recursive=recurse, raise_err=True)
ret.update({'comment': 'Updated permissions for '
'{0}'.format(acl_names),
'result': True, 'changes': changes})
except CommandExecutionError as exc:
ret.update({'comment': 'Error updating permissions for '
'{0}: {1}'.format(acl_names, exc.strerror),
'result': False})
else:
changes = {'new': {'acl_name': ', '.join(acl_names),
'acl_type': acl_type,
'perms': perms}}
if __opts__['test']:
ret.update({'comment': 'New permissions will be applied for '
'{0}: {1}'.format(acl_names, perms),
'result': None, 'changes': changes})
ret['result'] = None
return ret
try:
if force:
__salt__['acl.wipefacls'](name, recursive=recurse, raise_err=True)
for acl_name in acl_names:
__salt__['acl.modfacl'](acl_type, acl_name, perms, name,
recursive=recurse, raise_err=True)
ret.update({'comment': 'Applied new permissions for '
'{0}'.format(', '.join(acl_names)),
'result': True, 'changes': changes})
except CommandExecutionError as exc:
ret.update({'comment': 'Error updating permissions for {0}: '
'{1}'.format(acl_names, exc.strerror),
'result': False})
else:
changes = {'new': {'acl_name': ', '.join(acl_names),
'acl_type': acl_type,
'perms': perms}}
if __opts__['test']:
ret.update({'comment': 'New permissions will be applied for '
'{0}: {1}'.format(acl_names, perms),
'result': None, 'changes': changes})
ret['result'] = None
return ret
try:
if force:
__salt__['acl.wipefacls'](name, recursive=recurse, raise_err=True)
for acl_name in acl_names:
__salt__['acl.modfacl'](acl_type, acl_name, perms, name,
recursive=recurse, raise_err=True)
ret.update({'comment': 'Applied new permissions for '
'{0}'.format(', '.join(acl_names)),
'result': True, 'changes': changes})
except CommandExecutionError as exc:
ret.update({'comment': 'Error updating permissions for {0}: '
'{1}'.format(acl_names, exc.strerror),
'result': False})
else:
ret['comment'] = 'ACL Type does not exist'
ret['result'] = False
return ret | [
"def",
"list_present",
"(",
"name",
",",
"acl_type",
",",
"acl_names",
"=",
"None",
",",
"perms",
"=",
"''",
",",
"recurse",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"if",
"acl_names",
"is",
"None",
":",
"acl_names",
"=",
"[",
"]",
"ret",
... | Ensure a Linux ACL list is present
Takes a list of acl names and add them to the given path
name
The acl path
acl_type
The type of the acl is used for it can be 'user' or 'group'
acl_names
The list of users or groups
perms
Set the permissions eg.: rwx
recurse
Set the permissions recursive in the path
force
Wipe out old permissions and ensure only the new permissions are set | [
"Ensure",
"a",
"Linux",
"ACL",
"list",
"is",
"present"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/linux_acl.py#L310-L499 | train |
saltstack/salt | salt/states/linux_acl.py | list_absent | def list_absent(name, acl_type, acl_names=None, recurse=False):
'''
Ensure a Linux ACL list does not exist
Takes a list of acl names and remove them from the given path
name
The acl path
acl_type
The type of the acl is used for, it can be 'user' or 'group'
acl_names
The list of users or groups
perms
Remove the permissions eg.: rwx
recurse
Set the permissions recursive in the path
'''
if acl_names is None:
acl_names = []
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if not os.path.exists(name):
ret['comment'] = '{0} does not exist'.format(name)
ret['result'] = False
return ret
__current_perms = __salt__['acl.getfacl'](name)
if acl_type.startswith(('d:', 'default:')):
_acl_type = ':'.join(acl_type.split(':')[1:])
_current_perms = __current_perms[name].get('defaults', {})
_default = True
else:
_acl_type = acl_type
_current_perms = __current_perms[name]
_default = False
# The getfacl execution module lists default with empty names as being
# applied to the user/group that owns the file, e.g.,
# default:group::rwx would be listed as default:group:root:rwx
# In this case, if acl_name is empty, we really want to search for root
# but still uses '' for other
# We search through the dictionary getfacl returns for the owner of the
# file if acl_name is empty.
if not acl_names:
_search_names = set(__current_perms[name].get('comment').get(_acl_type, ''))
else:
_search_names = set(acl_names)
if _current_perms.get(_acl_type, None) or _default:
try:
users = {}
for i in _current_perms[_acl_type]:
if i and next(six.iterkeys(i)) in _search_names:
users.update(i)
except (AttributeError, KeyError):
users = None
if users:
ret['comment'] = 'Removing permissions'
if __opts__['test']:
ret['result'] = None
return ret
for acl_name in acl_names:
__salt__['acl.delfacl'](acl_type, acl_name, name, recursive=recurse)
else:
ret['comment'] = 'Permissions are in the desired state'
else:
ret['comment'] = 'ACL Type does not exist'
ret['result'] = False
return ret | python | def list_absent(name, acl_type, acl_names=None, recurse=False):
'''
Ensure a Linux ACL list does not exist
Takes a list of acl names and remove them from the given path
name
The acl path
acl_type
The type of the acl is used for, it can be 'user' or 'group'
acl_names
The list of users or groups
perms
Remove the permissions eg.: rwx
recurse
Set the permissions recursive in the path
'''
if acl_names is None:
acl_names = []
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if not os.path.exists(name):
ret['comment'] = '{0} does not exist'.format(name)
ret['result'] = False
return ret
__current_perms = __salt__['acl.getfacl'](name)
if acl_type.startswith(('d:', 'default:')):
_acl_type = ':'.join(acl_type.split(':')[1:])
_current_perms = __current_perms[name].get('defaults', {})
_default = True
else:
_acl_type = acl_type
_current_perms = __current_perms[name]
_default = False
# The getfacl execution module lists default with empty names as being
# applied to the user/group that owns the file, e.g.,
# default:group::rwx would be listed as default:group:root:rwx
# In this case, if acl_name is empty, we really want to search for root
# but still uses '' for other
# We search through the dictionary getfacl returns for the owner of the
# file if acl_name is empty.
if not acl_names:
_search_names = set(__current_perms[name].get('comment').get(_acl_type, ''))
else:
_search_names = set(acl_names)
if _current_perms.get(_acl_type, None) or _default:
try:
users = {}
for i in _current_perms[_acl_type]:
if i and next(six.iterkeys(i)) in _search_names:
users.update(i)
except (AttributeError, KeyError):
users = None
if users:
ret['comment'] = 'Removing permissions'
if __opts__['test']:
ret['result'] = None
return ret
for acl_name in acl_names:
__salt__['acl.delfacl'](acl_type, acl_name, name, recursive=recurse)
else:
ret['comment'] = 'Permissions are in the desired state'
else:
ret['comment'] = 'ACL Type does not exist'
ret['result'] = False
return ret | [
"def",
"list_absent",
"(",
"name",
",",
"acl_type",
",",
"acl_names",
"=",
"None",
",",
"recurse",
"=",
"False",
")",
":",
"if",
"acl_names",
"is",
"None",
":",
"acl_names",
"=",
"[",
"]",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",... | Ensure a Linux ACL list does not exist
Takes a list of acl names and remove them from the given path
name
The acl path
acl_type
The type of the acl is used for, it can be 'user' or 'group'
acl_names
The list of users or groups
perms
Remove the permissions eg.: rwx
recurse
Set the permissions recursive in the path | [
"Ensure",
"a",
"Linux",
"ACL",
"list",
"does",
"not",
"exist"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/linux_acl.py#L502-L584 | train |
saltstack/salt | salt/states/boto_cognitoidentity.py | _get_object | def _get_object(objname, objtype):
'''
Helper function to retrieve objtype from pillars if objname
is string_types, used for SupportedLoginProviders and
OpenIdConnectProviderARNs.
'''
ret = None
if objname is None:
return ret
if isinstance(objname, string_types):
if objname in __opts__:
ret = __opts__[objname]
master_opts = __pillar__.get('master', {})
if objname in master_opts:
ret = master_opts[objname]
if objname in __pillar__:
ret = __pillar__[objname]
elif isinstance(objname, objtype):
ret = objname
if not isinstance(ret, objtype):
ret = None
return ret | python | def _get_object(objname, objtype):
'''
Helper function to retrieve objtype from pillars if objname
is string_types, used for SupportedLoginProviders and
OpenIdConnectProviderARNs.
'''
ret = None
if objname is None:
return ret
if isinstance(objname, string_types):
if objname in __opts__:
ret = __opts__[objname]
master_opts = __pillar__.get('master', {})
if objname in master_opts:
ret = master_opts[objname]
if objname in __pillar__:
ret = __pillar__[objname]
elif isinstance(objname, objtype):
ret = objname
if not isinstance(ret, objtype):
ret = None
return ret | [
"def",
"_get_object",
"(",
"objname",
",",
"objtype",
")",
":",
"ret",
"=",
"None",
"if",
"objname",
"is",
"None",
":",
"return",
"ret",
"if",
"isinstance",
"(",
"objname",
",",
"string_types",
")",
":",
"if",
"objname",
"in",
"__opts__",
":",
"ret",
"... | Helper function to retrieve objtype from pillars if objname
is string_types, used for SupportedLoginProviders and
OpenIdConnectProviderARNs. | [
"Helper",
"function",
"to",
"retrieve",
"objtype",
"from",
"pillars",
"if",
"objname",
"is",
"string_types",
"used",
"for",
"SupportedLoginProviders",
"and",
"OpenIdConnectProviderARNs",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_cognitoidentity.py#L66-L90 | train |
saltstack/salt | salt/states/boto_cognitoidentity.py | _role_present | def _role_present(ret, IdentityPoolId, AuthenticatedRole, UnauthenticatedRole, conn_params):
'''
Helper function to set the Roles to the identity pool
'''
r = __salt__['boto_cognitoidentity.get_identity_pool_roles'](IdentityPoolName='',
IdentityPoolId=IdentityPoolId,
**conn_params)
if r.get('error'):
ret['result'] = False
failure_comment = ('Failed to get existing identity pool roles: '
'{0}'.format(r['error'].get('message', r['error'])))
ret['comment'] = '{0}\n{1}'.format(ret['comment'], failure_comment)
return
existing_identity_pool_role = r.get('identity_pool_roles')[0].get('Roles', {})
r = __salt__['boto_cognitoidentity.set_identity_pool_roles'](IdentityPoolId=IdentityPoolId,
AuthenticatedRole=AuthenticatedRole,
UnauthenticatedRole=UnauthenticatedRole,
**conn_params)
if not r.get('set'):
ret['result'] = False
failure_comment = ('Failed to set roles: '
'{0}'.format(r['error'].get('message', r['error'])))
ret['comment'] = '{0}\n{1}'.format(ret['comment'], failure_comment)
return
updated_identity_pool_role = r.get('roles')
if existing_identity_pool_role != updated_identity_pool_role:
if not ret['changes']:
ret['changes']['old'] = dict()
ret['changes']['new'] = dict()
ret['changes']['old']['Roles'] = existing_identity_pool_role
ret['changes']['new']['Roles'] = r.get('roles')
ret['comment'] = ('{0}\n{1}'.format(ret['comment'], 'identity pool roles updated.'))
else:
ret['comment'] = ('{0}\n{1}'.format(ret['comment'], 'identity pool roles is already current.'))
return | python | def _role_present(ret, IdentityPoolId, AuthenticatedRole, UnauthenticatedRole, conn_params):
'''
Helper function to set the Roles to the identity pool
'''
r = __salt__['boto_cognitoidentity.get_identity_pool_roles'](IdentityPoolName='',
IdentityPoolId=IdentityPoolId,
**conn_params)
if r.get('error'):
ret['result'] = False
failure_comment = ('Failed to get existing identity pool roles: '
'{0}'.format(r['error'].get('message', r['error'])))
ret['comment'] = '{0}\n{1}'.format(ret['comment'], failure_comment)
return
existing_identity_pool_role = r.get('identity_pool_roles')[0].get('Roles', {})
r = __salt__['boto_cognitoidentity.set_identity_pool_roles'](IdentityPoolId=IdentityPoolId,
AuthenticatedRole=AuthenticatedRole,
UnauthenticatedRole=UnauthenticatedRole,
**conn_params)
if not r.get('set'):
ret['result'] = False
failure_comment = ('Failed to set roles: '
'{0}'.format(r['error'].get('message', r['error'])))
ret['comment'] = '{0}\n{1}'.format(ret['comment'], failure_comment)
return
updated_identity_pool_role = r.get('roles')
if existing_identity_pool_role != updated_identity_pool_role:
if not ret['changes']:
ret['changes']['old'] = dict()
ret['changes']['new'] = dict()
ret['changes']['old']['Roles'] = existing_identity_pool_role
ret['changes']['new']['Roles'] = r.get('roles')
ret['comment'] = ('{0}\n{1}'.format(ret['comment'], 'identity pool roles updated.'))
else:
ret['comment'] = ('{0}\n{1}'.format(ret['comment'], 'identity pool roles is already current.'))
return | [
"def",
"_role_present",
"(",
"ret",
",",
"IdentityPoolId",
",",
"AuthenticatedRole",
",",
"UnauthenticatedRole",
",",
"conn_params",
")",
":",
"r",
"=",
"__salt__",
"[",
"'boto_cognitoidentity.get_identity_pool_roles'",
"]",
"(",
"IdentityPoolName",
"=",
"''",
",",
... | Helper function to set the Roles to the identity pool | [
"Helper",
"function",
"to",
"set",
"the",
"Roles",
"to",
"the",
"identity",
"pool"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_cognitoidentity.py#L93-L131 | train |
saltstack/salt | salt/states/boto_cognitoidentity.py | pool_present | def pool_present(name,
IdentityPoolName,
AuthenticatedRole,
AllowUnauthenticatedIdentities=False,
UnauthenticatedRole=None,
SupportedLoginProviders=None,
DeveloperProviderName=None,
OpenIdConnectProviderARNs=None,
region=None, key=None, keyid=None, profile=None):
'''
Ensure Cognito Identity Pool exists.
name
The name of the state definition
IdentityPoolName
Name of the Cognito Identity Pool
AuthenticatedRole
An IAM role name or ARN that will be associated with temporary AWS
credentials for an authenticated cognito identity.
AllowUnauthenticatedIdentities
Whether to allow anonymous user identities
UnauthenticatedRole
An IAM role name or ARN that will be associated with anonymous
user identities
SupportedLoginProviders
A dictionary or pillar that contains key:value pairs mapping provider
names to provider app IDs.
DeveloperProviderName
A string which is the domain by which Cognito will refer to your users.
This name acts as a placeholder that allows your backend and the Cognito
service to communicate about the developer provider. Once you have set a
developer provider name, you cannot change it. Please take care in setting
this parameter.
OpenIdConnectProviderARNs
A list or pillar name that contains a list of OpenID Connect provider ARNs.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': IdentityPoolName,
'result': True,
'comment': '',
'changes': {}}
conn_params = dict(region=region, key=key, keyid=keyid, profile=profile)
r = __salt__['boto_cognitoidentity.describe_identity_pools'](IdentityPoolName=IdentityPoolName,
**conn_params)
if r.get('error'):
ret['result'] = False
ret['comment'] = 'Failed to describe identity pools {0}'.format(r['error']['message'])
return ret
identity_pools = r.get('identity_pools')
if identity_pools and len(identity_pools) > 1:
ret['result'] = False
ret['comment'] = ('More than one identity pool for the given name matched '
'Cannot execute pool_present function.\n'
'Matched Identity Pools:\n{0}'.format(identity_pools))
return ret
existing_identity_pool = None if identity_pools is None else identity_pools[0]
IdentityPoolId = None if existing_identity_pool is None else existing_identity_pool.get('IdentityPoolId')
if __opts__['test']:
if identity_pools is None:
ret['comment'] = ('A new identity pool named {0} will be '
'created.'.format(IdentityPoolName))
else:
ret['comment'] = ('An existing identity pool named {0} with id '
'{1}will be updated.'.format(IdentityPoolName,
IdentityPoolId))
ret['result'] = None
return ret
SupportedLoginProviders = _get_object(SupportedLoginProviders, dict)
OpenIdConnectProviderARNs = _get_object(OpenIdConnectProviderARNs, list)
request_params = dict(IdentityPoolName=IdentityPoolName,
AllowUnauthenticatedIdentities=AllowUnauthenticatedIdentities,
SupportedLoginProviders=SupportedLoginProviders,
DeveloperProviderName=DeveloperProviderName,
OpenIdConnectProviderARNs=OpenIdConnectProviderARNs)
request_params.update(conn_params)
updated_identity_pool = None
if IdentityPoolId is None:
r = __salt__['boto_cognitoidentity.create_identity_pool'](**request_params)
if r.get('created'):
updated_identity_pool = r.get('identity_pool')
IdentityPoolId = updated_identity_pool.get('IdentityPoolId')
ret['comment'] = ('A new identity pool with name {0}, id {1} '
'is created.'.format(IdentityPoolName, IdentityPoolId))
else:
ret['result'] = False
ret['comment'] = ('Failed to add a new identity pool: '
'{0}'.format(r['error'].get('message', r['error'])))
return ret
else: # Update an existing pool
request_params['IdentityPoolId'] = IdentityPoolId
# we will never change the IdentityPoolName from the state module
request_params.pop('IdentityPoolName', None)
r = __salt__['boto_cognitoidentity.update_identity_pool'](**request_params)
if r.get('updated'):
updated_identity_pool = r.get('identity_pool')
ret['comment'] = ('Existing identity pool with name {0}, id {1} '
'is updated.'.format(IdentityPoolName, IdentityPoolId))
else:
ret['result'] = False
ret['comment'] = ('Failed to update an existing identity pool {0} {1}: '
'{2}'.format(IdentityPoolName, IdentityPoolId,
r['error'].get('message', r['error'])))
return ret
if existing_identity_pool != updated_identity_pool:
ret['changes']['old'] = dict()
ret['changes']['new'] = dict()
change_key = 'Identity Pool Name {0}'.format(IdentityPoolName)
ret['changes']['old'][change_key] = existing_identity_pool
ret['changes']['new'][change_key] = updated_identity_pool
else:
ret['comment'] = 'Identity Pool state is current, no changes.'
# Now update the Auth/Unauth Roles
_role_present(ret, IdentityPoolId, AuthenticatedRole, UnauthenticatedRole, conn_params)
return ret | python | def pool_present(name,
IdentityPoolName,
AuthenticatedRole,
AllowUnauthenticatedIdentities=False,
UnauthenticatedRole=None,
SupportedLoginProviders=None,
DeveloperProviderName=None,
OpenIdConnectProviderARNs=None,
region=None, key=None, keyid=None, profile=None):
'''
Ensure Cognito Identity Pool exists.
name
The name of the state definition
IdentityPoolName
Name of the Cognito Identity Pool
AuthenticatedRole
An IAM role name or ARN that will be associated with temporary AWS
credentials for an authenticated cognito identity.
AllowUnauthenticatedIdentities
Whether to allow anonymous user identities
UnauthenticatedRole
An IAM role name or ARN that will be associated with anonymous
user identities
SupportedLoginProviders
A dictionary or pillar that contains key:value pairs mapping provider
names to provider app IDs.
DeveloperProviderName
A string which is the domain by which Cognito will refer to your users.
This name acts as a placeholder that allows your backend and the Cognito
service to communicate about the developer provider. Once you have set a
developer provider name, you cannot change it. Please take care in setting
this parameter.
OpenIdConnectProviderARNs
A list or pillar name that contains a list of OpenID Connect provider ARNs.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': IdentityPoolName,
'result': True,
'comment': '',
'changes': {}}
conn_params = dict(region=region, key=key, keyid=keyid, profile=profile)
r = __salt__['boto_cognitoidentity.describe_identity_pools'](IdentityPoolName=IdentityPoolName,
**conn_params)
if r.get('error'):
ret['result'] = False
ret['comment'] = 'Failed to describe identity pools {0}'.format(r['error']['message'])
return ret
identity_pools = r.get('identity_pools')
if identity_pools and len(identity_pools) > 1:
ret['result'] = False
ret['comment'] = ('More than one identity pool for the given name matched '
'Cannot execute pool_present function.\n'
'Matched Identity Pools:\n{0}'.format(identity_pools))
return ret
existing_identity_pool = None if identity_pools is None else identity_pools[0]
IdentityPoolId = None if existing_identity_pool is None else existing_identity_pool.get('IdentityPoolId')
if __opts__['test']:
if identity_pools is None:
ret['comment'] = ('A new identity pool named {0} will be '
'created.'.format(IdentityPoolName))
else:
ret['comment'] = ('An existing identity pool named {0} with id '
'{1}will be updated.'.format(IdentityPoolName,
IdentityPoolId))
ret['result'] = None
return ret
SupportedLoginProviders = _get_object(SupportedLoginProviders, dict)
OpenIdConnectProviderARNs = _get_object(OpenIdConnectProviderARNs, list)
request_params = dict(IdentityPoolName=IdentityPoolName,
AllowUnauthenticatedIdentities=AllowUnauthenticatedIdentities,
SupportedLoginProviders=SupportedLoginProviders,
DeveloperProviderName=DeveloperProviderName,
OpenIdConnectProviderARNs=OpenIdConnectProviderARNs)
request_params.update(conn_params)
updated_identity_pool = None
if IdentityPoolId is None:
r = __salt__['boto_cognitoidentity.create_identity_pool'](**request_params)
if r.get('created'):
updated_identity_pool = r.get('identity_pool')
IdentityPoolId = updated_identity_pool.get('IdentityPoolId')
ret['comment'] = ('A new identity pool with name {0}, id {1} '
'is created.'.format(IdentityPoolName, IdentityPoolId))
else:
ret['result'] = False
ret['comment'] = ('Failed to add a new identity pool: '
'{0}'.format(r['error'].get('message', r['error'])))
return ret
else: # Update an existing pool
request_params['IdentityPoolId'] = IdentityPoolId
# we will never change the IdentityPoolName from the state module
request_params.pop('IdentityPoolName', None)
r = __salt__['boto_cognitoidentity.update_identity_pool'](**request_params)
if r.get('updated'):
updated_identity_pool = r.get('identity_pool')
ret['comment'] = ('Existing identity pool with name {0}, id {1} '
'is updated.'.format(IdentityPoolName, IdentityPoolId))
else:
ret['result'] = False
ret['comment'] = ('Failed to update an existing identity pool {0} {1}: '
'{2}'.format(IdentityPoolName, IdentityPoolId,
r['error'].get('message', r['error'])))
return ret
if existing_identity_pool != updated_identity_pool:
ret['changes']['old'] = dict()
ret['changes']['new'] = dict()
change_key = 'Identity Pool Name {0}'.format(IdentityPoolName)
ret['changes']['old'][change_key] = existing_identity_pool
ret['changes']['new'][change_key] = updated_identity_pool
else:
ret['comment'] = 'Identity Pool state is current, no changes.'
# Now update the Auth/Unauth Roles
_role_present(ret, IdentityPoolId, AuthenticatedRole, UnauthenticatedRole, conn_params)
return ret | [
"def",
"pool_present",
"(",
"name",
",",
"IdentityPoolName",
",",
"AuthenticatedRole",
",",
"AllowUnauthenticatedIdentities",
"=",
"False",
",",
"UnauthenticatedRole",
"=",
"None",
",",
"SupportedLoginProviders",
"=",
"None",
",",
"DeveloperProviderName",
"=",
"None",
... | Ensure Cognito Identity Pool exists.
name
The name of the state definition
IdentityPoolName
Name of the Cognito Identity Pool
AuthenticatedRole
An IAM role name or ARN that will be associated with temporary AWS
credentials for an authenticated cognito identity.
AllowUnauthenticatedIdentities
Whether to allow anonymous user identities
UnauthenticatedRole
An IAM role name or ARN that will be associated with anonymous
user identities
SupportedLoginProviders
A dictionary or pillar that contains key:value pairs mapping provider
names to provider app IDs.
DeveloperProviderName
A string which is the domain by which Cognito will refer to your users.
This name acts as a placeholder that allows your backend and the Cognito
service to communicate about the developer provider. Once you have set a
developer provider name, you cannot change it. Please take care in setting
this parameter.
OpenIdConnectProviderARNs
A list or pillar name that contains a list of OpenID Connect provider ARNs.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid. | [
"Ensure",
"Cognito",
"Identity",
"Pool",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_cognitoidentity.py#L134-L279 | train |
saltstack/salt | salt/states/boto_cognitoidentity.py | pool_absent | def pool_absent(name, IdentityPoolName, RemoveAllMatched=False,
region=None, key=None, keyid=None, profile=None):
'''
Ensure cognito identity pool with passed properties is absent.
name
The name of the state definition.
IdentityPoolName
Name of the Cognito Identity Pool. Please note that this may
match multiple pools with the same given name, in which case,
all will be removed.
RemoveAllMatched
If True, all identity pools with the matching IdentityPoolName
will be removed. If False and there are more than one identity pool
with the matching IdentityPoolName, no action will be taken. If False
and there is only one identity pool with the matching IdentityPoolName,
the identity pool will be removed.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': IdentityPoolName,
'result': True,
'comment': '',
'changes': {}
}
conn_params = dict(region=region, key=key, keyid=keyid, profile=profile)
r = __salt__['boto_cognitoidentity.describe_identity_pools'](IdentityPoolName=IdentityPoolName,
**conn_params)
if r.get('error'):
ret['result'] = False
ret['comment'] = 'Failed to describe identity pools {0}'.format(r['error']['message'])
return ret
identity_pools = r.get('identity_pools')
if identity_pools is None:
ret['result'] = True
ret['comment'] = 'No matching identity pool for the given name {0}'.format(IdentityPoolName)
return ret
if not RemoveAllMatched and len(identity_pools) > 1:
ret['result'] = False
ret['comment'] = ('More than one identity pool for the given name matched '
'and RemoveAllMatched flag is False.\n'
'Matched Identity Pools:\n{0}'.format(identity_pools))
return ret
if __opts__['test']:
ret['comment'] = ('The following matched identity pools will be '
'deleted.\n{0}'.format(identity_pools))
ret['result'] = None
return ret
for identity_pool in identity_pools:
IdentityPoolId = identity_pool.get('IdentityPoolId')
r = __salt__['boto_cognitoidentity.delete_identity_pools'](IdentityPoolName='',
IdentityPoolId=IdentityPoolId,
**conn_params)
if r.get('error'):
ret['result'] = False
failure_comment = ('Failed to delete identity pool {0}: '
'{1}'.format(IdentityPoolId, r['error'].get('message', r['error'])))
ret['comment'] = '{0}\n{1}'.format(ret['comment'], failure_comment)
return ret
if r.get('deleted'):
if not ret['changes']:
ret['changes']['old'] = dict()
ret['changes']['new'] = dict()
change_key = 'Identity Pool Id {0}'.format(IdentityPoolId)
ret['changes']['old'][change_key] = IdentityPoolName
ret['changes']['new'][change_key] = None
ret['comment'] = '{0}\n{1}'.format(ret['comment'], '{0} deleted'.format(change_key))
else:
ret['result'] = False
failure_comment = 'Identity Pool Id {0} not deleted, returned count 0'.format(IdentityPoolId)
ret['comment'] = '{0}\n{1}'.format(ret['comment'], failure_comment)
return ret
return ret | python | def pool_absent(name, IdentityPoolName, RemoveAllMatched=False,
region=None, key=None, keyid=None, profile=None):
'''
Ensure cognito identity pool with passed properties is absent.
name
The name of the state definition.
IdentityPoolName
Name of the Cognito Identity Pool. Please note that this may
match multiple pools with the same given name, in which case,
all will be removed.
RemoveAllMatched
If True, all identity pools with the matching IdentityPoolName
will be removed. If False and there are more than one identity pool
with the matching IdentityPoolName, no action will be taken. If False
and there is only one identity pool with the matching IdentityPoolName,
the identity pool will be removed.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': IdentityPoolName,
'result': True,
'comment': '',
'changes': {}
}
conn_params = dict(region=region, key=key, keyid=keyid, profile=profile)
r = __salt__['boto_cognitoidentity.describe_identity_pools'](IdentityPoolName=IdentityPoolName,
**conn_params)
if r.get('error'):
ret['result'] = False
ret['comment'] = 'Failed to describe identity pools {0}'.format(r['error']['message'])
return ret
identity_pools = r.get('identity_pools')
if identity_pools is None:
ret['result'] = True
ret['comment'] = 'No matching identity pool for the given name {0}'.format(IdentityPoolName)
return ret
if not RemoveAllMatched and len(identity_pools) > 1:
ret['result'] = False
ret['comment'] = ('More than one identity pool for the given name matched '
'and RemoveAllMatched flag is False.\n'
'Matched Identity Pools:\n{0}'.format(identity_pools))
return ret
if __opts__['test']:
ret['comment'] = ('The following matched identity pools will be '
'deleted.\n{0}'.format(identity_pools))
ret['result'] = None
return ret
for identity_pool in identity_pools:
IdentityPoolId = identity_pool.get('IdentityPoolId')
r = __salt__['boto_cognitoidentity.delete_identity_pools'](IdentityPoolName='',
IdentityPoolId=IdentityPoolId,
**conn_params)
if r.get('error'):
ret['result'] = False
failure_comment = ('Failed to delete identity pool {0}: '
'{1}'.format(IdentityPoolId, r['error'].get('message', r['error'])))
ret['comment'] = '{0}\n{1}'.format(ret['comment'], failure_comment)
return ret
if r.get('deleted'):
if not ret['changes']:
ret['changes']['old'] = dict()
ret['changes']['new'] = dict()
change_key = 'Identity Pool Id {0}'.format(IdentityPoolId)
ret['changes']['old'][change_key] = IdentityPoolName
ret['changes']['new'][change_key] = None
ret['comment'] = '{0}\n{1}'.format(ret['comment'], '{0} deleted'.format(change_key))
else:
ret['result'] = False
failure_comment = 'Identity Pool Id {0} not deleted, returned count 0'.format(IdentityPoolId)
ret['comment'] = '{0}\n{1}'.format(ret['comment'], failure_comment)
return ret
return ret | [
"def",
"pool_absent",
"(",
"name",
",",
"IdentityPoolName",
",",
"RemoveAllMatched",
"=",
"False",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
... | Ensure cognito identity pool with passed properties is absent.
name
The name of the state definition.
IdentityPoolName
Name of the Cognito Identity Pool. Please note that this may
match multiple pools with the same given name, in which case,
all will be removed.
RemoveAllMatched
If True, all identity pools with the matching IdentityPoolName
will be removed. If False and there are more than one identity pool
with the matching IdentityPoolName, no action will be taken. If False
and there is only one identity pool with the matching IdentityPoolName,
the identity pool will be removed.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid. | [
"Ensure",
"cognito",
"identity",
"pool",
"with",
"passed",
"properties",
"is",
"absent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_cognitoidentity.py#L282-L378 | train |
saltstack/salt | salt/matchers/pcre_match.py | match | def match(tgt, opts=None):
'''
Returns true if the passed pcre regex matches
'''
if not opts:
return bool(re.match(tgt, __opts__['id']))
else:
return bool(re.match(tgt, opts['id'])) | python | def match(tgt, opts=None):
'''
Returns true if the passed pcre regex matches
'''
if not opts:
return bool(re.match(tgt, __opts__['id']))
else:
return bool(re.match(tgt, opts['id'])) | [
"def",
"match",
"(",
"tgt",
",",
"opts",
"=",
"None",
")",
":",
"if",
"not",
"opts",
":",
"return",
"bool",
"(",
"re",
".",
"match",
"(",
"tgt",
",",
"__opts__",
"[",
"'id'",
"]",
")",
")",
"else",
":",
"return",
"bool",
"(",
"re",
".",
"match"... | Returns true if the passed pcre regex matches | [
"Returns",
"true",
"if",
"the",
"passed",
"pcre",
"regex",
"matches"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/matchers/pcre_match.py#L10-L17 | train |
saltstack/salt | salt/utils/minion.py | running | def running(opts):
'''
Return the running jobs on this minion
'''
ret = []
proc_dir = os.path.join(opts['cachedir'], 'proc')
if not os.path.isdir(proc_dir):
return ret
for fn_ in os.listdir(proc_dir):
path = os.path.join(proc_dir, fn_)
try:
data = _read_proc_file(path, opts)
if data is not None:
ret.append(data)
except (IOError, OSError):
# proc files may be removed at any time during this process by
# the minion process that is executing the JID in question, so
# we must ignore ENOENT during this process
pass
return ret | python | def running(opts):
'''
Return the running jobs on this minion
'''
ret = []
proc_dir = os.path.join(opts['cachedir'], 'proc')
if not os.path.isdir(proc_dir):
return ret
for fn_ in os.listdir(proc_dir):
path = os.path.join(proc_dir, fn_)
try:
data = _read_proc_file(path, opts)
if data is not None:
ret.append(data)
except (IOError, OSError):
# proc files may be removed at any time during this process by
# the minion process that is executing the JID in question, so
# we must ignore ENOENT during this process
pass
return ret | [
"def",
"running",
"(",
"opts",
")",
":",
"ret",
"=",
"[",
"]",
"proc_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"opts",
"[",
"'cachedir'",
"]",
",",
"'proc'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"proc_dir",
")",
":",
"r... | Return the running jobs on this minion | [
"Return",
"the",
"running",
"jobs",
"on",
"this",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minion.py#L21-L41 | train |
saltstack/salt | salt/utils/minion.py | cache_jobs | def cache_jobs(opts, jid, ret):
'''
Write job information to cache
'''
serial = salt.payload.Serial(opts=opts)
fn_ = os.path.join(
opts['cachedir'],
'minion_jobs',
jid,
'return.p')
jdir = os.path.dirname(fn_)
if not os.path.isdir(jdir):
os.makedirs(jdir)
with salt.utils.files.fopen(fn_, 'w+b') as fp_:
fp_.write(serial.dumps(ret)) | python | def cache_jobs(opts, jid, ret):
'''
Write job information to cache
'''
serial = salt.payload.Serial(opts=opts)
fn_ = os.path.join(
opts['cachedir'],
'minion_jobs',
jid,
'return.p')
jdir = os.path.dirname(fn_)
if not os.path.isdir(jdir):
os.makedirs(jdir)
with salt.utils.files.fopen(fn_, 'w+b') as fp_:
fp_.write(serial.dumps(ret)) | [
"def",
"cache_jobs",
"(",
"opts",
",",
"jid",
",",
"ret",
")",
":",
"serial",
"=",
"salt",
".",
"payload",
".",
"Serial",
"(",
"opts",
"=",
"opts",
")",
"fn_",
"=",
"os",
".",
"path",
".",
"join",
"(",
"opts",
"[",
"'cachedir'",
"]",
",",
"'minio... | Write job information to cache | [
"Write",
"job",
"information",
"to",
"cache"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minion.py#L44-L59 | train |
saltstack/salt | salt/utils/minion.py | _read_proc_file | def _read_proc_file(path, opts):
'''
Return a dict of JID metadata, or None
'''
serial = salt.payload.Serial(opts)
current_thread = threading.currentThread().name
pid = os.getpid()
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
fp_.close()
if buf:
data = serial.loads(buf)
else:
# Proc file is empty, remove
try:
os.remove(path)
except IOError:
log.debug('Unable to remove proc file %s.', path)
return None
if not isinstance(data, dict):
# Invalid serial object
return None
if not salt.utils.process.os_is_running(data['pid']):
# The process is no longer running, clear out the file and
# continue
try:
os.remove(path)
except IOError:
log.debug('Unable to remove proc file %s.', path)
return None
if opts.get('multiprocessing'):
if data.get('pid') == pid:
return None
else:
if data.get('pid') != pid:
try:
os.remove(path)
except IOError:
log.debug('Unable to remove proc file %s.', path)
return None
if data.get('jid') == current_thread:
return None
if not data.get('jid') in [x.name for x in threading.enumerate()]:
try:
os.remove(path)
except IOError:
log.debug('Unable to remove proc file %s.', path)
return None
if not _check_cmdline(data):
pid = data.get('pid')
if pid:
log.warning(
'PID %s exists but does not appear to be a salt process.', pid
)
try:
os.remove(path)
except IOError:
log.debug('Unable to remove proc file %s.', path)
return None
return data | python | def _read_proc_file(path, opts):
'''
Return a dict of JID metadata, or None
'''
serial = salt.payload.Serial(opts)
current_thread = threading.currentThread().name
pid = os.getpid()
with salt.utils.files.fopen(path, 'rb') as fp_:
buf = fp_.read()
fp_.close()
if buf:
data = serial.loads(buf)
else:
# Proc file is empty, remove
try:
os.remove(path)
except IOError:
log.debug('Unable to remove proc file %s.', path)
return None
if not isinstance(data, dict):
# Invalid serial object
return None
if not salt.utils.process.os_is_running(data['pid']):
# The process is no longer running, clear out the file and
# continue
try:
os.remove(path)
except IOError:
log.debug('Unable to remove proc file %s.', path)
return None
if opts.get('multiprocessing'):
if data.get('pid') == pid:
return None
else:
if data.get('pid') != pid:
try:
os.remove(path)
except IOError:
log.debug('Unable to remove proc file %s.', path)
return None
if data.get('jid') == current_thread:
return None
if not data.get('jid') in [x.name for x in threading.enumerate()]:
try:
os.remove(path)
except IOError:
log.debug('Unable to remove proc file %s.', path)
return None
if not _check_cmdline(data):
pid = data.get('pid')
if pid:
log.warning(
'PID %s exists but does not appear to be a salt process.', pid
)
try:
os.remove(path)
except IOError:
log.debug('Unable to remove proc file %s.', path)
return None
return data | [
"def",
"_read_proc_file",
"(",
"path",
",",
"opts",
")",
":",
"serial",
"=",
"salt",
".",
"payload",
".",
"Serial",
"(",
"opts",
")",
"current_thread",
"=",
"threading",
".",
"currentThread",
"(",
")",
".",
"name",
"pid",
"=",
"os",
".",
"getpid",
"(",... | Return a dict of JID metadata, or None | [
"Return",
"a",
"dict",
"of",
"JID",
"metadata",
"or",
"None"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minion.py#L62-L122 | train |
saltstack/salt | salt/utils/minion.py | _check_cmdline | def _check_cmdline(data):
'''
In some cases where there are an insane number of processes being created
on a system a PID can get recycled or assigned to a non-Salt process.
On Linux this fn checks to make sure the PID we are checking on is actually
a Salt process.
For non-Linux systems we punt and just return True
'''
if not salt.utils.platform.is_linux():
return True
pid = data.get('pid')
if not pid:
return False
if not os.path.isdir('/proc'):
return True
path = os.path.join('/proc/{0}/cmdline'.format(pid))
if not os.path.isfile(path):
return False
try:
with salt.utils.files.fopen(path, 'rb') as fp_:
if b'salt' in fp_.read():
return True
except (OSError, IOError):
return False | python | def _check_cmdline(data):
'''
In some cases where there are an insane number of processes being created
on a system a PID can get recycled or assigned to a non-Salt process.
On Linux this fn checks to make sure the PID we are checking on is actually
a Salt process.
For non-Linux systems we punt and just return True
'''
if not salt.utils.platform.is_linux():
return True
pid = data.get('pid')
if not pid:
return False
if not os.path.isdir('/proc'):
return True
path = os.path.join('/proc/{0}/cmdline'.format(pid))
if not os.path.isfile(path):
return False
try:
with salt.utils.files.fopen(path, 'rb') as fp_:
if b'salt' in fp_.read():
return True
except (OSError, IOError):
return False | [
"def",
"_check_cmdline",
"(",
"data",
")",
":",
"if",
"not",
"salt",
".",
"utils",
".",
"platform",
".",
"is_linux",
"(",
")",
":",
"return",
"True",
"pid",
"=",
"data",
".",
"get",
"(",
"'pid'",
")",
"if",
"not",
"pid",
":",
"return",
"False",
"if... | In some cases where there are an insane number of processes being created
on a system a PID can get recycled or assigned to a non-Salt process.
On Linux this fn checks to make sure the PID we are checking on is actually
a Salt process.
For non-Linux systems we punt and just return True | [
"In",
"some",
"cases",
"where",
"there",
"are",
"an",
"insane",
"number",
"of",
"processes",
"being",
"created",
"on",
"a",
"system",
"a",
"PID",
"can",
"get",
"recycled",
"or",
"assigned",
"to",
"a",
"non",
"-",
"Salt",
"process",
".",
"On",
"Linux",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minion.py#L125-L149 | train |
saltstack/salt | salt/pillar/file_tree.py | _check_newline | def _check_newline(prefix, file_name, keep_newline):
'''
Return a boolean stating whether or not a file's trailing newline should be
removed. To figure this out, first check if keep_newline is a boolean and
if so, return its opposite. Otherwise, iterate over keep_newline and check
if any of the patterns match the file path. If a match is found, return
False, otherwise return True.
'''
if isinstance(keep_newline, bool):
return not keep_newline
full_path = os.path.join(prefix, file_name)
for pattern in keep_newline:
try:
if fnmatch.fnmatch(full_path, pattern):
return False
except TypeError:
if fnmatch.fnmatch(full_path, six.text_type(pattern)):
return False
return True | python | def _check_newline(prefix, file_name, keep_newline):
'''
Return a boolean stating whether or not a file's trailing newline should be
removed. To figure this out, first check if keep_newline is a boolean and
if so, return its opposite. Otherwise, iterate over keep_newline and check
if any of the patterns match the file path. If a match is found, return
False, otherwise return True.
'''
if isinstance(keep_newline, bool):
return not keep_newline
full_path = os.path.join(prefix, file_name)
for pattern in keep_newline:
try:
if fnmatch.fnmatch(full_path, pattern):
return False
except TypeError:
if fnmatch.fnmatch(full_path, six.text_type(pattern)):
return False
return True | [
"def",
"_check_newline",
"(",
"prefix",
",",
"file_name",
",",
"keep_newline",
")",
":",
"if",
"isinstance",
"(",
"keep_newline",
",",
"bool",
")",
":",
"return",
"not",
"keep_newline",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"prefix",
",",
... | Return a boolean stating whether or not a file's trailing newline should be
removed. To figure this out, first check if keep_newline is a boolean and
if so, return its opposite. Otherwise, iterate over keep_newline and check
if any of the patterns match the file path. If a match is found, return
False, otherwise return True. | [
"Return",
"a",
"boolean",
"stating",
"whether",
"or",
"not",
"a",
"file",
"s",
"trailing",
"newline",
"should",
"be",
"removed",
".",
"To",
"figure",
"this",
"out",
"first",
"check",
"if",
"keep_newline",
"is",
"a",
"boolean",
"and",
"if",
"so",
"return",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/file_tree.py#L174-L192 | train |
saltstack/salt | salt/pillar/file_tree.py | _construct_pillar | def _construct_pillar(top_dir,
follow_dir_links,
keep_newline=False,
render_default=None,
renderer_blacklist=None,
renderer_whitelist=None,
template=False):
'''
Construct pillar from file tree.
'''
pillar = {}
renderers = salt.loader.render(__opts__, __salt__)
norm_top_dir = os.path.normpath(top_dir)
for dir_path, dir_names, file_names in salt.utils.path.os_walk(
top_dir, topdown=True, onerror=_on_walk_error,
followlinks=follow_dir_links):
# Find current path in pillar tree
pillar_node = pillar
norm_dir_path = os.path.normpath(dir_path)
prefix = os.path.relpath(norm_dir_path, norm_top_dir)
if norm_dir_path != norm_top_dir:
path_parts = []
head = prefix
while head:
head, tail = os.path.split(head)
path_parts.insert(0, tail)
while path_parts:
pillar_node = pillar_node[path_parts.pop(0)]
# Create dicts for subdirectories
for dir_name in dir_names:
pillar_node[dir_name] = {}
# Add files
for file_name in file_names:
file_path = os.path.join(dir_path, file_name)
if not os.path.isfile(file_path):
log.error('file_tree: %s: not a regular file', file_path)
continue
contents = b''
try:
with salt.utils.files.fopen(file_path, 'rb') as fhr:
buf = fhr.read(__opts__['file_buffer_size'])
while buf:
contents += buf
buf = fhr.read(__opts__['file_buffer_size'])
if contents.endswith(b'\n') \
and _check_newline(prefix,
file_name,
keep_newline):
contents = contents[:-1]
except (IOError, OSError) as exc:
log.error('file_tree: Error reading %s: %s',
file_path,
exc.strerror)
else:
data = contents
if template is True:
data = salt.template.compile_template_str(template=salt.utils.stringutils.to_unicode(contents),
renderers=renderers,
default=render_default,
blacklist=renderer_blacklist,
whitelist=renderer_whitelist)
if salt.utils.stringio.is_readable(data):
pillar_node[file_name] = data.getvalue()
else:
pillar_node[file_name] = data
return pillar | python | def _construct_pillar(top_dir,
follow_dir_links,
keep_newline=False,
render_default=None,
renderer_blacklist=None,
renderer_whitelist=None,
template=False):
'''
Construct pillar from file tree.
'''
pillar = {}
renderers = salt.loader.render(__opts__, __salt__)
norm_top_dir = os.path.normpath(top_dir)
for dir_path, dir_names, file_names in salt.utils.path.os_walk(
top_dir, topdown=True, onerror=_on_walk_error,
followlinks=follow_dir_links):
# Find current path in pillar tree
pillar_node = pillar
norm_dir_path = os.path.normpath(dir_path)
prefix = os.path.relpath(norm_dir_path, norm_top_dir)
if norm_dir_path != norm_top_dir:
path_parts = []
head = prefix
while head:
head, tail = os.path.split(head)
path_parts.insert(0, tail)
while path_parts:
pillar_node = pillar_node[path_parts.pop(0)]
# Create dicts for subdirectories
for dir_name in dir_names:
pillar_node[dir_name] = {}
# Add files
for file_name in file_names:
file_path = os.path.join(dir_path, file_name)
if not os.path.isfile(file_path):
log.error('file_tree: %s: not a regular file', file_path)
continue
contents = b''
try:
with salt.utils.files.fopen(file_path, 'rb') as fhr:
buf = fhr.read(__opts__['file_buffer_size'])
while buf:
contents += buf
buf = fhr.read(__opts__['file_buffer_size'])
if contents.endswith(b'\n') \
and _check_newline(prefix,
file_name,
keep_newline):
contents = contents[:-1]
except (IOError, OSError) as exc:
log.error('file_tree: Error reading %s: %s',
file_path,
exc.strerror)
else:
data = contents
if template is True:
data = salt.template.compile_template_str(template=salt.utils.stringutils.to_unicode(contents),
renderers=renderers,
default=render_default,
blacklist=renderer_blacklist,
whitelist=renderer_whitelist)
if salt.utils.stringio.is_readable(data):
pillar_node[file_name] = data.getvalue()
else:
pillar_node[file_name] = data
return pillar | [
"def",
"_construct_pillar",
"(",
"top_dir",
",",
"follow_dir_links",
",",
"keep_newline",
"=",
"False",
",",
"render_default",
"=",
"None",
",",
"renderer_blacklist",
"=",
"None",
",",
"renderer_whitelist",
"=",
"None",
",",
"template",
"=",
"False",
")",
":",
... | Construct pillar from file tree. | [
"Construct",
"pillar",
"from",
"file",
"tree",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/file_tree.py#L195-L265 | train |
saltstack/salt | salt/pillar/file_tree.py | ext_pillar | def ext_pillar(minion_id,
pillar,
root_dir=None,
follow_dir_links=False,
debug=False,
keep_newline=False,
render_default=None,
renderer_blacklist=None,
renderer_whitelist=None,
template=False):
'''
Compile pillar data from the given ``root_dir`` specific to Nodegroup names
and Minion IDs.
If a Minion's ID is not found at ``<root_dir>/host/<minion_id>`` or if it
is not included in any Nodegroups named at
``<root_dir>/nodegroups/<node_group>``, no pillar data provided by this
pillar module will be available for that Minion.
.. versionchanged:: 2017.7.0
Templating/rendering has been added. You can now specify a default
render pipeline and a black- and whitelist of (dis)allowed renderers.
``template`` must be set to ``True`` for templating to happen.
.. code-block:: yaml
ext_pillar:
- file_tree:
root_dir: /path/to/root/directory
render_default: jinja|yaml
renderer_blacklist:
- gpg
renderer_whitelist:
- jinja
- yaml
template: True
:param minion_id:
The ID of the Minion whose pillar data is to be collected
:param pillar:
Unused by the ``file_tree`` pillar module
:param root_dir:
Filesystem directory used as the root for pillar data (e.g.
``/srv/ext_pillar``)
.. versionchanged:: 2018.3.0
If ``root_dir`` is a relative path, it will be treated as relative to the
:conf_master:`pillar_roots` of the environment specified by
:conf_minion:`pillarenv`. If an environment specifies multiple
roots, this module will search for files relative to all of them, in order,
merging the results.
:param follow_dir_links:
Follow symbolic links to directories while collecting pillar files.
Defaults to ``False``.
.. warning::
Care should be exercised when enabling this option as it will
follow links that point outside of ``root_dir``.
.. warning::
Symbolic links that lead to infinite recursion are not filtered.
:param debug:
Enable debug information at log level ``debug``. Defaults to
``False``. This option may be useful to help debug errors when setting
up the ``file_tree`` pillar module.
:param keep_newline:
Preserve the end-of-file newline in files. Defaults to ``False``.
This option may either be a boolean or a list of file globs (as defined
by the `Python fnmatch package
<https://docs.python.org/library/fnmatch.html>`_) for which end-of-file
newlines are to be kept.
``keep_newline`` should be turned on if the pillar data is intended to
be used to deploy a file using ``contents_pillar`` with a
:py:func:`file.managed <salt.states.file.managed>` state.
.. versionchanged:: 2015.8.4
The ``raw_data`` parameter has been renamed to ``keep_newline``. In
earlier releases, ``raw_data`` must be used. Also, this parameter
can now be a list of globs, allowing for more granular control over
which pillar values keep their end-of-file newline. The globs match
paths relative to the directories named for Minion IDs and
Nodegroup namess underneath the ``root_dir``.
.. code-block:: yaml
ext_pillar:
- file_tree:
root_dir: /srv/ext_pillar
keep_newline:
- apache/config.d/*
- corporate_app/settings/*
.. note::
In earlier releases, this documentation incorrectly stated that
binary files would not affected by the ``keep_newline``. However,
this module does not actually distinguish between binary and text
files.
:param render_default:
Override Salt's :conf_master:`default global renderer <renderer>` for
the ``file_tree`` pillar.
.. code-block:: yaml
render_default: jinja
:param renderer_blacklist:
Disallow renderers for pillar files.
.. code-block:: yaml
renderer_blacklist:
- json
:param renderer_whitelist:
Allow renderers for pillar files.
.. code-block:: yaml
renderer_whitelist:
- yaml
- jinja
:param template:
Enable templating of pillar files. Defaults to ``False``.
'''
# Not used
del pillar
if not root_dir:
log.error('file_tree: no root_dir specified')
return {}
if not os.path.isabs(root_dir):
pillarenv = __opts__['pillarenv']
if pillarenv is None:
log.error('file_tree: root_dir is relative but pillarenv is not set')
return {}
log.debug('file_tree: pillarenv = %s', pillarenv)
env_roots = __opts__['pillar_roots'].get(pillarenv, None)
if env_roots is None:
log.error('file_tree: root_dir is relative but no pillar_roots are specified '
' for pillarenv %s', pillarenv)
return {}
env_dirs = []
for env_root in env_roots:
env_dir = os.path.normpath(os.path.join(env_root, root_dir))
# don't redundantly load consecutively, but preserve any expected precedence
if env_dir not in env_dirs or env_dir != env_dirs[-1]:
env_dirs.append(env_dir)
dirs = env_dirs
else:
dirs = [root_dir]
result_pillar = {}
for root in dirs:
dir_pillar = _ext_pillar(minion_id,
root,
follow_dir_links,
debug,
keep_newline,
render_default,
renderer_blacklist,
renderer_whitelist,
template)
result_pillar = salt.utils.dictupdate.merge(result_pillar,
dir_pillar,
strategy='recurse')
return result_pillar | python | def ext_pillar(minion_id,
pillar,
root_dir=None,
follow_dir_links=False,
debug=False,
keep_newline=False,
render_default=None,
renderer_blacklist=None,
renderer_whitelist=None,
template=False):
'''
Compile pillar data from the given ``root_dir`` specific to Nodegroup names
and Minion IDs.
If a Minion's ID is not found at ``<root_dir>/host/<minion_id>`` or if it
is not included in any Nodegroups named at
``<root_dir>/nodegroups/<node_group>``, no pillar data provided by this
pillar module will be available for that Minion.
.. versionchanged:: 2017.7.0
Templating/rendering has been added. You can now specify a default
render pipeline and a black- and whitelist of (dis)allowed renderers.
``template`` must be set to ``True`` for templating to happen.
.. code-block:: yaml
ext_pillar:
- file_tree:
root_dir: /path/to/root/directory
render_default: jinja|yaml
renderer_blacklist:
- gpg
renderer_whitelist:
- jinja
- yaml
template: True
:param minion_id:
The ID of the Minion whose pillar data is to be collected
:param pillar:
Unused by the ``file_tree`` pillar module
:param root_dir:
Filesystem directory used as the root for pillar data (e.g.
``/srv/ext_pillar``)
.. versionchanged:: 2018.3.0
If ``root_dir`` is a relative path, it will be treated as relative to the
:conf_master:`pillar_roots` of the environment specified by
:conf_minion:`pillarenv`. If an environment specifies multiple
roots, this module will search for files relative to all of them, in order,
merging the results.
:param follow_dir_links:
Follow symbolic links to directories while collecting pillar files.
Defaults to ``False``.
.. warning::
Care should be exercised when enabling this option as it will
follow links that point outside of ``root_dir``.
.. warning::
Symbolic links that lead to infinite recursion are not filtered.
:param debug:
Enable debug information at log level ``debug``. Defaults to
``False``. This option may be useful to help debug errors when setting
up the ``file_tree`` pillar module.
:param keep_newline:
Preserve the end-of-file newline in files. Defaults to ``False``.
This option may either be a boolean or a list of file globs (as defined
by the `Python fnmatch package
<https://docs.python.org/library/fnmatch.html>`_) for which end-of-file
newlines are to be kept.
``keep_newline`` should be turned on if the pillar data is intended to
be used to deploy a file using ``contents_pillar`` with a
:py:func:`file.managed <salt.states.file.managed>` state.
.. versionchanged:: 2015.8.4
The ``raw_data`` parameter has been renamed to ``keep_newline``. In
earlier releases, ``raw_data`` must be used. Also, this parameter
can now be a list of globs, allowing for more granular control over
which pillar values keep their end-of-file newline. The globs match
paths relative to the directories named for Minion IDs and
Nodegroup namess underneath the ``root_dir``.
.. code-block:: yaml
ext_pillar:
- file_tree:
root_dir: /srv/ext_pillar
keep_newline:
- apache/config.d/*
- corporate_app/settings/*
.. note::
In earlier releases, this documentation incorrectly stated that
binary files would not affected by the ``keep_newline``. However,
this module does not actually distinguish between binary and text
files.
:param render_default:
Override Salt's :conf_master:`default global renderer <renderer>` for
the ``file_tree`` pillar.
.. code-block:: yaml
render_default: jinja
:param renderer_blacklist:
Disallow renderers for pillar files.
.. code-block:: yaml
renderer_blacklist:
- json
:param renderer_whitelist:
Allow renderers for pillar files.
.. code-block:: yaml
renderer_whitelist:
- yaml
- jinja
:param template:
Enable templating of pillar files. Defaults to ``False``.
'''
# Not used
del pillar
if not root_dir:
log.error('file_tree: no root_dir specified')
return {}
if not os.path.isabs(root_dir):
pillarenv = __opts__['pillarenv']
if pillarenv is None:
log.error('file_tree: root_dir is relative but pillarenv is not set')
return {}
log.debug('file_tree: pillarenv = %s', pillarenv)
env_roots = __opts__['pillar_roots'].get(pillarenv, None)
if env_roots is None:
log.error('file_tree: root_dir is relative but no pillar_roots are specified '
' for pillarenv %s', pillarenv)
return {}
env_dirs = []
for env_root in env_roots:
env_dir = os.path.normpath(os.path.join(env_root, root_dir))
# don't redundantly load consecutively, but preserve any expected precedence
if env_dir not in env_dirs or env_dir != env_dirs[-1]:
env_dirs.append(env_dir)
dirs = env_dirs
else:
dirs = [root_dir]
result_pillar = {}
for root in dirs:
dir_pillar = _ext_pillar(minion_id,
root,
follow_dir_links,
debug,
keep_newline,
render_default,
renderer_blacklist,
renderer_whitelist,
template)
result_pillar = salt.utils.dictupdate.merge(result_pillar,
dir_pillar,
strategy='recurse')
return result_pillar | [
"def",
"ext_pillar",
"(",
"minion_id",
",",
"pillar",
",",
"root_dir",
"=",
"None",
",",
"follow_dir_links",
"=",
"False",
",",
"debug",
"=",
"False",
",",
"keep_newline",
"=",
"False",
",",
"render_default",
"=",
"None",
",",
"renderer_blacklist",
"=",
"Non... | Compile pillar data from the given ``root_dir`` specific to Nodegroup names
and Minion IDs.
If a Minion's ID is not found at ``<root_dir>/host/<minion_id>`` or if it
is not included in any Nodegroups named at
``<root_dir>/nodegroups/<node_group>``, no pillar data provided by this
pillar module will be available for that Minion.
.. versionchanged:: 2017.7.0
Templating/rendering has been added. You can now specify a default
render pipeline and a black- and whitelist of (dis)allowed renderers.
``template`` must be set to ``True`` for templating to happen.
.. code-block:: yaml
ext_pillar:
- file_tree:
root_dir: /path/to/root/directory
render_default: jinja|yaml
renderer_blacklist:
- gpg
renderer_whitelist:
- jinja
- yaml
template: True
:param minion_id:
The ID of the Minion whose pillar data is to be collected
:param pillar:
Unused by the ``file_tree`` pillar module
:param root_dir:
Filesystem directory used as the root for pillar data (e.g.
``/srv/ext_pillar``)
.. versionchanged:: 2018.3.0
If ``root_dir`` is a relative path, it will be treated as relative to the
:conf_master:`pillar_roots` of the environment specified by
:conf_minion:`pillarenv`. If an environment specifies multiple
roots, this module will search for files relative to all of them, in order,
merging the results.
:param follow_dir_links:
Follow symbolic links to directories while collecting pillar files.
Defaults to ``False``.
.. warning::
Care should be exercised when enabling this option as it will
follow links that point outside of ``root_dir``.
.. warning::
Symbolic links that lead to infinite recursion are not filtered.
:param debug:
Enable debug information at log level ``debug``. Defaults to
``False``. This option may be useful to help debug errors when setting
up the ``file_tree`` pillar module.
:param keep_newline:
Preserve the end-of-file newline in files. Defaults to ``False``.
This option may either be a boolean or a list of file globs (as defined
by the `Python fnmatch package
<https://docs.python.org/library/fnmatch.html>`_) for which end-of-file
newlines are to be kept.
``keep_newline`` should be turned on if the pillar data is intended to
be used to deploy a file using ``contents_pillar`` with a
:py:func:`file.managed <salt.states.file.managed>` state.
.. versionchanged:: 2015.8.4
The ``raw_data`` parameter has been renamed to ``keep_newline``. In
earlier releases, ``raw_data`` must be used. Also, this parameter
can now be a list of globs, allowing for more granular control over
which pillar values keep their end-of-file newline. The globs match
paths relative to the directories named for Minion IDs and
Nodegroup namess underneath the ``root_dir``.
.. code-block:: yaml
ext_pillar:
- file_tree:
root_dir: /srv/ext_pillar
keep_newline:
- apache/config.d/*
- corporate_app/settings/*
.. note::
In earlier releases, this documentation incorrectly stated that
binary files would not affected by the ``keep_newline``. However,
this module does not actually distinguish between binary and text
files.
:param render_default:
Override Salt's :conf_master:`default global renderer <renderer>` for
the ``file_tree`` pillar.
.. code-block:: yaml
render_default: jinja
:param renderer_blacklist:
Disallow renderers for pillar files.
.. code-block:: yaml
renderer_blacklist:
- json
:param renderer_whitelist:
Allow renderers for pillar files.
.. code-block:: yaml
renderer_whitelist:
- yaml
- jinja
:param template:
Enable templating of pillar files. Defaults to ``False``. | [
"Compile",
"pillar",
"data",
"from",
"the",
"given",
"root_dir",
"specific",
"to",
"Nodegroup",
"names",
"and",
"Minion",
"IDs",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/file_tree.py#L268-L448 | train |
saltstack/salt | salt/pillar/file_tree.py | _ext_pillar | def _ext_pillar(minion_id,
root_dir,
follow_dir_links,
debug,
keep_newline,
render_default,
renderer_blacklist,
renderer_whitelist,
template):
'''
Compile pillar data for a single root_dir for the specified minion ID
'''
log.debug('file_tree: reading %s', root_dir)
if not os.path.isdir(root_dir):
log.error(
'file_tree: root_dir %s does not exist or is not a directory',
root_dir
)
return {}
if not isinstance(keep_newline, (bool, list)):
log.error(
'file_tree: keep_newline must be either True/False or a list '
'of file globs. Skipping this ext_pillar for root_dir %s',
root_dir
)
return {}
ngroup_pillar = {}
nodegroups_dir = os.path.join(root_dir, 'nodegroups')
if os.path.exists(nodegroups_dir) and __opts__.get('nodegroups'):
master_ngroups = __opts__['nodegroups']
ext_pillar_dirs = os.listdir(nodegroups_dir)
if ext_pillar_dirs:
for nodegroup in ext_pillar_dirs:
if (os.path.isdir(nodegroups_dir) and
nodegroup in master_ngroups):
ckminions = salt.utils.minions.CkMinions(__opts__)
_res = ckminions.check_minions(
master_ngroups[nodegroup],
'compound')
match = _res['minions']
if minion_id in match:
ngroup_dir = os.path.join(
nodegroups_dir, six.text_type(nodegroup))
ngroup_pillar = salt.utils.dictupdate.merge(ngroup_pillar,
_construct_pillar(ngroup_dir,
follow_dir_links,
keep_newline,
render_default,
renderer_blacklist,
renderer_whitelist,
template),
strategy='recurse'
)
else:
if debug is True:
log.debug(
'file_tree: no nodegroups found in file tree directory %s, skipping...',
ext_pillar_dirs
)
else:
if debug is True:
log.debug('file_tree: no nodegroups found in master configuration')
host_dir = os.path.join(root_dir, 'hosts', minion_id)
if not os.path.exists(host_dir):
if debug is True:
log.debug(
'file_tree: no pillar data for minion %s found in file tree directory %s',
minion_id,
host_dir
)
return ngroup_pillar
if not os.path.isdir(host_dir):
log.error('file_tree: %s exists, but is not a directory', host_dir)
return ngroup_pillar
host_pillar = _construct_pillar(host_dir,
follow_dir_links,
keep_newline,
render_default,
renderer_blacklist,
renderer_whitelist,
template)
return salt.utils.dictupdate.merge(ngroup_pillar,
host_pillar,
strategy='recurse') | python | def _ext_pillar(minion_id,
root_dir,
follow_dir_links,
debug,
keep_newline,
render_default,
renderer_blacklist,
renderer_whitelist,
template):
'''
Compile pillar data for a single root_dir for the specified minion ID
'''
log.debug('file_tree: reading %s', root_dir)
if not os.path.isdir(root_dir):
log.error(
'file_tree: root_dir %s does not exist or is not a directory',
root_dir
)
return {}
if not isinstance(keep_newline, (bool, list)):
log.error(
'file_tree: keep_newline must be either True/False or a list '
'of file globs. Skipping this ext_pillar for root_dir %s',
root_dir
)
return {}
ngroup_pillar = {}
nodegroups_dir = os.path.join(root_dir, 'nodegroups')
if os.path.exists(nodegroups_dir) and __opts__.get('nodegroups'):
master_ngroups = __opts__['nodegroups']
ext_pillar_dirs = os.listdir(nodegroups_dir)
if ext_pillar_dirs:
for nodegroup in ext_pillar_dirs:
if (os.path.isdir(nodegroups_dir) and
nodegroup in master_ngroups):
ckminions = salt.utils.minions.CkMinions(__opts__)
_res = ckminions.check_minions(
master_ngroups[nodegroup],
'compound')
match = _res['minions']
if minion_id in match:
ngroup_dir = os.path.join(
nodegroups_dir, six.text_type(nodegroup))
ngroup_pillar = salt.utils.dictupdate.merge(ngroup_pillar,
_construct_pillar(ngroup_dir,
follow_dir_links,
keep_newline,
render_default,
renderer_blacklist,
renderer_whitelist,
template),
strategy='recurse'
)
else:
if debug is True:
log.debug(
'file_tree: no nodegroups found in file tree directory %s, skipping...',
ext_pillar_dirs
)
else:
if debug is True:
log.debug('file_tree: no nodegroups found in master configuration')
host_dir = os.path.join(root_dir, 'hosts', minion_id)
if not os.path.exists(host_dir):
if debug is True:
log.debug(
'file_tree: no pillar data for minion %s found in file tree directory %s',
minion_id,
host_dir
)
return ngroup_pillar
if not os.path.isdir(host_dir):
log.error('file_tree: %s exists, but is not a directory', host_dir)
return ngroup_pillar
host_pillar = _construct_pillar(host_dir,
follow_dir_links,
keep_newline,
render_default,
renderer_blacklist,
renderer_whitelist,
template)
return salt.utils.dictupdate.merge(ngroup_pillar,
host_pillar,
strategy='recurse') | [
"def",
"_ext_pillar",
"(",
"minion_id",
",",
"root_dir",
",",
"follow_dir_links",
",",
"debug",
",",
"keep_newline",
",",
"render_default",
",",
"renderer_blacklist",
",",
"renderer_whitelist",
",",
"template",
")",
":",
"log",
".",
"debug",
"(",
"'file_tree: read... | Compile pillar data for a single root_dir for the specified minion ID | [
"Compile",
"pillar",
"data",
"for",
"a",
"single",
"root_dir",
"for",
"the",
"specified",
"minion",
"ID"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/file_tree.py#L451-L540 | train |
saltstack/salt | salt/states/at.py | present | def present(name, timespec, tag=None, user=None, job=None, unique_tag=False):
'''
.. versionchanged:: 2017.7.0
Add a job to queue.
job : string
Command to run.
timespec : string
The 'timespec' follows the format documented in the at(1) manpage.
tag : string
Make a tag for the job.
user : string
The user to run the at job
.. versionadded:: 2014.1.4
unique_tag : boolean
If set to True job will not be added if a job with the tag exists.
.. versionadded:: 2017.7.0
.. code-block:: yaml
rose:
at.present:
- job: 'echo "I love saltstack" > love'
- timespec: '9:09 11/09/13'
- tag: love
- user: jam
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# if job is missing, use name
if not job:
job = name
# quick return on test=True
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'job {0} added and will run on {1}'.format(
job,
timespec,
)
return ret
# quick return if unique_tag and job exists
if unique_tag:
if not tag:
ret['result'] = False
ret['comment'] = 'no tag provided and unique_tag is set to True'
return ret
elif __salt__['at.jobcheck'](tag=tag)['jobs']:
ret['comment'] = 'atleast one job with tag {tag} exists.'.format(
tag=tag
)
return ret
# create job
if user:
luser = __salt__['user.info'](user)
if not luser:
ret['result'] = False
ret['comment'] = 'user {0} does not exists'.format(user)
return ret
ret['comment'] = 'job {0} added and will run as {1} on {2}'.format(
job,
user,
timespec,
)
res = __salt__['at.at'](
timespec,
job,
tag=tag,
runas=user,
)
else:
ret['comment'] = 'job {0} added and will run on {1}'.format(
job,
timespec,
)
res = __salt__['at.at'](
timespec,
job,
tag=tag,
)
# set ret['changes']
if res.get('jobs'):
ret['changes'] = res['jobs'][0]
if 'error' in res:
ret['result'] = False
ret['comment'] = res['error']
return ret | python | def present(name, timespec, tag=None, user=None, job=None, unique_tag=False):
'''
.. versionchanged:: 2017.7.0
Add a job to queue.
job : string
Command to run.
timespec : string
The 'timespec' follows the format documented in the at(1) manpage.
tag : string
Make a tag for the job.
user : string
The user to run the at job
.. versionadded:: 2014.1.4
unique_tag : boolean
If set to True job will not be added if a job with the tag exists.
.. versionadded:: 2017.7.0
.. code-block:: yaml
rose:
at.present:
- job: 'echo "I love saltstack" > love'
- timespec: '9:09 11/09/13'
- tag: love
- user: jam
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# if job is missing, use name
if not job:
job = name
# quick return on test=True
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'job {0} added and will run on {1}'.format(
job,
timespec,
)
return ret
# quick return if unique_tag and job exists
if unique_tag:
if not tag:
ret['result'] = False
ret['comment'] = 'no tag provided and unique_tag is set to True'
return ret
elif __salt__['at.jobcheck'](tag=tag)['jobs']:
ret['comment'] = 'atleast one job with tag {tag} exists.'.format(
tag=tag
)
return ret
# create job
if user:
luser = __salt__['user.info'](user)
if not luser:
ret['result'] = False
ret['comment'] = 'user {0} does not exists'.format(user)
return ret
ret['comment'] = 'job {0} added and will run as {1} on {2}'.format(
job,
user,
timespec,
)
res = __salt__['at.at'](
timespec,
job,
tag=tag,
runas=user,
)
else:
ret['comment'] = 'job {0} added and will run on {1}'.format(
job,
timespec,
)
res = __salt__['at.at'](
timespec,
job,
tag=tag,
)
# set ret['changes']
if res.get('jobs'):
ret['changes'] = res['jobs'][0]
if 'error' in res:
ret['result'] = False
ret['comment'] = res['error']
return ret | [
"def",
"present",
"(",
"name",
",",
"timespec",
",",
"tag",
"=",
"None",
",",
"user",
"=",
"None",
",",
"job",
"=",
"None",
",",
"unique_tag",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
... | .. versionchanged:: 2017.7.0
Add a job to queue.
job : string
Command to run.
timespec : string
The 'timespec' follows the format documented in the at(1) manpage.
tag : string
Make a tag for the job.
user : string
The user to run the at job
.. versionadded:: 2014.1.4
unique_tag : boolean
If set to True job will not be added if a job with the tag exists.
.. versionadded:: 2017.7.0
.. code-block:: yaml
rose:
at.present:
- job: 'echo "I love saltstack" > love'
- timespec: '9:09 11/09/13'
- tag: love
- user: jam | [
"..",
"versionchanged",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/at.py#L26-L125 | train |
saltstack/salt | salt/states/at.py | absent | def absent(name, jobid=None, **kwargs):
'''
.. versionchanged:: 2017.7.0
Remove a job from queue
jobid: string|int
Specific jobid to remove
tag : string
Job's tag
runas : string
Runs user-specified jobs
kwargs
Addition kwargs can be provided to filter jobs.
See output of `at.jobcheck` for more.
.. code-block:: yaml
example1:
at.absent:
.. warning::
this will remove all jobs!
.. code-block:: yaml
example2:
at.absent:
- year: 13
.. code-block:: yaml
example3:
at.absent:
- tag: rose
.. code-block:: yaml
example4:
at.absent:
- tag: rose
- day: 13
- hour: 16
.. code-block:: yaml
example5:
at.absent:
- jobid: 4
.. note:
all other filters are ignored and only job with id 4 is removed
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# limit was never support
if 'limit' in kwargs:
ret['comment'] = 'limit parameter not supported {0}'.format(name)
ret['result'] = False
return ret
# quick return on test=True
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'removed ? job(s)'
return ret
# remove specific job
if jobid:
jobs = __salt__['at.atq'](jobid)
if jobs.get('jobs'):
ret['result'] = True
ret['comment'] = 'job with id {jobid} not present'.format(
jobid=jobid
)
return ret
elif 'jobs' in jobs and len(jobs['jobs']) == 1:
if 'job' in jobs['jobs'][0] and jobs['jobs'][0]['job']:
res = __salt__['at.atrm'](jobid)
ret['result'] = jobid in res['jobs']['removed']
if ret['result']:
ret['comment'] = 'job with id {jobid} was removed'.format(
jobid=jobid
)
else:
ret['comment'] = 'failed to remove job with id {jobid}'.format(
jobid=jobid
)
ret['changes']['removed'] = res['jobs']['removed']
return ret
else:
ret['result'] = False
ret['comment'] = 'more than one job was return for job with id {jobid}'.format(
jobid=jobid
)
return ret
# remove jobs based on filter
if kwargs:
# we pass kwargs to at.jobcheck
opts = list(list(map(str, [j['job'] for j in __salt__['at.jobcheck'](**kwargs)['jobs']])))
res = __salt__['at.atrm'](*opts)
else:
# arguments to filter with, removing everything!
res = __salt__['at.atrm']('all')
if res['jobs']['removed']:
ret['changes']['removed'] = res['jobs']['removed']
ret['comment'] = 'removed {count} job(s)'.format(
count=len(res['jobs']['removed'])
)
return ret | python | def absent(name, jobid=None, **kwargs):
'''
.. versionchanged:: 2017.7.0
Remove a job from queue
jobid: string|int
Specific jobid to remove
tag : string
Job's tag
runas : string
Runs user-specified jobs
kwargs
Addition kwargs can be provided to filter jobs.
See output of `at.jobcheck` for more.
.. code-block:: yaml
example1:
at.absent:
.. warning::
this will remove all jobs!
.. code-block:: yaml
example2:
at.absent:
- year: 13
.. code-block:: yaml
example3:
at.absent:
- tag: rose
.. code-block:: yaml
example4:
at.absent:
- tag: rose
- day: 13
- hour: 16
.. code-block:: yaml
example5:
at.absent:
- jobid: 4
.. note:
all other filters are ignored and only job with id 4 is removed
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
# limit was never support
if 'limit' in kwargs:
ret['comment'] = 'limit parameter not supported {0}'.format(name)
ret['result'] = False
return ret
# quick return on test=True
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'removed ? job(s)'
return ret
# remove specific job
if jobid:
jobs = __salt__['at.atq'](jobid)
if jobs.get('jobs'):
ret['result'] = True
ret['comment'] = 'job with id {jobid} not present'.format(
jobid=jobid
)
return ret
elif 'jobs' in jobs and len(jobs['jobs']) == 1:
if 'job' in jobs['jobs'][0] and jobs['jobs'][0]['job']:
res = __salt__['at.atrm'](jobid)
ret['result'] = jobid in res['jobs']['removed']
if ret['result']:
ret['comment'] = 'job with id {jobid} was removed'.format(
jobid=jobid
)
else:
ret['comment'] = 'failed to remove job with id {jobid}'.format(
jobid=jobid
)
ret['changes']['removed'] = res['jobs']['removed']
return ret
else:
ret['result'] = False
ret['comment'] = 'more than one job was return for job with id {jobid}'.format(
jobid=jobid
)
return ret
# remove jobs based on filter
if kwargs:
# we pass kwargs to at.jobcheck
opts = list(list(map(str, [j['job'] for j in __salt__['at.jobcheck'](**kwargs)['jobs']])))
res = __salt__['at.atrm'](*opts)
else:
# arguments to filter with, removing everything!
res = __salt__['at.atrm']('all')
if res['jobs']['removed']:
ret['changes']['removed'] = res['jobs']['removed']
ret['comment'] = 'removed {count} job(s)'.format(
count=len(res['jobs']['removed'])
)
return ret | [
"def",
"absent",
"(",
"name",
",",
"jobid",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"# limit was never ... | .. versionchanged:: 2017.7.0
Remove a job from queue
jobid: string|int
Specific jobid to remove
tag : string
Job's tag
runas : string
Runs user-specified jobs
kwargs
Addition kwargs can be provided to filter jobs.
See output of `at.jobcheck` for more.
.. code-block:: yaml
example1:
at.absent:
.. warning::
this will remove all jobs!
.. code-block:: yaml
example2:
at.absent:
- year: 13
.. code-block:: yaml
example3:
at.absent:
- tag: rose
.. code-block:: yaml
example4:
at.absent:
- tag: rose
- day: 13
- hour: 16
.. code-block:: yaml
example5:
at.absent:
- jobid: 4
.. note:
all other filters are ignored and only job with id 4 is removed | [
"..",
"versionchanged",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/at.py#L128-L245 | train |
saltstack/salt | salt/states/at.py | watch | def watch(name, timespec, tag=None, user=None, job=None, unique_tag=False):
'''
.. versionadded:: 2017.7.0
Add an at job if trigger by watch
job : string
Command to run.
timespec : string
The 'timespec' follows the format documented in the at(1) manpage.
tag : string
Make a tag for the job.
user : string
The user to run the at job
.. versionadded:: 2014.1.4
unique_tag : boolean
If set to True job will not be added if a job with the tag exists.
.. versionadded:: 2017.7.0
.. code-block:: yaml
minion_restart:
at.watch:
- job: 'salt-call --local service.restart salt-minion'
- timespec: 'now +1 min'
- tag: minion_restart
- unique_tag: trye
- watch:
- file: /etc/salt/minion
'''
return {
'name': name,
'changes': {},
'result': True,
'comment': ''
} | python | def watch(name, timespec, tag=None, user=None, job=None, unique_tag=False):
'''
.. versionadded:: 2017.7.0
Add an at job if trigger by watch
job : string
Command to run.
timespec : string
The 'timespec' follows the format documented in the at(1) manpage.
tag : string
Make a tag for the job.
user : string
The user to run the at job
.. versionadded:: 2014.1.4
unique_tag : boolean
If set to True job will not be added if a job with the tag exists.
.. versionadded:: 2017.7.0
.. code-block:: yaml
minion_restart:
at.watch:
- job: 'salt-call --local service.restart salt-minion'
- timespec: 'now +1 min'
- tag: minion_restart
- unique_tag: trye
- watch:
- file: /etc/salt/minion
'''
return {
'name': name,
'changes': {},
'result': True,
'comment': ''
} | [
"def",
"watch",
"(",
"name",
",",
"timespec",
",",
"tag",
"=",
"None",
",",
"user",
"=",
"None",
",",
"job",
"=",
"None",
",",
"unique_tag",
"=",
"False",
")",
":",
"return",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'res... | .. versionadded:: 2017.7.0
Add an at job if trigger by watch
job : string
Command to run.
timespec : string
The 'timespec' follows the format documented in the at(1) manpage.
tag : string
Make a tag for the job.
user : string
The user to run the at job
.. versionadded:: 2014.1.4
unique_tag : boolean
If set to True job will not be added if a job with the tag exists.
.. versionadded:: 2017.7.0
.. code-block:: yaml
minion_restart:
at.watch:
- job: 'salt-call --local service.restart salt-minion'
- timespec: 'now +1 min'
- tag: minion_restart
- unique_tag: trye
- watch:
- file: /etc/salt/minion | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/at.py#L248-L288 | train |
saltstack/salt | salt/states/at.py | mod_watch | def mod_watch(name, **kwargs):
'''
The at watcher, called to invoke the watch command.
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
name
The name of the atjob
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if kwargs['sfun'] == 'watch':
for p in ['sfun', '__reqs__']:
del kwargs[p]
kwargs['name'] = name
ret = present(**kwargs)
return ret | python | def mod_watch(name, **kwargs):
'''
The at watcher, called to invoke the watch command.
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
name
The name of the atjob
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if kwargs['sfun'] == 'watch':
for p in ['sfun', '__reqs__']:
del kwargs[p]
kwargs['name'] = name
ret = present(**kwargs)
return ret | [
"def",
"mod_watch",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"if",
"kwargs",
"[",
"'sfun'",
"]",
"=="... | The at watcher, called to invoke the watch command.
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
name
The name of the atjob | [
"The",
"at",
"watcher",
"called",
"to",
"invoke",
"the",
"watch",
"command",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/at.py#L291-L316 | train |
saltstack/salt | salt/modules/parallels.py | _normalize_args | def _normalize_args(args):
'''
Return args as a list of strings
'''
if isinstance(args, six.string_types):
return shlex.split(args)
if isinstance(args, (tuple, list)):
return [six.text_type(arg) for arg in args]
else:
return [six.text_type(args)] | python | def _normalize_args(args):
'''
Return args as a list of strings
'''
if isinstance(args, six.string_types):
return shlex.split(args)
if isinstance(args, (tuple, list)):
return [six.text_type(arg) for arg in args]
else:
return [six.text_type(args)] | [
"def",
"_normalize_args",
"(",
"args",
")",
":",
"if",
"isinstance",
"(",
"args",
",",
"six",
".",
"string_types",
")",
":",
"return",
"shlex",
".",
"split",
"(",
"args",
")",
"if",
"isinstance",
"(",
"args",
",",
"(",
"tuple",
",",
"list",
")",
")",... | Return args as a list of strings | [
"Return",
"args",
"as",
"a",
"list",
"of",
"strings"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L49-L59 | train |
saltstack/salt | salt/modules/parallels.py | _find_guids | def _find_guids(guid_string):
'''
Return the set of GUIDs found in guid_string
:param str guid_string:
String containing zero or more GUIDs. Each GUID may or may not be
enclosed in {}
Example data (this string contains two distinct GUIDs):
PARENT_SNAPSHOT_ID SNAPSHOT_ID
{a5b8999f-5d95-4aff-82de-e515b0101b66}
{a5b8999f-5d95-4aff-82de-e515b0101b66} *{a7345be5-ab66-478c-946e-a6c2caf14909}
'''
guids = []
for found_guid in re.finditer(GUID_REGEX, guid_string):
if found_guid.groups():
guids.append(found_guid.group(0).strip('{}'))
return sorted(list(set(guids))) | python | def _find_guids(guid_string):
'''
Return the set of GUIDs found in guid_string
:param str guid_string:
String containing zero or more GUIDs. Each GUID may or may not be
enclosed in {}
Example data (this string contains two distinct GUIDs):
PARENT_SNAPSHOT_ID SNAPSHOT_ID
{a5b8999f-5d95-4aff-82de-e515b0101b66}
{a5b8999f-5d95-4aff-82de-e515b0101b66} *{a7345be5-ab66-478c-946e-a6c2caf14909}
'''
guids = []
for found_guid in re.finditer(GUID_REGEX, guid_string):
if found_guid.groups():
guids.append(found_guid.group(0).strip('{}'))
return sorted(list(set(guids))) | [
"def",
"_find_guids",
"(",
"guid_string",
")",
":",
"guids",
"=",
"[",
"]",
"for",
"found_guid",
"in",
"re",
".",
"finditer",
"(",
"GUID_REGEX",
",",
"guid_string",
")",
":",
"if",
"found_guid",
".",
"groups",
"(",
")",
":",
"guids",
".",
"append",
"("... | Return the set of GUIDs found in guid_string
:param str guid_string:
String containing zero or more GUIDs. Each GUID may or may not be
enclosed in {}
Example data (this string contains two distinct GUIDs):
PARENT_SNAPSHOT_ID SNAPSHOT_ID
{a5b8999f-5d95-4aff-82de-e515b0101b66}
{a5b8999f-5d95-4aff-82de-e515b0101b66} *{a7345be5-ab66-478c-946e-a6c2caf14909} | [
"Return",
"the",
"set",
"of",
"GUIDs",
"found",
"in",
"guid_string"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L62-L80 | train |
saltstack/salt | salt/modules/parallels.py | prlsrvctl | def prlsrvctl(sub_cmd, args=None, runas=None):
'''
Execute a prlsrvctl command
.. versionadded:: 2016.11.0
:param str sub_cmd:
prlsrvctl subcommand to execute
:param str args:
The arguments supplied to ``prlsrvctl <sub_cmd>``
:param str runas:
The user that the prlsrvctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.prlsrvctl info runas=macdev
salt '*' parallels.prlsrvctl usb list runas=macdev
salt -- '*' parallels.prlsrvctl set '--mem-limit auto' runas=macdev
'''
if not salt.utils.path.which('prlsrvctl'):
raise CommandExecutionError('prlsrvctl utility not available')
# Construct command
cmd = ['prlsrvctl', sub_cmd]
if args:
cmd.extend(_normalize_args(args))
# Execute command and return output
return __salt__['cmd.run'](cmd, runas=runas) | python | def prlsrvctl(sub_cmd, args=None, runas=None):
'''
Execute a prlsrvctl command
.. versionadded:: 2016.11.0
:param str sub_cmd:
prlsrvctl subcommand to execute
:param str args:
The arguments supplied to ``prlsrvctl <sub_cmd>``
:param str runas:
The user that the prlsrvctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.prlsrvctl info runas=macdev
salt '*' parallels.prlsrvctl usb list runas=macdev
salt -- '*' parallels.prlsrvctl set '--mem-limit auto' runas=macdev
'''
if not salt.utils.path.which('prlsrvctl'):
raise CommandExecutionError('prlsrvctl utility not available')
# Construct command
cmd = ['prlsrvctl', sub_cmd]
if args:
cmd.extend(_normalize_args(args))
# Execute command and return output
return __salt__['cmd.run'](cmd, runas=runas) | [
"def",
"prlsrvctl",
"(",
"sub_cmd",
",",
"args",
"=",
"None",
",",
"runas",
"=",
"None",
")",
":",
"if",
"not",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'prlsrvctl'",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'prlsrvctl utility not av... | Execute a prlsrvctl command
.. versionadded:: 2016.11.0
:param str sub_cmd:
prlsrvctl subcommand to execute
:param str args:
The arguments supplied to ``prlsrvctl <sub_cmd>``
:param str runas:
The user that the prlsrvctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.prlsrvctl info runas=macdev
salt '*' parallels.prlsrvctl usb list runas=macdev
salt -- '*' parallels.prlsrvctl set '--mem-limit auto' runas=macdev | [
"Execute",
"a",
"prlsrvctl",
"command"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L83-L115 | train |
saltstack/salt | salt/modules/parallels.py | list_vms | def list_vms(name=None, info=False, all=False, args=None, runas=None, template=False):
'''
List information about the VMs
:param str name:
Name/ID of VM to list
.. versionchanged:: 2016.11.0
No longer implies ``info=True``
:param str info:
List extra information
:param bool all:
List all non-template VMs
:param tuple args:
Additional arguments given to ``prctl list``
:param str runas:
The user that the prlctl command will be run as
:param bool template:
List the available virtual machine templates. The real virtual
machines will not be included in the output
.. versionadded:: 2016.11.0
Example:
.. code-block:: bash
salt '*' parallels.list_vms runas=macdev
salt '*' parallels.list_vms name=macvm info=True runas=macdev
salt '*' parallels.list_vms info=True runas=macdev
salt '*' parallels.list_vms ' -o uuid,status' all=True runas=macdev
'''
# Construct argument list
if args is None:
args = []
else:
args = _normalize_args(args)
if name:
args.extend([name])
if info:
args.append('--info')
if all:
args.append('--all')
if template:
args.append('--template')
# Execute command and return output
return prlctl('list', args, runas=runas) | python | def list_vms(name=None, info=False, all=False, args=None, runas=None, template=False):
'''
List information about the VMs
:param str name:
Name/ID of VM to list
.. versionchanged:: 2016.11.0
No longer implies ``info=True``
:param str info:
List extra information
:param bool all:
List all non-template VMs
:param tuple args:
Additional arguments given to ``prctl list``
:param str runas:
The user that the prlctl command will be run as
:param bool template:
List the available virtual machine templates. The real virtual
machines will not be included in the output
.. versionadded:: 2016.11.0
Example:
.. code-block:: bash
salt '*' parallels.list_vms runas=macdev
salt '*' parallels.list_vms name=macvm info=True runas=macdev
salt '*' parallels.list_vms info=True runas=macdev
salt '*' parallels.list_vms ' -o uuid,status' all=True runas=macdev
'''
# Construct argument list
if args is None:
args = []
else:
args = _normalize_args(args)
if name:
args.extend([name])
if info:
args.append('--info')
if all:
args.append('--all')
if template:
args.append('--template')
# Execute command and return output
return prlctl('list', args, runas=runas) | [
"def",
"list_vms",
"(",
"name",
"=",
"None",
",",
"info",
"=",
"False",
",",
"all",
"=",
"False",
",",
"args",
"=",
"None",
",",
"runas",
"=",
"None",
",",
"template",
"=",
"False",
")",
":",
"# Construct argument list",
"if",
"args",
"is",
"None",
"... | List information about the VMs
:param str name:
Name/ID of VM to list
.. versionchanged:: 2016.11.0
No longer implies ``info=True``
:param str info:
List extra information
:param bool all:
List all non-template VMs
:param tuple args:
Additional arguments given to ``prctl list``
:param str runas:
The user that the prlctl command will be run as
:param bool template:
List the available virtual machine templates. The real virtual
machines will not be included in the output
.. versionadded:: 2016.11.0
Example:
.. code-block:: bash
salt '*' parallels.list_vms runas=macdev
salt '*' parallels.list_vms name=macvm info=True runas=macdev
salt '*' parallels.list_vms info=True runas=macdev
salt '*' parallels.list_vms ' -o uuid,status' all=True runas=macdev | [
"List",
"information",
"about",
"the",
"VMs"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L151-L205 | train |
saltstack/salt | salt/modules/parallels.py | clone | def clone(name, new_name, linked=False, template=False, runas=None):
'''
Clone a VM
.. versionadded:: 2016.11.0
:param str name:
Name/ID of VM to clone
:param str new_name:
Name of the new VM
:param bool linked:
Create a linked virtual machine.
:param bool template:
Create a virtual machine template instead of a real virtual machine.
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.clone macvm macvm_new runas=macdev
salt '*' parallels.clone macvm macvm_templ template=True runas=macdev
'''
args = [salt.utils.data.decode(name), '--name', salt.utils.data.decode(new_name)]
if linked:
args.append('--linked')
if template:
args.append('--template')
return prlctl('clone', args, runas=runas) | python | def clone(name, new_name, linked=False, template=False, runas=None):
'''
Clone a VM
.. versionadded:: 2016.11.0
:param str name:
Name/ID of VM to clone
:param str new_name:
Name of the new VM
:param bool linked:
Create a linked virtual machine.
:param bool template:
Create a virtual machine template instead of a real virtual machine.
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.clone macvm macvm_new runas=macdev
salt '*' parallels.clone macvm macvm_templ template=True runas=macdev
'''
args = [salt.utils.data.decode(name), '--name', salt.utils.data.decode(new_name)]
if linked:
args.append('--linked')
if template:
args.append('--template')
return prlctl('clone', args, runas=runas) | [
"def",
"clone",
"(",
"name",
",",
"new_name",
",",
"linked",
"=",
"False",
",",
"template",
"=",
"False",
",",
"runas",
"=",
"None",
")",
":",
"args",
"=",
"[",
"salt",
".",
"utils",
".",
"data",
".",
"decode",
"(",
"name",
")",
",",
"'--name'",
... | Clone a VM
.. versionadded:: 2016.11.0
:param str name:
Name/ID of VM to clone
:param str new_name:
Name of the new VM
:param bool linked:
Create a linked virtual machine.
:param bool template:
Create a virtual machine template instead of a real virtual machine.
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.clone macvm macvm_new runas=macdev
salt '*' parallels.clone macvm macvm_templ template=True runas=macdev | [
"Clone",
"a",
"VM"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L208-L241 | train |
saltstack/salt | salt/modules/parallels.py | delete | def delete(name, runas=None):
'''
Delete a VM
.. versionadded:: 2016.11.0
:param str name:
Name/ID of VM to clone
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.exec macvm 'find /etc/paths.d' runas=macdev
'''
return prlctl('delete', salt.utils.data.decode(name), runas=runas) | python | def delete(name, runas=None):
'''
Delete a VM
.. versionadded:: 2016.11.0
:param str name:
Name/ID of VM to clone
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.exec macvm 'find /etc/paths.d' runas=macdev
'''
return prlctl('delete', salt.utils.data.decode(name), runas=runas) | [
"def",
"delete",
"(",
"name",
",",
"runas",
"=",
"None",
")",
":",
"return",
"prlctl",
"(",
"'delete'",
",",
"salt",
".",
"utils",
".",
"data",
".",
"decode",
"(",
"name",
")",
",",
"runas",
"=",
"runas",
")"
] | Delete a VM
.. versionadded:: 2016.11.0
:param str name:
Name/ID of VM to clone
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.exec macvm 'find /etc/paths.d' runas=macdev | [
"Delete",
"a",
"VM"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L244-L262 | train |
saltstack/salt | salt/modules/parallels.py | exists | def exists(name, runas=None):
'''
Query whether a VM exists
.. versionadded:: 2016.11.0
:param str name:
Name/ID of VM
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.exists macvm runas=macdev
'''
vm_info = list_vms(name, info=True, runas=runas).splitlines()
for info_line in vm_info:
if 'Name: {0}'.format(name) in info_line:
return True
return False | python | def exists(name, runas=None):
'''
Query whether a VM exists
.. versionadded:: 2016.11.0
:param str name:
Name/ID of VM
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.exists macvm runas=macdev
'''
vm_info = list_vms(name, info=True, runas=runas).splitlines()
for info_line in vm_info:
if 'Name: {0}'.format(name) in info_line:
return True
return False | [
"def",
"exists",
"(",
"name",
",",
"runas",
"=",
"None",
")",
":",
"vm_info",
"=",
"list_vms",
"(",
"name",
",",
"info",
"=",
"True",
",",
"runas",
"=",
"runas",
")",
".",
"splitlines",
"(",
")",
"for",
"info_line",
"in",
"vm_info",
":",
"if",
"'Na... | Query whether a VM exists
.. versionadded:: 2016.11.0
:param str name:
Name/ID of VM
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.exists macvm runas=macdev | [
"Query",
"whether",
"a",
"VM",
"exists"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L265-L287 | train |
saltstack/salt | salt/modules/parallels.py | start | def start(name, runas=None):
'''
Start a VM
:param str name:
Name/ID of VM to start
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.start macvm runas=macdev
'''
return prlctl('start', salt.utils.data.decode(name), runas=runas) | python | def start(name, runas=None):
'''
Start a VM
:param str name:
Name/ID of VM to start
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.start macvm runas=macdev
'''
return prlctl('start', salt.utils.data.decode(name), runas=runas) | [
"def",
"start",
"(",
"name",
",",
"runas",
"=",
"None",
")",
":",
"return",
"prlctl",
"(",
"'start'",
",",
"salt",
".",
"utils",
".",
"data",
".",
"decode",
"(",
"name",
")",
",",
"runas",
"=",
"runas",
")"
] | Start a VM
:param str name:
Name/ID of VM to start
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.start macvm runas=macdev | [
"Start",
"a",
"VM"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L290-L306 | train |
saltstack/salt | salt/modules/parallels.py | stop | def stop(name, kill=False, runas=None):
'''
Stop a VM
:param str name:
Name/ID of VM to stop
:param bool kill:
Perform a hard shutdown
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.stop macvm runas=macdev
salt '*' parallels.stop macvm kill=True runas=macdev
'''
# Construct argument list
args = [salt.utils.data.decode(name)]
if kill:
args.append('--kill')
# Execute command and return output
return prlctl('stop', args, runas=runas) | python | def stop(name, kill=False, runas=None):
'''
Stop a VM
:param str name:
Name/ID of VM to stop
:param bool kill:
Perform a hard shutdown
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.stop macvm runas=macdev
salt '*' parallels.stop macvm kill=True runas=macdev
'''
# Construct argument list
args = [salt.utils.data.decode(name)]
if kill:
args.append('--kill')
# Execute command and return output
return prlctl('stop', args, runas=runas) | [
"def",
"stop",
"(",
"name",
",",
"kill",
"=",
"False",
",",
"runas",
"=",
"None",
")",
":",
"# Construct argument list",
"args",
"=",
"[",
"salt",
".",
"utils",
".",
"data",
".",
"decode",
"(",
"name",
")",
"]",
"if",
"kill",
":",
"args",
".",
"app... | Stop a VM
:param str name:
Name/ID of VM to stop
:param bool kill:
Perform a hard shutdown
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.stop macvm runas=macdev
salt '*' parallels.stop macvm kill=True runas=macdev | [
"Stop",
"a",
"VM"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L309-L335 | train |
saltstack/salt | salt/modules/parallels.py | restart | def restart(name, runas=None):
'''
Restart a VM by gracefully shutting it down and then restarting
it
:param str name:
Name/ID of VM to restart
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.restart macvm runas=macdev
'''
return prlctl('restart', salt.utils.data.decode(name), runas=runas) | python | def restart(name, runas=None):
'''
Restart a VM by gracefully shutting it down and then restarting
it
:param str name:
Name/ID of VM to restart
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.restart macvm runas=macdev
'''
return prlctl('restart', salt.utils.data.decode(name), runas=runas) | [
"def",
"restart",
"(",
"name",
",",
"runas",
"=",
"None",
")",
":",
"return",
"prlctl",
"(",
"'restart'",
",",
"salt",
".",
"utils",
".",
"data",
".",
"decode",
"(",
"name",
")",
",",
"runas",
"=",
"runas",
")"
] | Restart a VM by gracefully shutting it down and then restarting
it
:param str name:
Name/ID of VM to restart
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.restart macvm runas=macdev | [
"Restart",
"a",
"VM",
"by",
"gracefully",
"shutting",
"it",
"down",
"and",
"then",
"restarting",
"it"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L338-L355 | train |
saltstack/salt | salt/modules/parallels.py | reset | def reset(name, runas=None):
'''
Reset a VM by performing a hard shutdown and then a restart
:param str name:
Name/ID of VM to reset
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.reset macvm runas=macdev
'''
return prlctl('reset', salt.utils.data.decode(name), runas=runas) | python | def reset(name, runas=None):
'''
Reset a VM by performing a hard shutdown and then a restart
:param str name:
Name/ID of VM to reset
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.reset macvm runas=macdev
'''
return prlctl('reset', salt.utils.data.decode(name), runas=runas) | [
"def",
"reset",
"(",
"name",
",",
"runas",
"=",
"None",
")",
":",
"return",
"prlctl",
"(",
"'reset'",
",",
"salt",
".",
"utils",
".",
"data",
".",
"decode",
"(",
"name",
")",
",",
"runas",
"=",
"runas",
")"
] | Reset a VM by performing a hard shutdown and then a restart
:param str name:
Name/ID of VM to reset
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.reset macvm runas=macdev | [
"Reset",
"a",
"VM",
"by",
"performing",
"a",
"hard",
"shutdown",
"and",
"then",
"a",
"restart"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L358-L374 | train |
saltstack/salt | salt/modules/parallels.py | status | def status(name, runas=None):
'''
Status of a VM
:param str name:
Name/ID of VM whose status will be returned
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.status macvm runas=macdev
'''
return prlctl('status', salt.utils.data.decode(name), runas=runas) | python | def status(name, runas=None):
'''
Status of a VM
:param str name:
Name/ID of VM whose status will be returned
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.status macvm runas=macdev
'''
return prlctl('status', salt.utils.data.decode(name), runas=runas) | [
"def",
"status",
"(",
"name",
",",
"runas",
"=",
"None",
")",
":",
"return",
"prlctl",
"(",
"'status'",
",",
"salt",
".",
"utils",
".",
"data",
".",
"decode",
"(",
"name",
")",
",",
"runas",
"=",
"runas",
")"
] | Status of a VM
:param str name:
Name/ID of VM whose status will be returned
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.status macvm runas=macdev | [
"Status",
"of",
"a",
"VM"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L377-L393 | train |
saltstack/salt | salt/modules/parallels.py | exec_ | def exec_(name, command, runas=None):
'''
Run a command on a VM
:param str name:
Name/ID of VM whose exec will be returned
:param str command:
Command to run on the VM
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.exec macvm 'find /etc/paths.d' runas=macdev
'''
# Construct argument list
args = [salt.utils.data.decode(name)]
args.extend(_normalize_args(command))
# Execute command and return output
return prlctl('exec', args, runas=runas) | python | def exec_(name, command, runas=None):
'''
Run a command on a VM
:param str name:
Name/ID of VM whose exec will be returned
:param str command:
Command to run on the VM
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.exec macvm 'find /etc/paths.d' runas=macdev
'''
# Construct argument list
args = [salt.utils.data.decode(name)]
args.extend(_normalize_args(command))
# Execute command and return output
return prlctl('exec', args, runas=runas) | [
"def",
"exec_",
"(",
"name",
",",
"command",
",",
"runas",
"=",
"None",
")",
":",
"# Construct argument list",
"args",
"=",
"[",
"salt",
".",
"utils",
".",
"data",
".",
"decode",
"(",
"name",
")",
"]",
"args",
".",
"extend",
"(",
"_normalize_args",
"("... | Run a command on a VM
:param str name:
Name/ID of VM whose exec will be returned
:param str command:
Command to run on the VM
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.exec macvm 'find /etc/paths.d' runas=macdev | [
"Run",
"a",
"command",
"on",
"a",
"VM"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L396-L420 | train |
saltstack/salt | salt/modules/parallels.py | snapshot_id_to_name | def snapshot_id_to_name(name, snap_id, strict=False, runas=None):
'''
Attempt to convert a snapshot ID to a snapshot name. If the snapshot has
no name or if the ID is not found or invalid, an empty string will be returned
:param str name:
Name/ID of VM whose snapshots are inspected
:param str snap_id:
ID of the snapshot
:param bool strict:
Raise an exception if a name cannot be found for the given ``snap_id``
:param str runas:
The user that the prlctl command will be run as
Example data
.. code-block:: yaml
ID: {a5b8999f-5d95-4aff-82de-e515b0101b66}
Name: original
Date: 2016-03-04 10:50:34
Current: yes
State: poweroff
Description: original state
CLI Example:
.. code-block:: bash
salt '*' parallels.snapshot_id_to_name macvm a5b8999f-5d95-4aff-82de-e515b0101b66 runas=macdev
'''
# Validate VM name and snapshot ID
name = salt.utils.data.decode(name)
if not re.match(GUID_REGEX, snap_id):
raise SaltInvocationError(
'Snapshot ID "{0}" is not a GUID'.format(salt.utils.data.decode(snap_id))
)
# Get the snapshot information of the snapshot having the requested ID
info = prlctl('snapshot-list', [name, '--id', snap_id], runas=runas)
# Parallels desktop returned no information for snap_id
if not info:
raise SaltInvocationError(
'No snapshots for VM "{0}" have ID "{1}"'.format(name, snap_id)
)
# Try to interpret the information
try:
data = salt.utils.yaml.safe_load(info)
except salt.utils.yaml.YAMLError as err:
log.warning(
'Could not interpret snapshot data returned from prlctl: %s', err
)
data = {}
# Find the snapshot name
if isinstance(data, dict):
snap_name = data.get('Name', '')
# If snapshot name is of type NoneType, then the snapshot is unnamed
if snap_name is None:
snap_name = ''
else:
log.warning(
'Could not interpret snapshot data returned from prlctl: '
'data is not formed as a dictionary: %s', data
)
snap_name = ''
# Raise or return the result
if not snap_name and strict:
raise SaltInvocationError(
'Could not find a snapshot name for snapshot ID "{0}" of VM '
'"{1}"'.format(snap_id, name)
)
return salt.utils.data.decode(snap_name) | python | def snapshot_id_to_name(name, snap_id, strict=False, runas=None):
'''
Attempt to convert a snapshot ID to a snapshot name. If the snapshot has
no name or if the ID is not found or invalid, an empty string will be returned
:param str name:
Name/ID of VM whose snapshots are inspected
:param str snap_id:
ID of the snapshot
:param bool strict:
Raise an exception if a name cannot be found for the given ``snap_id``
:param str runas:
The user that the prlctl command will be run as
Example data
.. code-block:: yaml
ID: {a5b8999f-5d95-4aff-82de-e515b0101b66}
Name: original
Date: 2016-03-04 10:50:34
Current: yes
State: poweroff
Description: original state
CLI Example:
.. code-block:: bash
salt '*' parallels.snapshot_id_to_name macvm a5b8999f-5d95-4aff-82de-e515b0101b66 runas=macdev
'''
# Validate VM name and snapshot ID
name = salt.utils.data.decode(name)
if not re.match(GUID_REGEX, snap_id):
raise SaltInvocationError(
'Snapshot ID "{0}" is not a GUID'.format(salt.utils.data.decode(snap_id))
)
# Get the snapshot information of the snapshot having the requested ID
info = prlctl('snapshot-list', [name, '--id', snap_id], runas=runas)
# Parallels desktop returned no information for snap_id
if not info:
raise SaltInvocationError(
'No snapshots for VM "{0}" have ID "{1}"'.format(name, snap_id)
)
# Try to interpret the information
try:
data = salt.utils.yaml.safe_load(info)
except salt.utils.yaml.YAMLError as err:
log.warning(
'Could not interpret snapshot data returned from prlctl: %s', err
)
data = {}
# Find the snapshot name
if isinstance(data, dict):
snap_name = data.get('Name', '')
# If snapshot name is of type NoneType, then the snapshot is unnamed
if snap_name is None:
snap_name = ''
else:
log.warning(
'Could not interpret snapshot data returned from prlctl: '
'data is not formed as a dictionary: %s', data
)
snap_name = ''
# Raise or return the result
if not snap_name and strict:
raise SaltInvocationError(
'Could not find a snapshot name for snapshot ID "{0}" of VM '
'"{1}"'.format(snap_id, name)
)
return salt.utils.data.decode(snap_name) | [
"def",
"snapshot_id_to_name",
"(",
"name",
",",
"snap_id",
",",
"strict",
"=",
"False",
",",
"runas",
"=",
"None",
")",
":",
"# Validate VM name and snapshot ID",
"name",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"decode",
"(",
"name",
")",
"if",
"not",... | Attempt to convert a snapshot ID to a snapshot name. If the snapshot has
no name or if the ID is not found or invalid, an empty string will be returned
:param str name:
Name/ID of VM whose snapshots are inspected
:param str snap_id:
ID of the snapshot
:param bool strict:
Raise an exception if a name cannot be found for the given ``snap_id``
:param str runas:
The user that the prlctl command will be run as
Example data
.. code-block:: yaml
ID: {a5b8999f-5d95-4aff-82de-e515b0101b66}
Name: original
Date: 2016-03-04 10:50:34
Current: yes
State: poweroff
Description: original state
CLI Example:
.. code-block:: bash
salt '*' parallels.snapshot_id_to_name macvm a5b8999f-5d95-4aff-82de-e515b0101b66 runas=macdev | [
"Attempt",
"to",
"convert",
"a",
"snapshot",
"ID",
"to",
"a",
"snapshot",
"name",
".",
"If",
"the",
"snapshot",
"has",
"no",
"name",
"or",
"if",
"the",
"ID",
"is",
"not",
"found",
"or",
"invalid",
"an",
"empty",
"string",
"will",
"be",
"returned"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L423-L501 | train |
saltstack/salt | salt/modules/parallels.py | snapshot_name_to_id | def snapshot_name_to_id(name, snap_name, strict=False, runas=None):
'''
Attempt to convert a snapshot name to a snapshot ID. If the name is not
found an empty string is returned. If multiple snapshots share the same
name, a list will be returned
:param str name:
Name/ID of VM whose snapshots are inspected
:param str snap_name:
Name of the snapshot
:param bool strict:
Raise an exception if multiple snapshot IDs are found
:param str runas:
The user that the prlctl command will be run as
CLI Example:
.. code-block:: bash
salt '*' parallels.snapshot_id_to_name macvm original runas=macdev
'''
# Validate VM and snapshot names
name = salt.utils.data.decode(name)
snap_name = salt.utils.data.decode(snap_name)
# Get a multiline string containing all the snapshot GUIDs
info = prlctl('snapshot-list', name, runas=runas)
# Get a set of all snapshot GUIDs in the string
snap_ids = _find_guids(info)
# Try to match the snapshot name to an ID
named_ids = []
for snap_id in snap_ids:
if snapshot_id_to_name(name, snap_id, runas=runas) == snap_name:
named_ids.append(snap_id)
# Return one or more IDs having snap_name or raise an error upon
# non-singular names
if not named_ids:
raise SaltInvocationError(
'No snapshots for VM "{0}" have name "{1}"'.format(name, snap_name)
)
elif len(named_ids) == 1:
return named_ids[0]
else:
multi_msg = ('Multiple snapshots for VM "{0}" have name '
'"{1}"'.format(name, snap_name))
if strict:
raise SaltInvocationError(multi_msg)
else:
log.warning(multi_msg)
return named_ids | python | def snapshot_name_to_id(name, snap_name, strict=False, runas=None):
'''
Attempt to convert a snapshot name to a snapshot ID. If the name is not
found an empty string is returned. If multiple snapshots share the same
name, a list will be returned
:param str name:
Name/ID of VM whose snapshots are inspected
:param str snap_name:
Name of the snapshot
:param bool strict:
Raise an exception if multiple snapshot IDs are found
:param str runas:
The user that the prlctl command will be run as
CLI Example:
.. code-block:: bash
salt '*' parallels.snapshot_id_to_name macvm original runas=macdev
'''
# Validate VM and snapshot names
name = salt.utils.data.decode(name)
snap_name = salt.utils.data.decode(snap_name)
# Get a multiline string containing all the snapshot GUIDs
info = prlctl('snapshot-list', name, runas=runas)
# Get a set of all snapshot GUIDs in the string
snap_ids = _find_guids(info)
# Try to match the snapshot name to an ID
named_ids = []
for snap_id in snap_ids:
if snapshot_id_to_name(name, snap_id, runas=runas) == snap_name:
named_ids.append(snap_id)
# Return one or more IDs having snap_name or raise an error upon
# non-singular names
if not named_ids:
raise SaltInvocationError(
'No snapshots for VM "{0}" have name "{1}"'.format(name, snap_name)
)
elif len(named_ids) == 1:
return named_ids[0]
else:
multi_msg = ('Multiple snapshots for VM "{0}" have name '
'"{1}"'.format(name, snap_name))
if strict:
raise SaltInvocationError(multi_msg)
else:
log.warning(multi_msg)
return named_ids | [
"def",
"snapshot_name_to_id",
"(",
"name",
",",
"snap_name",
",",
"strict",
"=",
"False",
",",
"runas",
"=",
"None",
")",
":",
"# Validate VM and snapshot names",
"name",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"decode",
"(",
"name",
")",
"snap_name",
... | Attempt to convert a snapshot name to a snapshot ID. If the name is not
found an empty string is returned. If multiple snapshots share the same
name, a list will be returned
:param str name:
Name/ID of VM whose snapshots are inspected
:param str snap_name:
Name of the snapshot
:param bool strict:
Raise an exception if multiple snapshot IDs are found
:param str runas:
The user that the prlctl command will be run as
CLI Example:
.. code-block:: bash
salt '*' parallels.snapshot_id_to_name macvm original runas=macdev | [
"Attempt",
"to",
"convert",
"a",
"snapshot",
"name",
"to",
"a",
"snapshot",
"ID",
".",
"If",
"the",
"name",
"is",
"not",
"found",
"an",
"empty",
"string",
"is",
"returned",
".",
"If",
"multiple",
"snapshots",
"share",
"the",
"same",
"name",
"a",
"list",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L504-L559 | train |
saltstack/salt | salt/modules/parallels.py | _validate_snap_name | def _validate_snap_name(name, snap_name, strict=True, runas=None):
'''
Validate snapshot name and convert to snapshot ID
:param str name:
Name/ID of VM whose snapshot name is being validated
:param str snap_name:
Name/ID of snapshot
:param bool strict:
Raise an exception if multiple snapshot IDs are found
:param str runas:
The user that the prlctl command will be run as
'''
snap_name = salt.utils.data.decode(snap_name)
# Try to convert snapshot name to an ID without {}
if re.match(GUID_REGEX, snap_name):
return snap_name.strip('{}')
else:
return snapshot_name_to_id(name, snap_name, strict=strict, runas=runas) | python | def _validate_snap_name(name, snap_name, strict=True, runas=None):
'''
Validate snapshot name and convert to snapshot ID
:param str name:
Name/ID of VM whose snapshot name is being validated
:param str snap_name:
Name/ID of snapshot
:param bool strict:
Raise an exception if multiple snapshot IDs are found
:param str runas:
The user that the prlctl command will be run as
'''
snap_name = salt.utils.data.decode(snap_name)
# Try to convert snapshot name to an ID without {}
if re.match(GUID_REGEX, snap_name):
return snap_name.strip('{}')
else:
return snapshot_name_to_id(name, snap_name, strict=strict, runas=runas) | [
"def",
"_validate_snap_name",
"(",
"name",
",",
"snap_name",
",",
"strict",
"=",
"True",
",",
"runas",
"=",
"None",
")",
":",
"snap_name",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"decode",
"(",
"snap_name",
")",
"# Try to convert snapshot name to an ID wi... | Validate snapshot name and convert to snapshot ID
:param str name:
Name/ID of VM whose snapshot name is being validated
:param str snap_name:
Name/ID of snapshot
:param bool strict:
Raise an exception if multiple snapshot IDs are found
:param str runas:
The user that the prlctl command will be run as | [
"Validate",
"snapshot",
"name",
"and",
"convert",
"to",
"snapshot",
"ID"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L562-L584 | train |
saltstack/salt | salt/modules/parallels.py | list_snapshots | def list_snapshots(name, snap_name=None, tree=False, names=False, runas=None):
'''
List the snapshots
:param str name:
Name/ID of VM whose snapshots will be listed
:param str snap_id:
Name/ID of snapshot to display information about. If ``tree=True`` is
also specified, display the snapshot subtree having this snapshot as
the root snapshot
:param bool tree:
List snapshots in tree format rather than tabular format
:param bool names:
List snapshots as ID, name pairs
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.list_snapshots macvm runas=macdev
salt '*' parallels.list_snapshots macvm tree=True runas=macdev
salt '*' parallels.list_snapshots macvm snap_name=original runas=macdev
salt '*' parallels.list_snapshots macvm names=True runas=macdev
'''
# Validate VM and snapshot names
name = salt.utils.data.decode(name)
if snap_name:
snap_name = _validate_snap_name(name, snap_name, runas=runas)
# Construct argument list
args = [name]
if tree:
args.append('--tree')
if snap_name:
args.extend(['--id', snap_name])
# Execute command
res = prlctl('snapshot-list', args, runas=runas)
# Construct ID, name pairs
if names:
# Find all GUIDs in the result
snap_ids = _find_guids(res)
# Try to find the snapshot names
ret = '{0:<38} {1}\n'.format('Snapshot ID', 'Snapshot Name')
for snap_id in snap_ids:
snap_name = snapshot_id_to_name(name, snap_id, runas=runas)
ret += ('{{{0}}} {1}\n'.format(snap_id, salt.utils.data.decode(snap_name)))
return ret
# Return information directly from parallels desktop
else:
return res | python | def list_snapshots(name, snap_name=None, tree=False, names=False, runas=None):
'''
List the snapshots
:param str name:
Name/ID of VM whose snapshots will be listed
:param str snap_id:
Name/ID of snapshot to display information about. If ``tree=True`` is
also specified, display the snapshot subtree having this snapshot as
the root snapshot
:param bool tree:
List snapshots in tree format rather than tabular format
:param bool names:
List snapshots as ID, name pairs
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.list_snapshots macvm runas=macdev
salt '*' parallels.list_snapshots macvm tree=True runas=macdev
salt '*' parallels.list_snapshots macvm snap_name=original runas=macdev
salt '*' parallels.list_snapshots macvm names=True runas=macdev
'''
# Validate VM and snapshot names
name = salt.utils.data.decode(name)
if snap_name:
snap_name = _validate_snap_name(name, snap_name, runas=runas)
# Construct argument list
args = [name]
if tree:
args.append('--tree')
if snap_name:
args.extend(['--id', snap_name])
# Execute command
res = prlctl('snapshot-list', args, runas=runas)
# Construct ID, name pairs
if names:
# Find all GUIDs in the result
snap_ids = _find_guids(res)
# Try to find the snapshot names
ret = '{0:<38} {1}\n'.format('Snapshot ID', 'Snapshot Name')
for snap_id in snap_ids:
snap_name = snapshot_id_to_name(name, snap_id, runas=runas)
ret += ('{{{0}}} {1}\n'.format(snap_id, salt.utils.data.decode(snap_name)))
return ret
# Return information directly from parallels desktop
else:
return res | [
"def",
"list_snapshots",
"(",
"name",
",",
"snap_name",
"=",
"None",
",",
"tree",
"=",
"False",
",",
"names",
"=",
"False",
",",
"runas",
"=",
"None",
")",
":",
"# Validate VM and snapshot names",
"name",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"dec... | List the snapshots
:param str name:
Name/ID of VM whose snapshots will be listed
:param str snap_id:
Name/ID of snapshot to display information about. If ``tree=True`` is
also specified, display the snapshot subtree having this snapshot as
the root snapshot
:param bool tree:
List snapshots in tree format rather than tabular format
:param bool names:
List snapshots as ID, name pairs
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.list_snapshots macvm runas=macdev
salt '*' parallels.list_snapshots macvm tree=True runas=macdev
salt '*' parallels.list_snapshots macvm snap_name=original runas=macdev
salt '*' parallels.list_snapshots macvm names=True runas=macdev | [
"List",
"the",
"snapshots"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L587-L646 | train |
saltstack/salt | salt/modules/parallels.py | snapshot | def snapshot(name, snap_name=None, desc=None, runas=None):
'''
Create a snapshot
:param str name:
Name/ID of VM to take a snapshot of
:param str snap_name:
Name of snapshot
:param str desc:
Description of snapshot
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.create_snapshot macvm snap_name=macvm-original runas=macdev
salt '*' parallels.create_snapshot macvm snap_name=macvm-updates desc='clean install with updates' runas=macdev
'''
# Validate VM and snapshot names
name = salt.utils.data.decode(name)
if snap_name:
snap_name = salt.utils.data.decode(snap_name)
# Construct argument list
args = [name]
if snap_name:
args.extend(['--name', snap_name])
if desc:
args.extend(['--description', desc])
# Execute command and return output
return prlctl('snapshot', args, runas=runas) | python | def snapshot(name, snap_name=None, desc=None, runas=None):
'''
Create a snapshot
:param str name:
Name/ID of VM to take a snapshot of
:param str snap_name:
Name of snapshot
:param str desc:
Description of snapshot
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.create_snapshot macvm snap_name=macvm-original runas=macdev
salt '*' parallels.create_snapshot macvm snap_name=macvm-updates desc='clean install with updates' runas=macdev
'''
# Validate VM and snapshot names
name = salt.utils.data.decode(name)
if snap_name:
snap_name = salt.utils.data.decode(snap_name)
# Construct argument list
args = [name]
if snap_name:
args.extend(['--name', snap_name])
if desc:
args.extend(['--description', desc])
# Execute command and return output
return prlctl('snapshot', args, runas=runas) | [
"def",
"snapshot",
"(",
"name",
",",
"snap_name",
"=",
"None",
",",
"desc",
"=",
"None",
",",
"runas",
"=",
"None",
")",
":",
"# Validate VM and snapshot names",
"name",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"decode",
"(",
"name",
")",
"if",
"sn... | Create a snapshot
:param str name:
Name/ID of VM to take a snapshot of
:param str snap_name:
Name of snapshot
:param str desc:
Description of snapshot
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.create_snapshot macvm snap_name=macvm-original runas=macdev
salt '*' parallels.create_snapshot macvm snap_name=macvm-updates desc='clean install with updates' runas=macdev | [
"Create",
"a",
"snapshot"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L649-L685 | train |
saltstack/salt | salt/modules/parallels.py | delete_snapshot | def delete_snapshot(name, snap_name, runas=None, all=False):
'''
Delete a snapshot
.. note::
Deleting a snapshot from which other snapshots are dervied will not
delete the derived snapshots
:param str name:
Name/ID of VM whose snapshot will be deleted
:param str snap_name:
Name/ID of snapshot to delete
:param str runas:
The user that the prlctl command will be run as
:param bool all:
Delete all snapshots having the name given
.. versionadded:: 2016.11.0
Example:
.. code-block:: bash
salt '*' parallels.delete_snapshot macvm 'unneeded snapshot' runas=macdev
salt '*' parallels.delete_snapshot macvm 'Snapshot for linked clone' all=True runas=macdev
'''
# strict means raise an error if multiple snapshot IDs found for the name given
strict = not all
# Validate VM and snapshot names
name = salt.utils.data.decode(name)
snap_ids = _validate_snap_name(name, snap_name, strict=strict, runas=runas)
if isinstance(snap_ids, six.string_types):
snap_ids = [snap_ids]
# Delete snapshot(s)
ret = {}
for snap_id in snap_ids:
snap_id = snap_id.strip('{}')
# Construct argument list
args = [name, '--id', snap_id]
# Execute command
ret[snap_id] = prlctl('snapshot-delete', args, runas=runas)
# Return results
ret_keys = list(ret.keys())
if len(ret_keys) == 1:
return ret[ret_keys[0]]
else:
return ret | python | def delete_snapshot(name, snap_name, runas=None, all=False):
'''
Delete a snapshot
.. note::
Deleting a snapshot from which other snapshots are dervied will not
delete the derived snapshots
:param str name:
Name/ID of VM whose snapshot will be deleted
:param str snap_name:
Name/ID of snapshot to delete
:param str runas:
The user that the prlctl command will be run as
:param bool all:
Delete all snapshots having the name given
.. versionadded:: 2016.11.0
Example:
.. code-block:: bash
salt '*' parallels.delete_snapshot macvm 'unneeded snapshot' runas=macdev
salt '*' parallels.delete_snapshot macvm 'Snapshot for linked clone' all=True runas=macdev
'''
# strict means raise an error if multiple snapshot IDs found for the name given
strict = not all
# Validate VM and snapshot names
name = salt.utils.data.decode(name)
snap_ids = _validate_snap_name(name, snap_name, strict=strict, runas=runas)
if isinstance(snap_ids, six.string_types):
snap_ids = [snap_ids]
# Delete snapshot(s)
ret = {}
for snap_id in snap_ids:
snap_id = snap_id.strip('{}')
# Construct argument list
args = [name, '--id', snap_id]
# Execute command
ret[snap_id] = prlctl('snapshot-delete', args, runas=runas)
# Return results
ret_keys = list(ret.keys())
if len(ret_keys) == 1:
return ret[ret_keys[0]]
else:
return ret | [
"def",
"delete_snapshot",
"(",
"name",
",",
"snap_name",
",",
"runas",
"=",
"None",
",",
"all",
"=",
"False",
")",
":",
"# strict means raise an error if multiple snapshot IDs found for the name given",
"strict",
"=",
"not",
"all",
"# Validate VM and snapshot names",
"nam... | Delete a snapshot
.. note::
Deleting a snapshot from which other snapshots are dervied will not
delete the derived snapshots
:param str name:
Name/ID of VM whose snapshot will be deleted
:param str snap_name:
Name/ID of snapshot to delete
:param str runas:
The user that the prlctl command will be run as
:param bool all:
Delete all snapshots having the name given
.. versionadded:: 2016.11.0
Example:
.. code-block:: bash
salt '*' parallels.delete_snapshot macvm 'unneeded snapshot' runas=macdev
salt '*' parallels.delete_snapshot macvm 'Snapshot for linked clone' all=True runas=macdev | [
"Delete",
"a",
"snapshot"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L688-L742 | train |
saltstack/salt | salt/modules/parallels.py | revert_snapshot | def revert_snapshot(name, snap_name, runas=None):
'''
Revert a VM to a snapshot
:param str name:
Name/ID of VM to revert to a snapshot
:param str snap_name:
Name/ID of snapshot to revert to
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.revert_snapshot macvm base-with-updates runas=macdev
'''
# Validate VM and snapshot names
name = salt.utils.data.decode(name)
snap_name = _validate_snap_name(name, snap_name, runas=runas)
# Construct argument list
args = [name, '--id', snap_name]
# Execute command and return output
return prlctl('snapshot-switch', args, runas=runas) | python | def revert_snapshot(name, snap_name, runas=None):
'''
Revert a VM to a snapshot
:param str name:
Name/ID of VM to revert to a snapshot
:param str snap_name:
Name/ID of snapshot to revert to
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.revert_snapshot macvm base-with-updates runas=macdev
'''
# Validate VM and snapshot names
name = salt.utils.data.decode(name)
snap_name = _validate_snap_name(name, snap_name, runas=runas)
# Construct argument list
args = [name, '--id', snap_name]
# Execute command and return output
return prlctl('snapshot-switch', args, runas=runas) | [
"def",
"revert_snapshot",
"(",
"name",
",",
"snap_name",
",",
"runas",
"=",
"None",
")",
":",
"# Validate VM and snapshot names",
"name",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"decode",
"(",
"name",
")",
"snap_name",
"=",
"_validate_snap_name",
"(",
"... | Revert a VM to a snapshot
:param str name:
Name/ID of VM to revert to a snapshot
:param str snap_name:
Name/ID of snapshot to revert to
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.revert_snapshot macvm base-with-updates runas=macdev | [
"Revert",
"a",
"VM",
"to",
"a",
"snapshot"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L745-L772 | train |
saltstack/salt | salt/states/junos.py | rpc | def rpc(name, dest=None, **kwargs):
'''
Executes the given rpc. The returned data can be stored in a file
by specifying the destination path with dest as an argument
.. code-block:: yaml
get-interface-information:
junos:
- rpc
- dest: /home/user/rpc.log
- interface_name: lo0
Parameters:
Required
* cmd:
The rpc to be executed. (default = None)
Optional
* dest:
Destination file where the rpc output is stored. (default = None)
Note that the file will be stored on the proxy minion. To push the
files to the master use the salt's following execution module: \
:py:func:`cp.push <salt.modules.cp.push>`
* format:
The format in which the rpc reply must be stored in file specified in the dest
(used only when dest is specified) (default = xml)
* kwargs: keyworded arguments taken by rpc call like-
* timeout:
Set NETCONF RPC timeout. Can be used for commands which
take a while to execute. (default= 30 seconds)
* filter:
Only to be used with 'get-config' rpc to get specific configuration.
* terse:
Amount of information you want.
* interface_name:
Name of the interface whose information you want.
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.rpc'](name, dest, **kwargs)
return ret | python | def rpc(name, dest=None, **kwargs):
'''
Executes the given rpc. The returned data can be stored in a file
by specifying the destination path with dest as an argument
.. code-block:: yaml
get-interface-information:
junos:
- rpc
- dest: /home/user/rpc.log
- interface_name: lo0
Parameters:
Required
* cmd:
The rpc to be executed. (default = None)
Optional
* dest:
Destination file where the rpc output is stored. (default = None)
Note that the file will be stored on the proxy minion. To push the
files to the master use the salt's following execution module: \
:py:func:`cp.push <salt.modules.cp.push>`
* format:
The format in which the rpc reply must be stored in file specified in the dest
(used only when dest is specified) (default = xml)
* kwargs: keyworded arguments taken by rpc call like-
* timeout:
Set NETCONF RPC timeout. Can be used for commands which
take a while to execute. (default= 30 seconds)
* filter:
Only to be used with 'get-config' rpc to get specific configuration.
* terse:
Amount of information you want.
* interface_name:
Name of the interface whose information you want.
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.rpc'](name, dest, **kwargs)
return ret | [
"def",
"rpc",
"(",
"name",
",",
"dest",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"ret",
"[",
"'chang... | Executes the given rpc. The returned data can be stored in a file
by specifying the destination path with dest as an argument
.. code-block:: yaml
get-interface-information:
junos:
- rpc
- dest: /home/user/rpc.log
- interface_name: lo0
Parameters:
Required
* cmd:
The rpc to be executed. (default = None)
Optional
* dest:
Destination file where the rpc output is stored. (default = None)
Note that the file will be stored on the proxy minion. To push the
files to the master use the salt's following execution module: \
:py:func:`cp.push <salt.modules.cp.push>`
* format:
The format in which the rpc reply must be stored in file specified in the dest
(used only when dest is specified) (default = xml)
* kwargs: keyworded arguments taken by rpc call like-
* timeout:
Set NETCONF RPC timeout. Can be used for commands which
take a while to execute. (default= 30 seconds)
* filter:
Only to be used with 'get-config' rpc to get specific configuration.
* terse:
Amount of information you want.
* interface_name:
Name of the interface whose information you want. | [
"Executes",
"the",
"given",
"rpc",
".",
"The",
"returned",
"data",
"can",
"be",
"stored",
"in",
"a",
"file",
"by",
"specifying",
"the",
"destination",
"path",
"with",
"dest",
"as",
"an",
"argument"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/junos.py#L35-L75 | train |
saltstack/salt | salt/states/junos.py | set_hostname | def set_hostname(name, **kwargs):
'''
Changes the hostname of the device.
.. code-block:: yaml
device_name:
junos:
- set_hostname
- comment: "Host-name set via saltstack."
Parameters:
Required
* hostname: The name to be set. (default = None)
Optional
* kwargs: Keyworded arguments which can be provided like-
* timeout:
Set NETCONF RPC timeout. Can be used for commands
which take a while to execute. (default = 30 seconds)
* comment:
Provide a comment to the commit. (default = None)
* confirm:
Provide time in minutes for commit confirmation. \
If this option is specified, the commit will be rollbacked in \
the given time unless the commit is confirmed.
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.set_hostname'](name, **kwargs)
return ret | python | def set_hostname(name, **kwargs):
'''
Changes the hostname of the device.
.. code-block:: yaml
device_name:
junos:
- set_hostname
- comment: "Host-name set via saltstack."
Parameters:
Required
* hostname: The name to be set. (default = None)
Optional
* kwargs: Keyworded arguments which can be provided like-
* timeout:
Set NETCONF RPC timeout. Can be used for commands
which take a while to execute. (default = 30 seconds)
* comment:
Provide a comment to the commit. (default = None)
* confirm:
Provide time in minutes for commit confirmation. \
If this option is specified, the commit will be rollbacked in \
the given time unless the commit is confirmed.
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.set_hostname'](name, **kwargs)
return ret | [
"def",
"set_hostname",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"ret",
"[",
"'changes'",
"]",
"=",
"__... | Changes the hostname of the device.
.. code-block:: yaml
device_name:
junos:
- set_hostname
- comment: "Host-name set via saltstack."
Parameters:
Required
* hostname: The name to be set. (default = None)
Optional
* kwargs: Keyworded arguments which can be provided like-
* timeout:
Set NETCONF RPC timeout. Can be used for commands
which take a while to execute. (default = 30 seconds)
* comment:
Provide a comment to the commit. (default = None)
* confirm:
Provide time in minutes for commit confirmation. \
If this option is specified, the commit will be rollbacked in \
the given time unless the commit is confirmed. | [
"Changes",
"the",
"hostname",
"of",
"the",
"device",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/junos.py#L79-L109 | train |
saltstack/salt | salt/states/junos.py | commit | def commit(name, **kwargs):
'''
Commits the changes loaded into the candidate configuration.
.. code-block:: yaml
commit the changes:
junos:
- commit
- confirm: 10
Parameters:
Optional
* kwargs: Keyworded arguments which can be provided like-
* timeout:
Set NETCONF RPC timeout. Can be used for commands which take a \
while to execute. (default = 30 seconds)
* comment:
Provide a comment to the commit. (default = None)
* confirm:
Provide time in minutes for commit confirmation. If this option \
is specified, the commit will be rollbacked in the given time \
unless the commit is confirmed.
* sync:
On dual control plane systems, requests that the candidate\
configuration on one control plane be copied to the other \
control plane,checked for correct syntax, and committed on \
both Routing Engines. (default = False)
* force_sync:
On dual control plane systems, force the candidate configuration
on one control plane to be copied to the other control plane.
* full:
When set to True requires all the daemons to check and evaluate \
the new configuration.
* detail:
When true return commit detail.
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.commit'](**kwargs)
return ret | python | def commit(name, **kwargs):
'''
Commits the changes loaded into the candidate configuration.
.. code-block:: yaml
commit the changes:
junos:
- commit
- confirm: 10
Parameters:
Optional
* kwargs: Keyworded arguments which can be provided like-
* timeout:
Set NETCONF RPC timeout. Can be used for commands which take a \
while to execute. (default = 30 seconds)
* comment:
Provide a comment to the commit. (default = None)
* confirm:
Provide time in minutes for commit confirmation. If this option \
is specified, the commit will be rollbacked in the given time \
unless the commit is confirmed.
* sync:
On dual control plane systems, requests that the candidate\
configuration on one control plane be copied to the other \
control plane,checked for correct syntax, and committed on \
both Routing Engines. (default = False)
* force_sync:
On dual control plane systems, force the candidate configuration
on one control plane to be copied to the other control plane.
* full:
When set to True requires all the daemons to check and evaluate \
the new configuration.
* detail:
When true return commit detail.
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.commit'](**kwargs)
return ret | [
"def",
"commit",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"ret",
"[",
"'changes'",
"]",
"=",
"__salt__... | Commits the changes loaded into the candidate configuration.
.. code-block:: yaml
commit the changes:
junos:
- commit
- confirm: 10
Parameters:
Optional
* kwargs: Keyworded arguments which can be provided like-
* timeout:
Set NETCONF RPC timeout. Can be used for commands which take a \
while to execute. (default = 30 seconds)
* comment:
Provide a comment to the commit. (default = None)
* confirm:
Provide time in minutes for commit confirmation. If this option \
is specified, the commit will be rollbacked in the given time \
unless the commit is confirmed.
* sync:
On dual control plane systems, requests that the candidate\
configuration on one control plane be copied to the other \
control plane,checked for correct syntax, and committed on \
both Routing Engines. (default = False)
* force_sync:
On dual control plane systems, force the candidate configuration
on one control plane to be copied to the other control plane.
* full:
When set to True requires all the daemons to check and evaluate \
the new configuration.
* detail:
When true return commit detail. | [
"Commits",
"the",
"changes",
"loaded",
"into",
"the",
"candidate",
"configuration",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/junos.py#L113-L153 | train |
saltstack/salt | salt/states/junos.py | rollback | def rollback(name, **kwargs):
'''
Rollbacks the committed changes.
.. code-block:: yaml
rollback the changes:
junos:
- rollback
- id: 5
Parameters:
Optional
* id:
The rollback id value [0-49]. (default = 0)
* kwargs: Keyworded arguments which can be provided like-
* timeout:
Set NETCONF RPC timeout. Can be used for commands which
take a while to execute. (default = 30 seconds)
* comment:
Provide a comment to the commit. (default = None)
* confirm:
Provide time in minutes for commit confirmation. If this option \
is specified, the commit will be rollbacked in the given time \
unless the commit is confirmed.
* diffs_file:
Path to the file where any diffs will be written. (default = None)
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.rollback'](**kwargs)
return ret | python | def rollback(name, **kwargs):
'''
Rollbacks the committed changes.
.. code-block:: yaml
rollback the changes:
junos:
- rollback
- id: 5
Parameters:
Optional
* id:
The rollback id value [0-49]. (default = 0)
* kwargs: Keyworded arguments which can be provided like-
* timeout:
Set NETCONF RPC timeout. Can be used for commands which
take a while to execute. (default = 30 seconds)
* comment:
Provide a comment to the commit. (default = None)
* confirm:
Provide time in minutes for commit confirmation. If this option \
is specified, the commit will be rollbacked in the given time \
unless the commit is confirmed.
* diffs_file:
Path to the file where any diffs will be written. (default = None)
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.rollback'](**kwargs)
return ret | [
"def",
"rollback",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"ret",
"[",
"'changes'",
"]",
"=",
"__salt... | Rollbacks the committed changes.
.. code-block:: yaml
rollback the changes:
junos:
- rollback
- id: 5
Parameters:
Optional
* id:
The rollback id value [0-49]. (default = 0)
* kwargs: Keyworded arguments which can be provided like-
* timeout:
Set NETCONF RPC timeout. Can be used for commands which
take a while to execute. (default = 30 seconds)
* comment:
Provide a comment to the commit. (default = None)
* confirm:
Provide time in minutes for commit confirmation. If this option \
is specified, the commit will be rollbacked in the given time \
unless the commit is confirmed.
* diffs_file:
Path to the file where any diffs will be written. (default = None) | [
"Rollbacks",
"the",
"committed",
"changes",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/junos.py#L157-L188 | train |
saltstack/salt | salt/states/junos.py | diff | def diff(name, **kwargs):
'''
Gets the difference between the candidate and the current configuration.
.. code-block:: yaml
get the diff:
junos:
- diff
- id: 10
Parameters:
Optional
* id:
The rollback id value [0-49]. (default = 0)
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.diff'](**kwargs)
return ret | python | def diff(name, **kwargs):
'''
Gets the difference between the candidate and the current configuration.
.. code-block:: yaml
get the diff:
junos:
- diff
- id: 10
Parameters:
Optional
* id:
The rollback id value [0-49]. (default = 0)
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.diff'](**kwargs)
return ret | [
"def",
"diff",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"ret",
"[",
"'changes'",
"]",
"=",
"__salt__",... | Gets the difference between the candidate and the current configuration.
.. code-block:: yaml
get the diff:
junos:
- diff
- id: 10
Parameters:
Optional
* id:
The rollback id value [0-49]. (default = 0) | [
"Gets",
"the",
"difference",
"between",
"the",
"candidate",
"and",
"the",
"current",
"configuration",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/junos.py#L192-L210 | train |
saltstack/salt | salt/states/junos.py | cli | def cli(name, format='text', **kwargs):
'''
Executes the CLI commands and reuturns the text output.
.. code-block:: yaml
show version:
junos:
- cli
- format: xml
Parameters:
Required
* command:
The command that need to be executed on Junos CLI. (default = None)
Optional
* format:
Format in which to get the CLI output. (text or xml, \
default = 'text')
* kwargs: Keyworded arguments which can be provided like-
* timeout:
Set NETCONF RPC timeout. Can be used for commands which
take a while to execute. (default = 30 seconds)
* dest:
The destination file where the CLI output can be stored.\
(default = None)
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.cli'](name, format, **kwargs)
return ret | python | def cli(name, format='text', **kwargs):
'''
Executes the CLI commands and reuturns the text output.
.. code-block:: yaml
show version:
junos:
- cli
- format: xml
Parameters:
Required
* command:
The command that need to be executed on Junos CLI. (default = None)
Optional
* format:
Format in which to get the CLI output. (text or xml, \
default = 'text')
* kwargs: Keyworded arguments which can be provided like-
* timeout:
Set NETCONF RPC timeout. Can be used for commands which
take a while to execute. (default = 30 seconds)
* dest:
The destination file where the CLI output can be stored.\
(default = None)
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.cli'](name, format, **kwargs)
return ret | [
"def",
"cli",
"(",
"name",
",",
"format",
"=",
"'text'",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"ret",
"[",
"'c... | Executes the CLI commands and reuturns the text output.
.. code-block:: yaml
show version:
junos:
- cli
- format: xml
Parameters:
Required
* command:
The command that need to be executed on Junos CLI. (default = None)
Optional
* format:
Format in which to get the CLI output. (text or xml, \
default = 'text')
* kwargs: Keyworded arguments which can be provided like-
* timeout:
Set NETCONF RPC timeout. Can be used for commands which
take a while to execute. (default = 30 seconds)
* dest:
The destination file where the CLI output can be stored.\
(default = None) | [
"Executes",
"the",
"CLI",
"commands",
"and",
"reuturns",
"the",
"text",
"output",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/junos.py#L214-L243 | train |
saltstack/salt | salt/states/junos.py | shutdown | def shutdown(name, **kwargs):
'''
Shuts down the device.
.. code-block:: yaml
shut the device:
junos:
- shutdown
- in_min: 10
Parameters:
Optional
* kwargs:
* reboot:
Whether to reboot instead of shutdown. (default=False)
* at:
Specify time for reboot. (To be used only if reboot=yes)
* in_min:
Specify delay in minutes for shutdown
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.shutdown'](**kwargs)
return ret | python | def shutdown(name, **kwargs):
'''
Shuts down the device.
.. code-block:: yaml
shut the device:
junos:
- shutdown
- in_min: 10
Parameters:
Optional
* kwargs:
* reboot:
Whether to reboot instead of shutdown. (default=False)
* at:
Specify time for reboot. (To be used only if reboot=yes)
* in_min:
Specify delay in minutes for shutdown
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.shutdown'](**kwargs)
return ret | [
"def",
"shutdown",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"ret",
"[",
"'changes'",
"]",
"=",
"__salt... | Shuts down the device.
.. code-block:: yaml
shut the device:
junos:
- shutdown
- in_min: 10
Parameters:
Optional
* kwargs:
* reboot:
Whether to reboot instead of shutdown. (default=False)
* at:
Specify time for reboot. (To be used only if reboot=yes)
* in_min:
Specify delay in minutes for shutdown | [
"Shuts",
"down",
"the",
"device",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/junos.py#L247-L270 | train |
saltstack/salt | salt/states/junos.py | install_config | def install_config(name, **kwargs):
'''
Loads and commits the configuration provided.
.. code-block:: yaml
Install the mentioned config:
junos:
- install_config
- path: salt//configs/interface.set
- timeout: 100
- diffs_file: 'var/log/diff'
.. code-block:: yaml
Install the mentioned config:
junos:
- install_config
- template_path: salt//configs/interface.set
- timeout: 100
- template_vars:
interface_name: lo0
description: Creating interface via SaltStack.
name
Path where the configuration/template file is present. If the file has
a ``*.conf`` extension, the content is treated as text format. If the
file has a ``*.xml`` extension, the content is treated as XML format. If
the file has a ``*.set`` extension, the content is treated as Junos OS
``set`` commands
template_vars
The dictionary of data for the jinja variables present in the jinja
template
timeout : 30
Set NETCONF RPC timeout. Can be used for commands which take a while to
execute.
overwrite : False
Set to ``True`` if you want this file is to completely replace the
configuration file.
replace : False
Specify whether the configuration file uses "replace:" statements. Only
those statements under the 'replace' tag will be changed.
comment
Provide a comment to the commit. (default = None)
confirm
Provide time in minutes for commit confirmation. If this option is
specified, the commit will be rolled back in the given time unless the
commit is confirmed.
diffs_file
Path to the file where the diff (difference in old configuration and the
committed configuration) will be stored.
.. note::
The file will be stored on the proxy minion. To push the files to the
master use :py:func:`cp.push <salt.modules.cp.push>`.
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.install_config'](name, **kwargs)
return ret | python | def install_config(name, **kwargs):
'''
Loads and commits the configuration provided.
.. code-block:: yaml
Install the mentioned config:
junos:
- install_config
- path: salt//configs/interface.set
- timeout: 100
- diffs_file: 'var/log/diff'
.. code-block:: yaml
Install the mentioned config:
junos:
- install_config
- template_path: salt//configs/interface.set
- timeout: 100
- template_vars:
interface_name: lo0
description: Creating interface via SaltStack.
name
Path where the configuration/template file is present. If the file has
a ``*.conf`` extension, the content is treated as text format. If the
file has a ``*.xml`` extension, the content is treated as XML format. If
the file has a ``*.set`` extension, the content is treated as Junos OS
``set`` commands
template_vars
The dictionary of data for the jinja variables present in the jinja
template
timeout : 30
Set NETCONF RPC timeout. Can be used for commands which take a while to
execute.
overwrite : False
Set to ``True`` if you want this file is to completely replace the
configuration file.
replace : False
Specify whether the configuration file uses "replace:" statements. Only
those statements under the 'replace' tag will be changed.
comment
Provide a comment to the commit. (default = None)
confirm
Provide time in minutes for commit confirmation. If this option is
specified, the commit will be rolled back in the given time unless the
commit is confirmed.
diffs_file
Path to the file where the diff (difference in old configuration and the
committed configuration) will be stored.
.. note::
The file will be stored on the proxy minion. To push the files to the
master use :py:func:`cp.push <salt.modules.cp.push>`.
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.install_config'](name, **kwargs)
return ret | [
"def",
"install_config",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"ret",
"[",
"'changes'",
"]",
"=",
"... | Loads and commits the configuration provided.
.. code-block:: yaml
Install the mentioned config:
junos:
- install_config
- path: salt//configs/interface.set
- timeout: 100
- diffs_file: 'var/log/diff'
.. code-block:: yaml
Install the mentioned config:
junos:
- install_config
- template_path: salt//configs/interface.set
- timeout: 100
- template_vars:
interface_name: lo0
description: Creating interface via SaltStack.
name
Path where the configuration/template file is present. If the file has
a ``*.conf`` extension, the content is treated as text format. If the
file has a ``*.xml`` extension, the content is treated as XML format. If
the file has a ``*.set`` extension, the content is treated as Junos OS
``set`` commands
template_vars
The dictionary of data for the jinja variables present in the jinja
template
timeout : 30
Set NETCONF RPC timeout. Can be used for commands which take a while to
execute.
overwrite : False
Set to ``True`` if you want this file is to completely replace the
configuration file.
replace : False
Specify whether the configuration file uses "replace:" statements. Only
those statements under the 'replace' tag will be changed.
comment
Provide a comment to the commit. (default = None)
confirm
Provide time in minutes for commit confirmation. If this option is
specified, the commit will be rolled back in the given time unless the
commit is confirmed.
diffs_file
Path to the file where the diff (difference in old configuration and the
committed configuration) will be stored.
.. note::
The file will be stored on the proxy minion. To push the files to the
master use :py:func:`cp.push <salt.modules.cp.push>`. | [
"Loads",
"and",
"commits",
"the",
"configuration",
"provided",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/junos.py#L274-L342 | train |
saltstack/salt | salt/states/junos.py | install_os | def install_os(name, **kwargs):
'''
Installs the given image on the device. After the installation is complete
the device is rebooted, if reboot=True is given as a keyworded argument.
.. code-block:: yaml
salt://images/junos_image.tgz:
junos:
- install_os
- timeout: 100
- reboot: True
Parameters:
Required
* path:
Path where the image file is present on the pro\
xy minion.
Optional
* kwargs: keyworded arguments to be given such as timeout, reboot etc
* timeout:
Set NETCONF RPC timeout. Can be used to RPCs which
take a while to execute. (default = 30 seconds)
* reboot:
Whether to reboot after installation (default = False)
* no_copy:
When True the software package will not be SCP’d to the device. \
(default = False)
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.install_os'](name, **kwargs)
return ret | python | def install_os(name, **kwargs):
'''
Installs the given image on the device. After the installation is complete
the device is rebooted, if reboot=True is given as a keyworded argument.
.. code-block:: yaml
salt://images/junos_image.tgz:
junos:
- install_os
- timeout: 100
- reboot: True
Parameters:
Required
* path:
Path where the image file is present on the pro\
xy minion.
Optional
* kwargs: keyworded arguments to be given such as timeout, reboot etc
* timeout:
Set NETCONF RPC timeout. Can be used to RPCs which
take a while to execute. (default = 30 seconds)
* reboot:
Whether to reboot after installation (default = False)
* no_copy:
When True the software package will not be SCP’d to the device. \
(default = False)
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.install_os'](name, **kwargs)
return ret | [
"def",
"install_os",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"ret",
"[",
"'changes'",
"]",
"=",
"__sa... | Installs the given image on the device. After the installation is complete
the device is rebooted, if reboot=True is given as a keyworded argument.
.. code-block:: yaml
salt://images/junos_image.tgz:
junos:
- install_os
- timeout: 100
- reboot: True
Parameters:
Required
* path:
Path where the image file is present on the pro\
xy minion.
Optional
* kwargs: keyworded arguments to be given such as timeout, reboot etc
* timeout:
Set NETCONF RPC timeout. Can be used to RPCs which
take a while to execute. (default = 30 seconds)
* reboot:
Whether to reboot after installation (default = False)
* no_copy:
When True the software package will not be SCP’d to the device. \
(default = False) | [
"Installs",
"the",
"given",
"image",
"on",
"the",
"device",
".",
"After",
"the",
"installation",
"is",
"complete",
"the",
"device",
"is",
"rebooted",
"if",
"reboot",
"=",
"True",
"is",
"given",
"as",
"a",
"keyworded",
"argument",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/junos.py#L363-L395 | train |
saltstack/salt | salt/states/junos.py | file_copy | def file_copy(name, dest=None, **kwargs):
'''
Copies the file from the local device to the junos device.
.. code-block:: yaml
/home/m2/info.txt:
junos:
- file_copy
- dest: info_copy.txt
Parameters:
Required
* src:
The sorce path where the file is kept.
* dest:
The destination path where the file will be copied.
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.file_copy'](name, dest, **kwargs)
return ret | python | def file_copy(name, dest=None, **kwargs):
'''
Copies the file from the local device to the junos device.
.. code-block:: yaml
/home/m2/info.txt:
junos:
- file_copy
- dest: info_copy.txt
Parameters:
Required
* src:
The sorce path where the file is kept.
* dest:
The destination path where the file will be copied.
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.file_copy'](name, dest, **kwargs)
return ret | [
"def",
"file_copy",
"(",
"name",
",",
"dest",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"ret",
"[",
"... | Copies the file from the local device to the junos device.
.. code-block:: yaml
/home/m2/info.txt:
junos:
- file_copy
- dest: info_copy.txt
Parameters:
Required
* src:
The sorce path where the file is kept.
* dest:
The destination path where the file will be copied. | [
"Copies",
"the",
"file",
"from",
"the",
"local",
"device",
"to",
"the",
"junos",
"device",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/junos.py#L399-L419 | train |
saltstack/salt | salt/states/junos.py | load | def load(name, **kwargs):
'''
Loads the configuration provided onto the junos device.
.. code-block:: yaml
Install the mentioned config:
junos:
- load
- path: salt//configs/interface.set
.. code-block:: yaml
Install the mentioned config:
junos:
- load
- template_path: salt//configs/interface.set
- template_vars:
interface_name: lo0
description: Creating interface via SaltStack.
name
Path where the configuration/template file is present. If the file has
a ``*.conf`` extension, the content is treated as text format. If the
file has a ``*.xml`` extension, the content is treated as XML format. If
the file has a ``*.set`` extension, the content is treated as Junos OS
``set`` commands.
overwrite : False
Set to ``True`` if you want this file is to completely replace the
configuration file.
replace : False
Specify whether the configuration file uses "replace:" statements.
Only those statements under the 'replace' tag will be changed.
format:
Determines the format of the contents.
update : False
Compare a complete loaded configuration against the candidate
configuration. For each hierarchy level or configuration object that is
different in the two configurations, the version in the loaded
configuration replaces the version in the candidate configuration. When
the configuration is later committed, only system processes that are
affected by the changed configuration elements parse the new
configuration. This action is supported from PyEZ 2.1 (default = False)
template_vars
Variables to be passed into the template processing engine in addition
to those present in __pillar__, __opts__, __grains__, etc.
You may reference these variables in your template like so:
{{ template_vars["var_name"] }}
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.load'](name, **kwargs)
return ret | python | def load(name, **kwargs):
'''
Loads the configuration provided onto the junos device.
.. code-block:: yaml
Install the mentioned config:
junos:
- load
- path: salt//configs/interface.set
.. code-block:: yaml
Install the mentioned config:
junos:
- load
- template_path: salt//configs/interface.set
- template_vars:
interface_name: lo0
description: Creating interface via SaltStack.
name
Path where the configuration/template file is present. If the file has
a ``*.conf`` extension, the content is treated as text format. If the
file has a ``*.xml`` extension, the content is treated as XML format. If
the file has a ``*.set`` extension, the content is treated as Junos OS
``set`` commands.
overwrite : False
Set to ``True`` if you want this file is to completely replace the
configuration file.
replace : False
Specify whether the configuration file uses "replace:" statements.
Only those statements under the 'replace' tag will be changed.
format:
Determines the format of the contents.
update : False
Compare a complete loaded configuration against the candidate
configuration. For each hierarchy level or configuration object that is
different in the two configurations, the version in the loaded
configuration replaces the version in the candidate configuration. When
the configuration is later committed, only system processes that are
affected by the changed configuration elements parse the new
configuration. This action is supported from PyEZ 2.1 (default = False)
template_vars
Variables to be passed into the template processing engine in addition
to those present in __pillar__, __opts__, __grains__, etc.
You may reference these variables in your template like so:
{{ template_vars["var_name"] }}
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.load'](name, **kwargs)
return ret | [
"def",
"load",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"ret",
"[",
"'changes'",
"]",
"=",
"__salt__",... | Loads the configuration provided onto the junos device.
.. code-block:: yaml
Install the mentioned config:
junos:
- load
- path: salt//configs/interface.set
.. code-block:: yaml
Install the mentioned config:
junos:
- load
- template_path: salt//configs/interface.set
- template_vars:
interface_name: lo0
description: Creating interface via SaltStack.
name
Path where the configuration/template file is present. If the file has
a ``*.conf`` extension, the content is treated as text format. If the
file has a ``*.xml`` extension, the content is treated as XML format. If
the file has a ``*.set`` extension, the content is treated as Junos OS
``set`` commands.
overwrite : False
Set to ``True`` if you want this file is to completely replace the
configuration file.
replace : False
Specify whether the configuration file uses "replace:" statements.
Only those statements under the 'replace' tag will be changed.
format:
Determines the format of the contents.
update : False
Compare a complete loaded configuration against the candidate
configuration. For each hierarchy level or configuration object that is
different in the two configurations, the version in the loaded
configuration replaces the version in the candidate configuration. When
the configuration is later committed, only system processes that are
affected by the changed configuration elements parse the new
configuration. This action is supported from PyEZ 2.1 (default = False)
template_vars
Variables to be passed into the template processing engine in addition
to those present in __pillar__, __opts__, __grains__, etc.
You may reference these variables in your template like so:
{{ template_vars["var_name"] }} | [
"Loads",
"the",
"configuration",
"provided",
"onto",
"the",
"junos",
"device",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/junos.py#L461-L519 | train |
saltstack/salt | salt/states/junos.py | get_table | def get_table(name, table, table_file, **kwargs):
'''
Retrieve data from a Junos device using Tables/Views
name (required)
task definition
table (required)
Name of PyEZ Table
file
YAML file that has the table specified in table parameter
path:
Path of location of the YAML file.
defaults to op directory in jnpr.junos.op
target:
if command need to run on FPC, can specify fpc target
key:
To overwrite key provided in YAML
key_items:
To select only given key items
filters:
To select only filter for the dictionary from columns
template_args:
key/value pair which should render Jinja template command
.. code-block:: yaml
get route details:
junos.get_table:
- table: RouteTable
- file: routes.yml
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.get_table'](table, table_file, **kwargs)
return ret | python | def get_table(name, table, table_file, **kwargs):
'''
Retrieve data from a Junos device using Tables/Views
name (required)
task definition
table (required)
Name of PyEZ Table
file
YAML file that has the table specified in table parameter
path:
Path of location of the YAML file.
defaults to op directory in jnpr.junos.op
target:
if command need to run on FPC, can specify fpc target
key:
To overwrite key provided in YAML
key_items:
To select only given key items
filters:
To select only filter for the dictionary from columns
template_args:
key/value pair which should render Jinja template command
.. code-block:: yaml
get route details:
junos.get_table:
- table: RouteTable
- file: routes.yml
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.get_table'](table, table_file, **kwargs)
return ret | [
"def",
"get_table",
"(",
"name",
",",
"table",
",",
"table_file",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"ret",
"... | Retrieve data from a Junos device using Tables/Views
name (required)
task definition
table (required)
Name of PyEZ Table
file
YAML file that has the table specified in table parameter
path:
Path of location of the YAML file.
defaults to op directory in jnpr.junos.op
target:
if command need to run on FPC, can specify fpc target
key:
To overwrite key provided in YAML
key_items:
To select only given key items
filters:
To select only filter for the dictionary from columns
template_args:
key/value pair which should render Jinja template command
.. code-block:: yaml
get route details:
junos.get_table:
- table: RouteTable
- file: routes.yml | [
"Retrieve",
"data",
"from",
"a",
"Junos",
"device",
"using",
"Tables",
"/",
"Views"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/junos.py#L540-L581 | train |
saltstack/salt | salt/modules/extfs.py | mkfs | def mkfs(device, fs_type, **kwargs):
'''
Create a file system on the specified device
CLI Example:
.. code-block:: bash
salt '*' extfs.mkfs /dev/sda1 fs_type=ext4 opts='acl,noexec'
Valid options are:
* **block_size**: 1024, 2048 or 4096
* **check**: check for bad blocks
* **direct**: use direct IO
* **ext_opts**: extended file system options (comma-separated)
* **fragment_size**: size of fragments
* **force**: setting force to True will cause mke2fs to specify the -F
option twice (it is already set once); this is truly dangerous
* **blocks_per_group**: number of blocks in a block group
* **number_of_groups**: ext4 option for a virtual block group
* **bytes_per_inode**: set the bytes/inode ratio
* **inode_size**: size of the inode
* **journal**: set to True to create a journal (default on ext3/4)
* **journal_opts**: options for the fs journal (comma separated)
* **blocks_file**: read bad blocks from file
* **label**: label to apply to the file system
* **reserved**: percentage of blocks reserved for super-user
* **last_dir**: last mounted directory
* **test**: set to True to not actually create the file system (mke2fs -n)
* **number_of_inodes**: override default number of inodes
* **creator_os**: override "creator operating system" field
* **opts**: mount options (comma separated)
* **revision**: set the filesystem revision (default 1)
* **super**: write superblock and group descriptors only
* **fs_type**: set the filesystem type (REQUIRED)
* **usage_type**: how the filesystem is going to be used
* **uuid**: set the UUID for the file system
See the ``mke2fs(8)`` manpage for a more complete description of these
options.
'''
kwarg_map = {'block_size': 'b',
'check': 'c',
'direct': 'D',
'ext_opts': 'E',
'fragment_size': 'f',
'force': 'F',
'blocks_per_group': 'g',
'number_of_groups': 'G',
'bytes_per_inode': 'i',
'inode_size': 'I',
'journal': 'j',
'journal_opts': 'J',
'blocks_file': 'l',
'label': 'L',
'reserved': 'm',
'last_dir': 'M',
'test': 'n',
'number_of_inodes': 'N',
'creator_os': 'o',
'opts': 'O',
'revision': 'r',
'super': 'S',
'usage_type': 'T',
'uuid': 'U'}
opts = ''
for key in kwargs:
if key in kwarg_map:
opt = kwarg_map[key]
if kwargs[key] == 'True':
opts += '-{0} '.format(opt)
else:
opts += '-{0} {1} '.format(opt, kwargs[key])
cmd = 'mke2fs -F -t {0} {1}{2}'.format(fs_type, opts, device)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
ret = []
for line in out:
if not line:
continue
elif line.startswith('mke2fs'):
continue
elif line.startswith('Discarding device blocks'):
continue
elif line.startswith('Allocating group tables'):
continue
elif line.startswith('Writing inode tables'):
continue
elif line.startswith('Creating journal'):
continue
elif line.startswith('Writing superblocks'):
continue
ret.append(line)
return ret | python | def mkfs(device, fs_type, **kwargs):
'''
Create a file system on the specified device
CLI Example:
.. code-block:: bash
salt '*' extfs.mkfs /dev/sda1 fs_type=ext4 opts='acl,noexec'
Valid options are:
* **block_size**: 1024, 2048 or 4096
* **check**: check for bad blocks
* **direct**: use direct IO
* **ext_opts**: extended file system options (comma-separated)
* **fragment_size**: size of fragments
* **force**: setting force to True will cause mke2fs to specify the -F
option twice (it is already set once); this is truly dangerous
* **blocks_per_group**: number of blocks in a block group
* **number_of_groups**: ext4 option for a virtual block group
* **bytes_per_inode**: set the bytes/inode ratio
* **inode_size**: size of the inode
* **journal**: set to True to create a journal (default on ext3/4)
* **journal_opts**: options for the fs journal (comma separated)
* **blocks_file**: read bad blocks from file
* **label**: label to apply to the file system
* **reserved**: percentage of blocks reserved for super-user
* **last_dir**: last mounted directory
* **test**: set to True to not actually create the file system (mke2fs -n)
* **number_of_inodes**: override default number of inodes
* **creator_os**: override "creator operating system" field
* **opts**: mount options (comma separated)
* **revision**: set the filesystem revision (default 1)
* **super**: write superblock and group descriptors only
* **fs_type**: set the filesystem type (REQUIRED)
* **usage_type**: how the filesystem is going to be used
* **uuid**: set the UUID for the file system
See the ``mke2fs(8)`` manpage for a more complete description of these
options.
'''
kwarg_map = {'block_size': 'b',
'check': 'c',
'direct': 'D',
'ext_opts': 'E',
'fragment_size': 'f',
'force': 'F',
'blocks_per_group': 'g',
'number_of_groups': 'G',
'bytes_per_inode': 'i',
'inode_size': 'I',
'journal': 'j',
'journal_opts': 'J',
'blocks_file': 'l',
'label': 'L',
'reserved': 'm',
'last_dir': 'M',
'test': 'n',
'number_of_inodes': 'N',
'creator_os': 'o',
'opts': 'O',
'revision': 'r',
'super': 'S',
'usage_type': 'T',
'uuid': 'U'}
opts = ''
for key in kwargs:
if key in kwarg_map:
opt = kwarg_map[key]
if kwargs[key] == 'True':
opts += '-{0} '.format(opt)
else:
opts += '-{0} {1} '.format(opt, kwargs[key])
cmd = 'mke2fs -F -t {0} {1}{2}'.format(fs_type, opts, device)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
ret = []
for line in out:
if not line:
continue
elif line.startswith('mke2fs'):
continue
elif line.startswith('Discarding device blocks'):
continue
elif line.startswith('Allocating group tables'):
continue
elif line.startswith('Writing inode tables'):
continue
elif line.startswith('Creating journal'):
continue
elif line.startswith('Writing superblocks'):
continue
ret.append(line)
return ret | [
"def",
"mkfs",
"(",
"device",
",",
"fs_type",
",",
"*",
"*",
"kwargs",
")",
":",
"kwarg_map",
"=",
"{",
"'block_size'",
":",
"'b'",
",",
"'check'",
":",
"'c'",
",",
"'direct'",
":",
"'D'",
",",
"'ext_opts'",
":",
"'E'",
",",
"'fragment_size'",
":",
"... | Create a file system on the specified device
CLI Example:
.. code-block:: bash
salt '*' extfs.mkfs /dev/sda1 fs_type=ext4 opts='acl,noexec'
Valid options are:
* **block_size**: 1024, 2048 or 4096
* **check**: check for bad blocks
* **direct**: use direct IO
* **ext_opts**: extended file system options (comma-separated)
* **fragment_size**: size of fragments
* **force**: setting force to True will cause mke2fs to specify the -F
option twice (it is already set once); this is truly dangerous
* **blocks_per_group**: number of blocks in a block group
* **number_of_groups**: ext4 option for a virtual block group
* **bytes_per_inode**: set the bytes/inode ratio
* **inode_size**: size of the inode
* **journal**: set to True to create a journal (default on ext3/4)
* **journal_opts**: options for the fs journal (comma separated)
* **blocks_file**: read bad blocks from file
* **label**: label to apply to the file system
* **reserved**: percentage of blocks reserved for super-user
* **last_dir**: last mounted directory
* **test**: set to True to not actually create the file system (mke2fs -n)
* **number_of_inodes**: override default number of inodes
* **creator_os**: override "creator operating system" field
* **opts**: mount options (comma separated)
* **revision**: set the filesystem revision (default 1)
* **super**: write superblock and group descriptors only
* **fs_type**: set the filesystem type (REQUIRED)
* **usage_type**: how the filesystem is going to be used
* **uuid**: set the UUID for the file system
See the ``mke2fs(8)`` manpage for a more complete description of these
options. | [
"Create",
"a",
"file",
"system",
"on",
"the",
"specified",
"device"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/extfs.py#L29-L123 | train |
saltstack/salt | salt/modules/extfs.py | tune | def tune(device, **kwargs):
'''
Set attributes for the specified device (using tune2fs)
CLI Example:
.. code-block:: bash
salt '*' extfs.tune /dev/sda1 force=True label=wildstallyns opts='acl,noexec'
Valid options are:
* **max**: max mount count
* **count**: mount count
* **error**: error behavior
* **extended_opts**: extended options (comma separated)
* **force**: force, even if there are errors (set to True)
* **group**: group name or gid that can use the reserved blocks
* **interval**: interval between checks
* **journal**: set to True to create a journal (default on ext3/4)
* **journal_opts**: options for the fs journal (comma separated)
* **label**: label to apply to the file system
* **reserved**: percentage of blocks reserved for super-user
* **last_dir**: last mounted directory
* **opts**: mount options (comma separated)
* **feature**: set or clear a feature (comma separated)
* **mmp_check**: mmp check interval
* **reserved**: reserved blocks count
* **quota_opts**: quota options (comma separated)
* **time**: time last checked
* **user**: user or uid who can use the reserved blocks
* **uuid**: set the UUID for the file system
See the ``mke2fs(8)`` manpage for a more complete description of these
options.
'''
kwarg_map = {'max': 'c',
'count': 'C',
'error': 'e',
'extended_opts': 'E',
'force': 'f',
'group': 'g',
'interval': 'i',
'journal': 'j',
'journal_opts': 'J',
'label': 'L',
'last_dir': 'M',
'opts': 'o',
'feature': 'O',
'mmp_check': 'p',
'reserved': 'r',
'quota_opts': 'Q',
'time': 'T',
'user': 'u',
'uuid': 'U'}
opts = ''
for key in kwargs:
if key in kwarg_map:
opt = kwarg_map[key]
if kwargs[key] == 'True':
opts += '-{0} '.format(opt)
else:
opts += '-{0} {1} '.format(opt, kwargs[key])
cmd = 'tune2fs {0}{1}'.format(opts, device)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return out | python | def tune(device, **kwargs):
'''
Set attributes for the specified device (using tune2fs)
CLI Example:
.. code-block:: bash
salt '*' extfs.tune /dev/sda1 force=True label=wildstallyns opts='acl,noexec'
Valid options are:
* **max**: max mount count
* **count**: mount count
* **error**: error behavior
* **extended_opts**: extended options (comma separated)
* **force**: force, even if there are errors (set to True)
* **group**: group name or gid that can use the reserved blocks
* **interval**: interval between checks
* **journal**: set to True to create a journal (default on ext3/4)
* **journal_opts**: options for the fs journal (comma separated)
* **label**: label to apply to the file system
* **reserved**: percentage of blocks reserved for super-user
* **last_dir**: last mounted directory
* **opts**: mount options (comma separated)
* **feature**: set or clear a feature (comma separated)
* **mmp_check**: mmp check interval
* **reserved**: reserved blocks count
* **quota_opts**: quota options (comma separated)
* **time**: time last checked
* **user**: user or uid who can use the reserved blocks
* **uuid**: set the UUID for the file system
See the ``mke2fs(8)`` manpage for a more complete description of these
options.
'''
kwarg_map = {'max': 'c',
'count': 'C',
'error': 'e',
'extended_opts': 'E',
'force': 'f',
'group': 'g',
'interval': 'i',
'journal': 'j',
'journal_opts': 'J',
'label': 'L',
'last_dir': 'M',
'opts': 'o',
'feature': 'O',
'mmp_check': 'p',
'reserved': 'r',
'quota_opts': 'Q',
'time': 'T',
'user': 'u',
'uuid': 'U'}
opts = ''
for key in kwargs:
if key in kwarg_map:
opt = kwarg_map[key]
if kwargs[key] == 'True':
opts += '-{0} '.format(opt)
else:
opts += '-{0} {1} '.format(opt, kwargs[key])
cmd = 'tune2fs {0}{1}'.format(opts, device)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return out | [
"def",
"tune",
"(",
"device",
",",
"*",
"*",
"kwargs",
")",
":",
"kwarg_map",
"=",
"{",
"'max'",
":",
"'c'",
",",
"'count'",
":",
"'C'",
",",
"'error'",
":",
"'e'",
",",
"'extended_opts'",
":",
"'E'",
",",
"'force'",
":",
"'f'",
",",
"'group'",
":"... | Set attributes for the specified device (using tune2fs)
CLI Example:
.. code-block:: bash
salt '*' extfs.tune /dev/sda1 force=True label=wildstallyns opts='acl,noexec'
Valid options are:
* **max**: max mount count
* **count**: mount count
* **error**: error behavior
* **extended_opts**: extended options (comma separated)
* **force**: force, even if there are errors (set to True)
* **group**: group name or gid that can use the reserved blocks
* **interval**: interval between checks
* **journal**: set to True to create a journal (default on ext3/4)
* **journal_opts**: options for the fs journal (comma separated)
* **label**: label to apply to the file system
* **reserved**: percentage of blocks reserved for super-user
* **last_dir**: last mounted directory
* **opts**: mount options (comma separated)
* **feature**: set or clear a feature (comma separated)
* **mmp_check**: mmp check interval
* **reserved**: reserved blocks count
* **quota_opts**: quota options (comma separated)
* **time**: time last checked
* **user**: user or uid who can use the reserved blocks
* **uuid**: set the UUID for the file system
See the ``mke2fs(8)`` manpage for a more complete description of these
options. | [
"Set",
"attributes",
"for",
"the",
"specified",
"device",
"(",
"using",
"tune2fs",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/extfs.py#L126-L191 | train |
saltstack/salt | salt/modules/extfs.py | dump | def dump(device, args=None):
'''
Return all contents of dumpe2fs for a specified device
CLI Example:
.. code-block:: bash
salt '*' extfs.dump /dev/sda1
'''
cmd = 'dumpe2fs {0}'.format(device)
if args:
cmd = cmd + ' -' + args
ret = {'attributes': {}, 'blocks': {}}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
mode = 'opts'
group = None
for line in out:
if not line:
continue
if line.startswith('dumpe2fs'):
continue
if mode == 'opts':
line = line.replace('\t', ' ')
comps = line.split(': ')
if line.startswith('Filesystem features'):
ret['attributes'][comps[0]] = comps[1].split()
elif line.startswith('Group') and not line.startswith('Group descriptor size'):
mode = 'blocks'
else:
if len(comps) < 2:
continue
ret['attributes'][comps[0]] = comps[1].strip()
if mode == 'blocks':
if line.startswith('Group'):
line = line.replace(':', '')
line = line.replace('(', '')
line = line.replace(')', '')
line = line.replace('[', '')
line = line.replace(']', '')
comps = line.split()
blkgrp = comps[1]
group = 'Group {0}'.format(blkgrp)
ret['blocks'][group] = {}
ret['blocks'][group]['group'] = blkgrp
ret['blocks'][group]['range'] = comps[3]
# TODO: comps[4:], which may look one one of the following:
# ITABLE_ZEROED
# INODE_UNINIT, ITABLE_ZEROED
# Does anyone know what to call these?
ret['blocks'][group]['extra'] = []
elif 'Free blocks:' in line:
comps = line.split(': ')
free_blocks = comps[1].split(', ')
ret['blocks'][group]['free blocks'] = free_blocks
elif 'Free inodes:' in line:
comps = line.split(': ')
inodes = comps[1].split(', ')
ret['blocks'][group]['free inodes'] = inodes
else:
line = line.strip()
ret['blocks'][group]['extra'].append(line)
return ret | python | def dump(device, args=None):
'''
Return all contents of dumpe2fs for a specified device
CLI Example:
.. code-block:: bash
salt '*' extfs.dump /dev/sda1
'''
cmd = 'dumpe2fs {0}'.format(device)
if args:
cmd = cmd + ' -' + args
ret = {'attributes': {}, 'blocks': {}}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
mode = 'opts'
group = None
for line in out:
if not line:
continue
if line.startswith('dumpe2fs'):
continue
if mode == 'opts':
line = line.replace('\t', ' ')
comps = line.split(': ')
if line.startswith('Filesystem features'):
ret['attributes'][comps[0]] = comps[1].split()
elif line.startswith('Group') and not line.startswith('Group descriptor size'):
mode = 'blocks'
else:
if len(comps) < 2:
continue
ret['attributes'][comps[0]] = comps[1].strip()
if mode == 'blocks':
if line.startswith('Group'):
line = line.replace(':', '')
line = line.replace('(', '')
line = line.replace(')', '')
line = line.replace('[', '')
line = line.replace(']', '')
comps = line.split()
blkgrp = comps[1]
group = 'Group {0}'.format(blkgrp)
ret['blocks'][group] = {}
ret['blocks'][group]['group'] = blkgrp
ret['blocks'][group]['range'] = comps[3]
# TODO: comps[4:], which may look one one of the following:
# ITABLE_ZEROED
# INODE_UNINIT, ITABLE_ZEROED
# Does anyone know what to call these?
ret['blocks'][group]['extra'] = []
elif 'Free blocks:' in line:
comps = line.split(': ')
free_blocks = comps[1].split(', ')
ret['blocks'][group]['free blocks'] = free_blocks
elif 'Free inodes:' in line:
comps = line.split(': ')
inodes = comps[1].split(', ')
ret['blocks'][group]['free inodes'] = inodes
else:
line = line.strip()
ret['blocks'][group]['extra'].append(line)
return ret | [
"def",
"dump",
"(",
"device",
",",
"args",
"=",
"None",
")",
":",
"cmd",
"=",
"'dumpe2fs {0}'",
".",
"format",
"(",
"device",
")",
"if",
"args",
":",
"cmd",
"=",
"cmd",
"+",
"' -'",
"+",
"args",
"ret",
"=",
"{",
"'attributes'",
":",
"{",
"}",
","... | Return all contents of dumpe2fs for a specified device
CLI Example:
.. code-block:: bash
salt '*' extfs.dump /dev/sda1 | [
"Return",
"all",
"contents",
"of",
"dumpe2fs",
"for",
"a",
"specified",
"device"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/extfs.py#L222-L285 | train |
saltstack/salt | salt/utils/verify.py | zmq_version | def zmq_version():
'''
ZeroMQ python bindings >= 2.1.9 are required
'''
try:
import zmq
except Exception:
# Return True for local mode
return True
ver = zmq.__version__
# The last matched group can be None if the version
# is something like 3.1 and that will work properly
match = re.match(r'^(\d+)\.(\d+)(?:\.(\d+))?', ver)
# Fallthrough and hope for the best
if not match:
msg = "Using untested zmq python bindings version: '{0}'".format(ver)
if is_console_configured():
log.warning(msg)
else:
sys.stderr.write("WARNING {0}\n".format(msg))
return True
major, minor, point = match.groups()
if major.isdigit():
major = int(major)
if minor.isdigit():
minor = int(minor)
# point very well could be None
if point and point.isdigit():
point = int(point)
if major == 2 and minor == 1:
# zmq 2.1dev could be built against a newer libzmq
if "dev" in ver and not point:
msg = 'Using dev zmq module, please report unexpected results'
if is_console_configured():
log.warning(msg)
else:
sys.stderr.write("WARNING: {0}\n".format(msg))
return True
elif point and point >= 9:
return True
elif major > 2 or (major == 2 and minor > 1):
return True
# If all else fails, gracefully croak and warn the user
log.critical('ZeroMQ python bindings >= 2.1.9 are required')
if 'salt-master' in sys.argv[0]:
msg = ('The Salt Master is unstable using a ZeroMQ version '
'lower than 2.1.11 and requires this fix: http://lists.zeromq.'
'org/pipermail/zeromq-dev/2011-June/012094.html')
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write('CRITICAL {0}\n'.format(msg))
return False | python | def zmq_version():
'''
ZeroMQ python bindings >= 2.1.9 are required
'''
try:
import zmq
except Exception:
# Return True for local mode
return True
ver = zmq.__version__
# The last matched group can be None if the version
# is something like 3.1 and that will work properly
match = re.match(r'^(\d+)\.(\d+)(?:\.(\d+))?', ver)
# Fallthrough and hope for the best
if not match:
msg = "Using untested zmq python bindings version: '{0}'".format(ver)
if is_console_configured():
log.warning(msg)
else:
sys.stderr.write("WARNING {0}\n".format(msg))
return True
major, minor, point = match.groups()
if major.isdigit():
major = int(major)
if minor.isdigit():
minor = int(minor)
# point very well could be None
if point and point.isdigit():
point = int(point)
if major == 2 and minor == 1:
# zmq 2.1dev could be built against a newer libzmq
if "dev" in ver and not point:
msg = 'Using dev zmq module, please report unexpected results'
if is_console_configured():
log.warning(msg)
else:
sys.stderr.write("WARNING: {0}\n".format(msg))
return True
elif point and point >= 9:
return True
elif major > 2 or (major == 2 and minor > 1):
return True
# If all else fails, gracefully croak and warn the user
log.critical('ZeroMQ python bindings >= 2.1.9 are required')
if 'salt-master' in sys.argv[0]:
msg = ('The Salt Master is unstable using a ZeroMQ version '
'lower than 2.1.11 and requires this fix: http://lists.zeromq.'
'org/pipermail/zeromq-dev/2011-June/012094.html')
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write('CRITICAL {0}\n'.format(msg))
return False | [
"def",
"zmq_version",
"(",
")",
":",
"try",
":",
"import",
"zmq",
"except",
"Exception",
":",
"# Return True for local mode",
"return",
"True",
"ver",
"=",
"zmq",
".",
"__version__",
"# The last matched group can be None if the version",
"# is something like 3.1 and that wi... | ZeroMQ python bindings >= 2.1.9 are required | [
"ZeroMQ",
"python",
"bindings",
">",
"=",
"2",
".",
"1",
".",
"9",
"are",
"required"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/verify.py#L40-L98 | train |
saltstack/salt | salt/utils/verify.py | lookup_family | def lookup_family(hostname):
'''
Lookup a hostname and determine its address family. The first address returned
will be AF_INET6 if the system is IPv6-enabled, and AF_INET otherwise.
'''
# If lookups fail, fall back to AF_INET sockets (and v4 addresses).
fallback = socket.AF_INET
try:
hostnames = socket.getaddrinfo(
hostname or None, None, socket.AF_UNSPEC, socket.SOCK_STREAM
)
if not hostnames:
return fallback
h = hostnames[0]
return h[0]
except socket.gaierror:
return fallback | python | def lookup_family(hostname):
'''
Lookup a hostname and determine its address family. The first address returned
will be AF_INET6 if the system is IPv6-enabled, and AF_INET otherwise.
'''
# If lookups fail, fall back to AF_INET sockets (and v4 addresses).
fallback = socket.AF_INET
try:
hostnames = socket.getaddrinfo(
hostname or None, None, socket.AF_UNSPEC, socket.SOCK_STREAM
)
if not hostnames:
return fallback
h = hostnames[0]
return h[0]
except socket.gaierror:
return fallback | [
"def",
"lookup_family",
"(",
"hostname",
")",
":",
"# If lookups fail, fall back to AF_INET sockets (and v4 addresses).",
"fallback",
"=",
"socket",
".",
"AF_INET",
"try",
":",
"hostnames",
"=",
"socket",
".",
"getaddrinfo",
"(",
"hostname",
"or",
"None",
",",
"None",... | Lookup a hostname and determine its address family. The first address returned
will be AF_INET6 if the system is IPv6-enabled, and AF_INET otherwise. | [
"Lookup",
"a",
"hostname",
"and",
"determine",
"its",
"address",
"family",
".",
"The",
"first",
"address",
"returned",
"will",
"be",
"AF_INET6",
"if",
"the",
"system",
"is",
"IPv6",
"-",
"enabled",
"and",
"AF_INET",
"otherwise",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/verify.py#L101-L117 | train |
saltstack/salt | salt/utils/verify.py | verify_socket | def verify_socket(interface, pub_port, ret_port):
'''
Attempt to bind to the sockets to verify that they are available
'''
addr_family = lookup_family(interface)
for port in pub_port, ret_port:
sock = socket.socket(addr_family, socket.SOCK_STREAM)
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((interface, int(port)))
except Exception as exc:
msg = 'Unable to bind socket {0}:{1}'.format(interface, port)
if exc.args:
msg = '{0}, error: {1}'.format(msg, str(exc))
else:
msg = '{0}, this might not be a problem.'.format(msg)
msg += '; Is there another salt-master running?'
if is_console_configured():
log.warning(msg)
else:
sys.stderr.write('WARNING: {0}\n'.format(msg))
return False
finally:
sock.close()
return True | python | def verify_socket(interface, pub_port, ret_port):
'''
Attempt to bind to the sockets to verify that they are available
'''
addr_family = lookup_family(interface)
for port in pub_port, ret_port:
sock = socket.socket(addr_family, socket.SOCK_STREAM)
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((interface, int(port)))
except Exception as exc:
msg = 'Unable to bind socket {0}:{1}'.format(interface, port)
if exc.args:
msg = '{0}, error: {1}'.format(msg, str(exc))
else:
msg = '{0}, this might not be a problem.'.format(msg)
msg += '; Is there another salt-master running?'
if is_console_configured():
log.warning(msg)
else:
sys.stderr.write('WARNING: {0}\n'.format(msg))
return False
finally:
sock.close()
return True | [
"def",
"verify_socket",
"(",
"interface",
",",
"pub_port",
",",
"ret_port",
")",
":",
"addr_family",
"=",
"lookup_family",
"(",
"interface",
")",
"for",
"port",
"in",
"pub_port",
",",
"ret_port",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"addr_family",... | Attempt to bind to the sockets to verify that they are available | [
"Attempt",
"to",
"bind",
"to",
"the",
"sockets",
"to",
"verify",
"that",
"they",
"are",
"available"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/verify.py#L120-L146 | train |
saltstack/salt | salt/utils/verify.py | verify_files | def verify_files(files, user):
'''
Verify that the named files exist and are owned by the named user
'''
if salt.utils.platform.is_windows():
return True
import pwd # after confirming not running Windows
try:
pwnam = pwd.getpwnam(user)
uid = pwnam[2]
except KeyError:
err = ('Failed to prepare the Salt environment for user '
'{0}. The user is not available.\n').format(user)
sys.stderr.write(err)
sys.exit(salt.defaults.exitcodes.EX_NOUSER)
for fn_ in files:
dirname = os.path.dirname(fn_)
try:
if dirname:
try:
os.makedirs(dirname)
except OSError as err:
if err.errno != errno.EEXIST:
raise
if not os.path.isfile(fn_):
with salt.utils.files.fopen(fn_, 'w'):
pass
except IOError as err:
if os.path.isfile(dirname):
msg = 'Failed to create path {0}, is {1} a file?'.format(fn_, dirname)
raise SaltSystemExit(msg=msg)
if err.errno != errno.EACCES:
raise
msg = 'No permissions to access "{0}", are you running as the correct user?'.format(fn_)
raise SaltSystemExit(msg=msg)
except OSError as err:
msg = 'Failed to create path "{0}" - {1}'.format(fn_, err)
raise SaltSystemExit(msg=msg)
stats = os.stat(fn_)
if uid != stats.st_uid:
try:
os.chown(fn_, uid, -1)
except OSError:
pass
return True | python | def verify_files(files, user):
'''
Verify that the named files exist and are owned by the named user
'''
if salt.utils.platform.is_windows():
return True
import pwd # after confirming not running Windows
try:
pwnam = pwd.getpwnam(user)
uid = pwnam[2]
except KeyError:
err = ('Failed to prepare the Salt environment for user '
'{0}. The user is not available.\n').format(user)
sys.stderr.write(err)
sys.exit(salt.defaults.exitcodes.EX_NOUSER)
for fn_ in files:
dirname = os.path.dirname(fn_)
try:
if dirname:
try:
os.makedirs(dirname)
except OSError as err:
if err.errno != errno.EEXIST:
raise
if not os.path.isfile(fn_):
with salt.utils.files.fopen(fn_, 'w'):
pass
except IOError as err:
if os.path.isfile(dirname):
msg = 'Failed to create path {0}, is {1} a file?'.format(fn_, dirname)
raise SaltSystemExit(msg=msg)
if err.errno != errno.EACCES:
raise
msg = 'No permissions to access "{0}", are you running as the correct user?'.format(fn_)
raise SaltSystemExit(msg=msg)
except OSError as err:
msg = 'Failed to create path "{0}" - {1}'.format(fn_, err)
raise SaltSystemExit(msg=msg)
stats = os.stat(fn_)
if uid != stats.st_uid:
try:
os.chown(fn_, uid, -1)
except OSError:
pass
return True | [
"def",
"verify_files",
"(",
"files",
",",
"user",
")",
":",
"if",
"salt",
".",
"utils",
".",
"platform",
".",
"is_windows",
"(",
")",
":",
"return",
"True",
"import",
"pwd",
"# after confirming not running Windows",
"try",
":",
"pwnam",
"=",
"pwd",
".",
"g... | Verify that the named files exist and are owned by the named user | [
"Verify",
"that",
"the",
"named",
"files",
"exist",
"and",
"are",
"owned",
"by",
"the",
"named",
"user"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/verify.py#L149-L197 | train |
saltstack/salt | salt/utils/verify.py | verify_env | def verify_env(
dirs,
user,
permissive=False,
pki_dir='',
skip_extra=False,
root_dir=ROOT_DIR):
'''
Verify that the named directories are in place and that the environment
can shake the salt
'''
if salt.utils.platform.is_windows():
return win_verify_env(root_dir,
dirs,
permissive=permissive,
skip_extra=skip_extra)
import pwd # after confirming not running Windows
try:
pwnam = pwd.getpwnam(user)
uid = pwnam[2]
gid = pwnam[3]
groups = salt.utils.user.get_gid_list(user, include_default=False)
except KeyError:
err = ('Failed to prepare the Salt environment for user '
'{0}. The user is not available.\n').format(user)
sys.stderr.write(err)
sys.exit(salt.defaults.exitcodes.EX_NOUSER)
for dir_ in dirs:
if not dir_:
continue
if not os.path.isdir(dir_):
try:
with salt.utils.files.set_umask(0o022):
os.makedirs(dir_)
# If starting the process as root, chown the new dirs
if os.getuid() == 0:
os.chown(dir_, uid, gid)
except OSError as err:
msg = 'Failed to create directory path "{0}" - {1}\n'
sys.stderr.write(msg.format(dir_, err))
sys.exit(err.errno)
mode = os.stat(dir_)
# If starting the process as root, chown the new dirs
if os.getuid() == 0:
fmode = os.stat(dir_)
if fmode.st_uid != uid or fmode.st_gid != gid:
if permissive and fmode.st_gid in groups:
# Allow the directory to be owned by any group root
# belongs to if we say it's ok to be permissive
pass
else:
# chown the file for the new user
os.chown(dir_, uid, gid)
for subdir in [a for a in os.listdir(dir_) if 'jobs' not in a]:
fsubdir = os.path.join(dir_, subdir)
if '{0}jobs'.format(os.path.sep) in fsubdir:
continue
for root, dirs, files in salt.utils.path.os_walk(fsubdir):
for name in files:
if name.startswith('.'):
continue
path = os.path.join(root, name)
try:
fmode = os.stat(path)
except (IOError, OSError):
pass
if fmode.st_uid != uid or fmode.st_gid != gid:
if permissive and fmode.st_gid in groups:
pass
else:
# chown the file for the new user
os.chown(path, uid, gid)
for name in dirs:
path = os.path.join(root, name)
fmode = os.stat(path)
if fmode.st_uid != uid or fmode.st_gid != gid:
if permissive and fmode.st_gid in groups:
pass
else:
# chown the file for the new user
os.chown(path, uid, gid)
# Allow the pki dir to be 700 or 750, but nothing else.
# This prevents other users from writing out keys, while
# allowing the use-case of 3rd-party software (like django)
# to read in what it needs to integrate.
#
# If the permissions aren't correct, default to the more secure 700.
# If acls are enabled, the pki_dir needs to remain readable, this
# is still secure because the private keys are still only readable
# by the user running the master
if dir_ == pki_dir:
smode = stat.S_IMODE(mode.st_mode)
if smode != 448 and smode != 488:
if os.access(dir_, os.W_OK):
os.chmod(dir_, 448)
else:
msg = 'Unable to securely set the permissions of "{0}".'
msg = msg.format(dir_)
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write("CRITICAL: {0}\n".format(msg))
if skip_extra is False:
# Run the extra verification checks
zmq_version() | python | def verify_env(
dirs,
user,
permissive=False,
pki_dir='',
skip_extra=False,
root_dir=ROOT_DIR):
'''
Verify that the named directories are in place and that the environment
can shake the salt
'''
if salt.utils.platform.is_windows():
return win_verify_env(root_dir,
dirs,
permissive=permissive,
skip_extra=skip_extra)
import pwd # after confirming not running Windows
try:
pwnam = pwd.getpwnam(user)
uid = pwnam[2]
gid = pwnam[3]
groups = salt.utils.user.get_gid_list(user, include_default=False)
except KeyError:
err = ('Failed to prepare the Salt environment for user '
'{0}. The user is not available.\n').format(user)
sys.stderr.write(err)
sys.exit(salt.defaults.exitcodes.EX_NOUSER)
for dir_ in dirs:
if not dir_:
continue
if not os.path.isdir(dir_):
try:
with salt.utils.files.set_umask(0o022):
os.makedirs(dir_)
# If starting the process as root, chown the new dirs
if os.getuid() == 0:
os.chown(dir_, uid, gid)
except OSError as err:
msg = 'Failed to create directory path "{0}" - {1}\n'
sys.stderr.write(msg.format(dir_, err))
sys.exit(err.errno)
mode = os.stat(dir_)
# If starting the process as root, chown the new dirs
if os.getuid() == 0:
fmode = os.stat(dir_)
if fmode.st_uid != uid or fmode.st_gid != gid:
if permissive and fmode.st_gid in groups:
# Allow the directory to be owned by any group root
# belongs to if we say it's ok to be permissive
pass
else:
# chown the file for the new user
os.chown(dir_, uid, gid)
for subdir in [a for a in os.listdir(dir_) if 'jobs' not in a]:
fsubdir = os.path.join(dir_, subdir)
if '{0}jobs'.format(os.path.sep) in fsubdir:
continue
for root, dirs, files in salt.utils.path.os_walk(fsubdir):
for name in files:
if name.startswith('.'):
continue
path = os.path.join(root, name)
try:
fmode = os.stat(path)
except (IOError, OSError):
pass
if fmode.st_uid != uid or fmode.st_gid != gid:
if permissive and fmode.st_gid in groups:
pass
else:
# chown the file for the new user
os.chown(path, uid, gid)
for name in dirs:
path = os.path.join(root, name)
fmode = os.stat(path)
if fmode.st_uid != uid or fmode.st_gid != gid:
if permissive and fmode.st_gid in groups:
pass
else:
# chown the file for the new user
os.chown(path, uid, gid)
# Allow the pki dir to be 700 or 750, but nothing else.
# This prevents other users from writing out keys, while
# allowing the use-case of 3rd-party software (like django)
# to read in what it needs to integrate.
#
# If the permissions aren't correct, default to the more secure 700.
# If acls are enabled, the pki_dir needs to remain readable, this
# is still secure because the private keys are still only readable
# by the user running the master
if dir_ == pki_dir:
smode = stat.S_IMODE(mode.st_mode)
if smode != 448 and smode != 488:
if os.access(dir_, os.W_OK):
os.chmod(dir_, 448)
else:
msg = 'Unable to securely set the permissions of "{0}".'
msg = msg.format(dir_)
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write("CRITICAL: {0}\n".format(msg))
if skip_extra is False:
# Run the extra verification checks
zmq_version() | [
"def",
"verify_env",
"(",
"dirs",
",",
"user",
",",
"permissive",
"=",
"False",
",",
"pki_dir",
"=",
"''",
",",
"skip_extra",
"=",
"False",
",",
"root_dir",
"=",
"ROOT_DIR",
")",
":",
"if",
"salt",
".",
"utils",
".",
"platform",
".",
"is_windows",
"(",... | Verify that the named directories are in place and that the environment
can shake the salt | [
"Verify",
"that",
"the",
"named",
"directories",
"are",
"in",
"place",
"and",
"that",
"the",
"environment",
"can",
"shake",
"the",
"salt"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/verify.py#L200-L307 | train |
saltstack/salt | salt/utils/verify.py | check_user | def check_user(user):
'''
Check user and assign process uid/gid.
'''
if salt.utils.platform.is_windows():
return True
if user == salt.utils.user.get_user():
return True
import pwd # after confirming not running Windows
try:
pwuser = pwd.getpwnam(user)
try:
if hasattr(os, 'initgroups'):
os.initgroups(user, pwuser.pw_gid) # pylint: disable=minimum-python-version
else:
os.setgroups(salt.utils.user.get_gid_list(user, include_default=False))
os.setgid(pwuser.pw_gid)
os.setuid(pwuser.pw_uid)
# We could just reset the whole environment but let's just override
# the variables we can get from pwuser
if 'HOME' in os.environ:
os.environ['HOME'] = pwuser.pw_dir
if 'SHELL' in os.environ:
os.environ['SHELL'] = pwuser.pw_shell
for envvar in ('USER', 'LOGNAME'):
if envvar in os.environ:
os.environ[envvar] = pwuser.pw_name
except OSError:
msg = 'Salt configured to run as user "{0}" but unable to switch.'
msg = msg.format(user)
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write("CRITICAL: {0}\n".format(msg))
return False
except KeyError:
msg = 'User not found: "{0}"'.format(user)
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write("CRITICAL: {0}\n".format(msg))
return False
return True | python | def check_user(user):
'''
Check user and assign process uid/gid.
'''
if salt.utils.platform.is_windows():
return True
if user == salt.utils.user.get_user():
return True
import pwd # after confirming not running Windows
try:
pwuser = pwd.getpwnam(user)
try:
if hasattr(os, 'initgroups'):
os.initgroups(user, pwuser.pw_gid) # pylint: disable=minimum-python-version
else:
os.setgroups(salt.utils.user.get_gid_list(user, include_default=False))
os.setgid(pwuser.pw_gid)
os.setuid(pwuser.pw_uid)
# We could just reset the whole environment but let's just override
# the variables we can get from pwuser
if 'HOME' in os.environ:
os.environ['HOME'] = pwuser.pw_dir
if 'SHELL' in os.environ:
os.environ['SHELL'] = pwuser.pw_shell
for envvar in ('USER', 'LOGNAME'):
if envvar in os.environ:
os.environ[envvar] = pwuser.pw_name
except OSError:
msg = 'Salt configured to run as user "{0}" but unable to switch.'
msg = msg.format(user)
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write("CRITICAL: {0}\n".format(msg))
return False
except KeyError:
msg = 'User not found: "{0}"'.format(user)
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write("CRITICAL: {0}\n".format(msg))
return False
return True | [
"def",
"check_user",
"(",
"user",
")",
":",
"if",
"salt",
".",
"utils",
".",
"platform",
".",
"is_windows",
"(",
")",
":",
"return",
"True",
"if",
"user",
"==",
"salt",
".",
"utils",
".",
"user",
".",
"get_user",
"(",
")",
":",
"return",
"True",
"i... | Check user and assign process uid/gid. | [
"Check",
"user",
"and",
"assign",
"process",
"uid",
"/",
"gid",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/verify.py#L310-L356 | train |
saltstack/salt | salt/utils/verify.py | list_path_traversal | def list_path_traversal(path):
'''
Returns a full list of directories leading up to, and including, a path.
So list_path_traversal('/path/to/salt') would return:
['/', '/path', '/path/to', '/path/to/salt']
in that order.
This routine has been tested on Windows systems as well.
list_path_traversal('c:\\path\\to\\salt') on Windows would return:
['c:\\', 'c:\\path', 'c:\\path\\to', 'c:\\path\\to\\salt']
'''
out = [path]
(head, tail) = os.path.split(path)
if tail == '':
# paths with trailing separators will return an empty string
out = [head]
(head, tail) = os.path.split(head)
while head != out[0]:
# loop until head is the same two consecutive times
out.insert(0, head)
(head, tail) = os.path.split(head)
return out | python | def list_path_traversal(path):
'''
Returns a full list of directories leading up to, and including, a path.
So list_path_traversal('/path/to/salt') would return:
['/', '/path', '/path/to', '/path/to/salt']
in that order.
This routine has been tested on Windows systems as well.
list_path_traversal('c:\\path\\to\\salt') on Windows would return:
['c:\\', 'c:\\path', 'c:\\path\\to', 'c:\\path\\to\\salt']
'''
out = [path]
(head, tail) = os.path.split(path)
if tail == '':
# paths with trailing separators will return an empty string
out = [head]
(head, tail) = os.path.split(head)
while head != out[0]:
# loop until head is the same two consecutive times
out.insert(0, head)
(head, tail) = os.path.split(head)
return out | [
"def",
"list_path_traversal",
"(",
"path",
")",
":",
"out",
"=",
"[",
"path",
"]",
"(",
"head",
",",
"tail",
")",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"if",
"tail",
"==",
"''",
":",
"# paths with trailing separators will return an empty ... | Returns a full list of directories leading up to, and including, a path.
So list_path_traversal('/path/to/salt') would return:
['/', '/path', '/path/to', '/path/to/salt']
in that order.
This routine has been tested on Windows systems as well.
list_path_traversal('c:\\path\\to\\salt') on Windows would return:
['c:\\', 'c:\\path', 'c:\\path\\to', 'c:\\path\\to\\salt'] | [
"Returns",
"a",
"full",
"list",
"of",
"directories",
"leading",
"up",
"to",
"and",
"including",
"a",
"path",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/verify.py#L359-L381 | train |
saltstack/salt | salt/utils/verify.py | check_path_traversal | def check_path_traversal(path, user='root', skip_perm_errors=False):
'''
Walk from the root up to a directory and verify that the current
user has access to read each directory. This is used for making
sure a user can read all parent directories of the minion's key
before trying to go and generate a new key and raising an IOError
'''
for tpath in list_path_traversal(path):
if not os.access(tpath, os.R_OK):
msg = 'Could not access {0}.'.format(tpath)
if not os.path.exists(tpath):
msg += ' Path does not exist.'
else:
current_user = salt.utils.user.get_user()
# Make the error message more intelligent based on how
# the user invokes salt-call or whatever other script.
if user != current_user:
msg += ' Try running as user {0}.'.format(user)
else:
msg += ' Please give {0} read permissions.'.format(user)
# We don't need to bail on config file permission errors
# if the CLI
# process is run with the -a flag
if skip_perm_errors:
return
# Propagate this exception up so there isn't a sys.exit()
# in the middle of code that could be imported elsewhere.
raise SaltClientError(msg) | python | def check_path_traversal(path, user='root', skip_perm_errors=False):
'''
Walk from the root up to a directory and verify that the current
user has access to read each directory. This is used for making
sure a user can read all parent directories of the minion's key
before trying to go and generate a new key and raising an IOError
'''
for tpath in list_path_traversal(path):
if not os.access(tpath, os.R_OK):
msg = 'Could not access {0}.'.format(tpath)
if not os.path.exists(tpath):
msg += ' Path does not exist.'
else:
current_user = salt.utils.user.get_user()
# Make the error message more intelligent based on how
# the user invokes salt-call or whatever other script.
if user != current_user:
msg += ' Try running as user {0}.'.format(user)
else:
msg += ' Please give {0} read permissions.'.format(user)
# We don't need to bail on config file permission errors
# if the CLI
# process is run with the -a flag
if skip_perm_errors:
return
# Propagate this exception up so there isn't a sys.exit()
# in the middle of code that could be imported elsewhere.
raise SaltClientError(msg) | [
"def",
"check_path_traversal",
"(",
"path",
",",
"user",
"=",
"'root'",
",",
"skip_perm_errors",
"=",
"False",
")",
":",
"for",
"tpath",
"in",
"list_path_traversal",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"access",
"(",
"tpath",
",",
"os",
".",
... | Walk from the root up to a directory and verify that the current
user has access to read each directory. This is used for making
sure a user can read all parent directories of the minion's key
before trying to go and generate a new key and raising an IOError | [
"Walk",
"from",
"the",
"root",
"up",
"to",
"a",
"directory",
"and",
"verify",
"that",
"the",
"current",
"user",
"has",
"access",
"to",
"read",
"each",
"directory",
".",
"This",
"is",
"used",
"for",
"making",
"sure",
"a",
"user",
"can",
"read",
"all",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/verify.py#L384-L412 | train |
saltstack/salt | salt/utils/verify.py | check_max_open_files | def check_max_open_files(opts):
'''
Check the number of max allowed open files and adjust if needed
'''
mof_c = opts.get('max_open_files', 100000)
if sys.platform.startswith('win'):
# Check the Windows API for more detail on this
# http://msdn.microsoft.com/en-us/library/xt874334(v=vs.71).aspx
# and the python binding http://timgolden.me.uk/pywin32-docs/win32file.html
mof_s = mof_h = win32file._getmaxstdio()
else:
mof_s, mof_h = resource.getrlimit(resource.RLIMIT_NOFILE)
accepted_keys_dir = os.path.join(opts.get('pki_dir'), 'minions')
accepted_count = len(os.listdir(accepted_keys_dir))
log.debug(
'This salt-master instance has accepted %s minion keys.',
accepted_count
)
level = logging.INFO
if (accepted_count * 4) <= mof_s:
# We check for the soft value of max open files here because that's the
# value the user chose to raise to.
#
# The number of accepted keys multiplied by four(4) is lower than the
# soft value, everything should be OK
return
msg = (
'The number of accepted minion keys({0}) should be lower than 1/4 '
'of the max open files soft setting({1}). '.format(
accepted_count, mof_s
)
)
if accepted_count >= mof_s:
# This should never occur, it might have already crashed
msg += 'salt-master will crash pretty soon! '
level = logging.CRITICAL
elif (accepted_count * 2) >= mof_s:
# This is way too low, CRITICAL
level = logging.CRITICAL
elif (accepted_count * 3) >= mof_s:
level = logging.WARNING
# The accepted count is more than 3 time, WARN
elif (accepted_count * 4) >= mof_s:
level = logging.INFO
if mof_c < mof_h:
msg += ('According to the system\'s hard limit, there\'s still a '
'margin of {0} to raise the salt\'s max_open_files '
'setting. ').format(mof_h - mof_c)
msg += 'Please consider raising this value.'
log.log(level=level, msg=msg) | python | def check_max_open_files(opts):
'''
Check the number of max allowed open files and adjust if needed
'''
mof_c = opts.get('max_open_files', 100000)
if sys.platform.startswith('win'):
# Check the Windows API for more detail on this
# http://msdn.microsoft.com/en-us/library/xt874334(v=vs.71).aspx
# and the python binding http://timgolden.me.uk/pywin32-docs/win32file.html
mof_s = mof_h = win32file._getmaxstdio()
else:
mof_s, mof_h = resource.getrlimit(resource.RLIMIT_NOFILE)
accepted_keys_dir = os.path.join(opts.get('pki_dir'), 'minions')
accepted_count = len(os.listdir(accepted_keys_dir))
log.debug(
'This salt-master instance has accepted %s minion keys.',
accepted_count
)
level = logging.INFO
if (accepted_count * 4) <= mof_s:
# We check for the soft value of max open files here because that's the
# value the user chose to raise to.
#
# The number of accepted keys multiplied by four(4) is lower than the
# soft value, everything should be OK
return
msg = (
'The number of accepted minion keys({0}) should be lower than 1/4 '
'of the max open files soft setting({1}). '.format(
accepted_count, mof_s
)
)
if accepted_count >= mof_s:
# This should never occur, it might have already crashed
msg += 'salt-master will crash pretty soon! '
level = logging.CRITICAL
elif (accepted_count * 2) >= mof_s:
# This is way too low, CRITICAL
level = logging.CRITICAL
elif (accepted_count * 3) >= mof_s:
level = logging.WARNING
# The accepted count is more than 3 time, WARN
elif (accepted_count * 4) >= mof_s:
level = logging.INFO
if mof_c < mof_h:
msg += ('According to the system\'s hard limit, there\'s still a '
'margin of {0} to raise the salt\'s max_open_files '
'setting. ').format(mof_h - mof_c)
msg += 'Please consider raising this value.'
log.log(level=level, msg=msg) | [
"def",
"check_max_open_files",
"(",
"opts",
")",
":",
"mof_c",
"=",
"opts",
".",
"get",
"(",
"'max_open_files'",
",",
"100000",
")",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'win'",
")",
":",
"# Check the Windows API for more detail on this",
"# ht... | Check the number of max allowed open files and adjust if needed | [
"Check",
"the",
"number",
"of",
"max",
"allowed",
"open",
"files",
"and",
"adjust",
"if",
"needed"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/verify.py#L415-L472 | train |
saltstack/salt | salt/utils/verify.py | clean_path | def clean_path(root, path, subdir=False):
'''
Accepts the root the path needs to be under and verifies that the path is
under said root. Pass in subdir=True if the path can result in a
subdirectory of the root instead of having to reside directly in the root
'''
if not os.path.isabs(root):
return ''
if not os.path.isabs(path):
path = os.path.join(root, path)
path = os.path.normpath(path)
if subdir:
if path.startswith(root):
return path
else:
if os.path.dirname(path) == os.path.normpath(root):
return path
return '' | python | def clean_path(root, path, subdir=False):
'''
Accepts the root the path needs to be under and verifies that the path is
under said root. Pass in subdir=True if the path can result in a
subdirectory of the root instead of having to reside directly in the root
'''
if not os.path.isabs(root):
return ''
if not os.path.isabs(path):
path = os.path.join(root, path)
path = os.path.normpath(path)
if subdir:
if path.startswith(root):
return path
else:
if os.path.dirname(path) == os.path.normpath(root):
return path
return '' | [
"def",
"clean_path",
"(",
"root",
",",
"path",
",",
"subdir",
"=",
"False",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"root",
")",
":",
"return",
"''",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
":",
"pat... | Accepts the root the path needs to be under and verifies that the path is
under said root. Pass in subdir=True if the path can result in a
subdirectory of the root instead of having to reside directly in the root | [
"Accepts",
"the",
"root",
"the",
"path",
"needs",
"to",
"be",
"under",
"and",
"verifies",
"that",
"the",
"path",
"is",
"under",
"said",
"root",
".",
"Pass",
"in",
"subdir",
"=",
"True",
"if",
"the",
"path",
"can",
"result",
"in",
"a",
"subdirectory",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/verify.py#L475-L492 | train |
saltstack/salt | salt/utils/verify.py | valid_id | def valid_id(opts, id_):
'''
Returns if the passed id is valid
'''
try:
if any(x in id_ for x in ('/', '\\', str('\0'))):
return False
return bool(clean_path(opts['pki_dir'], id_))
except (AttributeError, KeyError, TypeError, UnicodeDecodeError):
return False | python | def valid_id(opts, id_):
'''
Returns if the passed id is valid
'''
try:
if any(x in id_ for x in ('/', '\\', str('\0'))):
return False
return bool(clean_path(opts['pki_dir'], id_))
except (AttributeError, KeyError, TypeError, UnicodeDecodeError):
return False | [
"def",
"valid_id",
"(",
"opts",
",",
"id_",
")",
":",
"try",
":",
"if",
"any",
"(",
"x",
"in",
"id_",
"for",
"x",
"in",
"(",
"'/'",
",",
"'\\\\'",
",",
"str",
"(",
"'\\0'",
")",
")",
")",
":",
"return",
"False",
"return",
"bool",
"(",
"clean_pa... | Returns if the passed id is valid | [
"Returns",
"if",
"the",
"passed",
"id",
"is",
"valid"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/verify.py#L495-L504 | train |
saltstack/salt | salt/utils/verify.py | safe_py_code | def safe_py_code(code):
'''
Check a string to see if it has any potentially unsafe routines which
could be executed via python, this routine is used to improve the
safety of modules suct as virtualenv
'''
bads = (
'import',
';',
'subprocess',
'eval',
'open',
'file',
'exec',
'input')
for bad in bads:
if code.count(bad):
return False
return True | python | def safe_py_code(code):
'''
Check a string to see if it has any potentially unsafe routines which
could be executed via python, this routine is used to improve the
safety of modules suct as virtualenv
'''
bads = (
'import',
';',
'subprocess',
'eval',
'open',
'file',
'exec',
'input')
for bad in bads:
if code.count(bad):
return False
return True | [
"def",
"safe_py_code",
"(",
"code",
")",
":",
"bads",
"=",
"(",
"'import'",
",",
"';'",
",",
"'subprocess'",
",",
"'eval'",
",",
"'open'",
",",
"'file'",
",",
"'exec'",
",",
"'input'",
")",
"for",
"bad",
"in",
"bads",
":",
"if",
"code",
".",
"count",... | Check a string to see if it has any potentially unsafe routines which
could be executed via python, this routine is used to improve the
safety of modules suct as virtualenv | [
"Check",
"a",
"string",
"to",
"see",
"if",
"it",
"has",
"any",
"potentially",
"unsafe",
"routines",
"which",
"could",
"be",
"executed",
"via",
"python",
"this",
"routine",
"is",
"used",
"to",
"improve",
"the",
"safety",
"of",
"modules",
"suct",
"as",
"virt... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/verify.py#L507-L525 | train |
saltstack/salt | salt/utils/verify.py | verify_log | def verify_log(opts):
'''
If an insecre logging configuration is found, show a warning
'''
level = LOG_LEVELS.get(str(opts.get('log_level')).lower(), logging.NOTSET)
if level < logging.INFO:
log.warning('Insecure logging configuration detected! Sensitive data may be logged.') | python | def verify_log(opts):
'''
If an insecre logging configuration is found, show a warning
'''
level = LOG_LEVELS.get(str(opts.get('log_level')).lower(), logging.NOTSET)
if level < logging.INFO:
log.warning('Insecure logging configuration detected! Sensitive data may be logged.') | [
"def",
"verify_log",
"(",
"opts",
")",
":",
"level",
"=",
"LOG_LEVELS",
".",
"get",
"(",
"str",
"(",
"opts",
".",
"get",
"(",
"'log_level'",
")",
")",
".",
"lower",
"(",
")",
",",
"logging",
".",
"NOTSET",
")",
"if",
"level",
"<",
"logging",
".",
... | If an insecre logging configuration is found, show a warning | [
"If",
"an",
"insecre",
"logging",
"configuration",
"is",
"found",
"show",
"a",
"warning"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/verify.py#L528-L535 | train |
saltstack/salt | salt/utils/verify.py | win_verify_env | def win_verify_env(
path,
dirs,
permissive=False,
pki_dir='',
skip_extra=False):
'''
Verify that the named directories are in place and that the environment
can shake the salt
'''
import salt.utils.win_functions
import salt.utils.win_dacl
import salt.utils.path
# Make sure the file_roots is not set to something unsafe since permissions
# on that directory are reset
# `salt.utils.path.safe_path` will consider anything inside `C:\Windows` to
# be unsafe. In some instances the test suite uses
# `C:\Windows\Temp\salt-tests-tmpdir\rootdir` as the file_roots. So, we need
# to consider anything in `C:\Windows\Temp` to be safe
system_root = os.environ.get('SystemRoot', r'C:\Windows')
allow_path = '\\'.join([system_root, 'TEMP'])
if not salt.utils.path.safe_path(path=path, allow_path=allow_path):
raise CommandExecutionError(
'`file_roots` set to a possibly unsafe location: {0}'.format(path)
)
# Create the root path directory if missing
if not os.path.isdir(path):
os.makedirs(path)
# Set permissions to the root path directory
current_user = salt.utils.win_functions.get_current_user()
if salt.utils.win_functions.is_admin(current_user):
try:
# Make the Administrators group owner
# Use the SID to be locale agnostic
salt.utils.win_dacl.set_owner(path, 'S-1-5-32-544')
except CommandExecutionError:
msg = 'Unable to securely set the owner of "{0}".'.format(path)
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write("CRITICAL: {0}\n".format(msg))
if not permissive:
try:
# Get a clean dacl by not passing an obj_name
dacl = salt.utils.win_dacl.dacl()
# Add aces to the dacl, use the GUID (locale non-specific)
# Administrators Group
dacl.add_ace('S-1-5-32-544', 'grant', 'full_control',
'this_folder_subfolders_files')
# System
dacl.add_ace('S-1-5-18', 'grant', 'full_control',
'this_folder_subfolders_files')
# Owner
dacl.add_ace('S-1-3-4', 'grant', 'full_control',
'this_folder_subfolders_files')
# Save the dacl to the object
dacl.save(path, True)
except CommandExecutionError:
msg = 'Unable to securely set the permissions of ' \
'"{0}".'.format(path)
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write("CRITICAL: {0}\n".format(msg))
# Create the directories
for dir_ in dirs:
if not dir_:
continue
if not os.path.isdir(dir_):
try:
os.makedirs(dir_)
except OSError as err:
msg = 'Failed to create directory path "{0}" - {1}\n'
sys.stderr.write(msg.format(dir_, err))
sys.exit(err.errno)
# The PKI dir gets its own permissions
if dir_ == pki_dir:
try:
# Make Administrators group the owner
salt.utils.win_dacl.set_owner(path, 'S-1-5-32-544')
# Give Admins, System and Owner permissions
# Get a clean dacl by not passing an obj_name
dacl = salt.utils.win_dacl.dacl()
# Add aces to the dacl, use the GUID (locale non-specific)
# Administrators Group
dacl.add_ace('S-1-5-32-544', 'grant', 'full_control',
'this_folder_subfolders_files')
# System
dacl.add_ace('S-1-5-18', 'grant', 'full_control',
'this_folder_subfolders_files')
# Owner
dacl.add_ace('S-1-3-4', 'grant', 'full_control',
'this_folder_subfolders_files')
# Save the dacl to the object
dacl.save(dir_, True)
except CommandExecutionError:
msg = 'Unable to securely set the permissions of "{0}".'
msg = msg.format(dir_)
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write("CRITICAL: {0}\n".format(msg))
if skip_extra is False:
# Run the extra verification checks
zmq_version() | python | def win_verify_env(
path,
dirs,
permissive=False,
pki_dir='',
skip_extra=False):
'''
Verify that the named directories are in place and that the environment
can shake the salt
'''
import salt.utils.win_functions
import salt.utils.win_dacl
import salt.utils.path
# Make sure the file_roots is not set to something unsafe since permissions
# on that directory are reset
# `salt.utils.path.safe_path` will consider anything inside `C:\Windows` to
# be unsafe. In some instances the test suite uses
# `C:\Windows\Temp\salt-tests-tmpdir\rootdir` as the file_roots. So, we need
# to consider anything in `C:\Windows\Temp` to be safe
system_root = os.environ.get('SystemRoot', r'C:\Windows')
allow_path = '\\'.join([system_root, 'TEMP'])
if not salt.utils.path.safe_path(path=path, allow_path=allow_path):
raise CommandExecutionError(
'`file_roots` set to a possibly unsafe location: {0}'.format(path)
)
# Create the root path directory if missing
if not os.path.isdir(path):
os.makedirs(path)
# Set permissions to the root path directory
current_user = salt.utils.win_functions.get_current_user()
if salt.utils.win_functions.is_admin(current_user):
try:
# Make the Administrators group owner
# Use the SID to be locale agnostic
salt.utils.win_dacl.set_owner(path, 'S-1-5-32-544')
except CommandExecutionError:
msg = 'Unable to securely set the owner of "{0}".'.format(path)
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write("CRITICAL: {0}\n".format(msg))
if not permissive:
try:
# Get a clean dacl by not passing an obj_name
dacl = salt.utils.win_dacl.dacl()
# Add aces to the dacl, use the GUID (locale non-specific)
# Administrators Group
dacl.add_ace('S-1-5-32-544', 'grant', 'full_control',
'this_folder_subfolders_files')
# System
dacl.add_ace('S-1-5-18', 'grant', 'full_control',
'this_folder_subfolders_files')
# Owner
dacl.add_ace('S-1-3-4', 'grant', 'full_control',
'this_folder_subfolders_files')
# Save the dacl to the object
dacl.save(path, True)
except CommandExecutionError:
msg = 'Unable to securely set the permissions of ' \
'"{0}".'.format(path)
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write("CRITICAL: {0}\n".format(msg))
# Create the directories
for dir_ in dirs:
if not dir_:
continue
if not os.path.isdir(dir_):
try:
os.makedirs(dir_)
except OSError as err:
msg = 'Failed to create directory path "{0}" - {1}\n'
sys.stderr.write(msg.format(dir_, err))
sys.exit(err.errno)
# The PKI dir gets its own permissions
if dir_ == pki_dir:
try:
# Make Administrators group the owner
salt.utils.win_dacl.set_owner(path, 'S-1-5-32-544')
# Give Admins, System and Owner permissions
# Get a clean dacl by not passing an obj_name
dacl = salt.utils.win_dacl.dacl()
# Add aces to the dacl, use the GUID (locale non-specific)
# Administrators Group
dacl.add_ace('S-1-5-32-544', 'grant', 'full_control',
'this_folder_subfolders_files')
# System
dacl.add_ace('S-1-5-18', 'grant', 'full_control',
'this_folder_subfolders_files')
# Owner
dacl.add_ace('S-1-3-4', 'grant', 'full_control',
'this_folder_subfolders_files')
# Save the dacl to the object
dacl.save(dir_, True)
except CommandExecutionError:
msg = 'Unable to securely set the permissions of "{0}".'
msg = msg.format(dir_)
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write("CRITICAL: {0}\n".format(msg))
if skip_extra is False:
# Run the extra verification checks
zmq_version() | [
"def",
"win_verify_env",
"(",
"path",
",",
"dirs",
",",
"permissive",
"=",
"False",
",",
"pki_dir",
"=",
"''",
",",
"skip_extra",
"=",
"False",
")",
":",
"import",
"salt",
".",
"utils",
".",
"win_functions",
"import",
"salt",
".",
"utils",
".",
"win_dacl... | Verify that the named directories are in place and that the environment
can shake the salt | [
"Verify",
"that",
"the",
"named",
"directories",
"are",
"in",
"place",
"and",
"that",
"the",
"environment",
"can",
"shake",
"the",
"salt"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/verify.py#L538-L658 | train |
saltstack/salt | salt/modules/pacmanpkg.py | list_upgrades | def list_upgrades(refresh=False, root=None, **kwargs): # pylint: disable=W0613
'''
List all available package upgrades on this system
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
upgrades = {}
cmd = ['pacman', '-S', '-p', '-u', '--print-format', '%n %v']
if root is not None:
cmd.extend(('-r', root))
if refresh:
cmd.append('-y')
call = __salt__['cmd.run_all'](cmd,
python_shell=False,
output_loglevel='trace')
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
if comment:
comment = ': ' + comment
raise CommandExecutionError('Error listing upgrades' + comment)
else:
out = call['stdout']
for line in salt.utils.itertools.split(out, '\n'):
try:
pkgname, pkgver = line.split()
except ValueError:
continue
if pkgname.lower() == 'downloading' and '.db' in pkgver.lower():
# Antergos (and possibly other Arch derivatives) add lines when pkg
# metadata is being downloaded. Because these lines, when split,
# contain two columns (i.e. 'downloading community.db...'), we will
# skip this line to keep it from being interpreted as an upgrade.
continue
upgrades[pkgname] = pkgver
return upgrades | python | def list_upgrades(refresh=False, root=None, **kwargs): # pylint: disable=W0613
'''
List all available package upgrades on this system
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
upgrades = {}
cmd = ['pacman', '-S', '-p', '-u', '--print-format', '%n %v']
if root is not None:
cmd.extend(('-r', root))
if refresh:
cmd.append('-y')
call = __salt__['cmd.run_all'](cmd,
python_shell=False,
output_loglevel='trace')
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
if comment:
comment = ': ' + comment
raise CommandExecutionError('Error listing upgrades' + comment)
else:
out = call['stdout']
for line in salt.utils.itertools.split(out, '\n'):
try:
pkgname, pkgver = line.split()
except ValueError:
continue
if pkgname.lower() == 'downloading' and '.db' in pkgver.lower():
# Antergos (and possibly other Arch derivatives) add lines when pkg
# metadata is being downloaded. Because these lines, when split,
# contain two columns (i.e. 'downloading community.db...'), we will
# skip this line to keep it from being interpreted as an upgrade.
continue
upgrades[pkgname] = pkgver
return upgrades | [
"def",
"list_upgrades",
"(",
"refresh",
"=",
"False",
",",
"root",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=W0613",
"upgrades",
"=",
"{",
"}",
"cmd",
"=",
"[",
"'pacman'",
",",
"'-S'",
",",
"'-p'",
",",
"'-u'",
",",
"'--print-... | List all available package upgrades on this system
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades | [
"List",
"all",
"available",
"package",
"upgrades",
"on",
"this",
"system"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pacmanpkg.py#L127-L174 | train |
saltstack/salt | salt/modules/pacmanpkg.py | list_pkgs | def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed as a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
if 'pkg.list_pkgs' in __context__:
if versions_as_list:
return __context__['pkg.list_pkgs']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs'])
__salt__['pkg_resource.stringify'](ret)
return ret
cmd = ['pacman', '-Q']
if 'root' in kwargs:
cmd.extend(('-r', kwargs['root']))
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
if not line:
continue
try:
name, version_num = line.split()[0:2]
except ValueError:
log.error('Problem parsing pacman -Q: Unexpected formatting in '
'line: \'%s\'', line)
else:
__salt__['pkg_resource.add_pkg'](ret, name, version_num)
__salt__['pkg_resource.sort_pkglist'](ret)
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret | python | def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed as a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
if 'pkg.list_pkgs' in __context__:
if versions_as_list:
return __context__['pkg.list_pkgs']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs'])
__salt__['pkg_resource.stringify'](ret)
return ret
cmd = ['pacman', '-Q']
if 'root' in kwargs:
cmd.extend(('-r', kwargs['root']))
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
if not line:
continue
try:
name, version_num = line.split()[0:2]
except ValueError:
log.error('Problem parsing pacman -Q: Unexpected formatting in '
'line: \'%s\'', line)
else:
__salt__['pkg_resource.add_pkg'](ret, name, version_num)
__salt__['pkg_resource.sort_pkglist'](ret)
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret | [
"def",
"list_pkgs",
"(",
"versions_as_list",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"versions_as_list",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"is_true",
"(",
"versions_as_list",
")",
"# not yet implemented or not applicable",
"if",
"any",
"(",
... | List the packages currently installed as a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs | [
"List",
"the",
"packages",
"currently",
"installed",
"as",
"a",
"dict",
"::"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pacmanpkg.py#L193-L241 | train |
saltstack/salt | salt/modules/pacmanpkg.py | group_list | def group_list():
'''
.. versionadded:: 2016.11.0
Lists all groups known by pacman on this system
CLI Example:
.. code-block:: bash
salt '*' pkg.group_list
'''
ret = {'installed': [],
'partially_installed': [],
'available': []}
# find out what's available
cmd = ['pacman', '-Sgg']
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
available = {}
for line in salt.utils.itertools.split(out, '\n'):
if not line:
continue
try:
group, pkg = line.split()[0:2]
except ValueError:
log.error('Problem parsing pacman -Sgg: Unexpected formatting in '
'line: \'%s\'', line)
else:
available.setdefault(group, []).append(pkg)
# now get what's installed
cmd = ['pacman', '-Qg']
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
installed = {}
for line in salt.utils.itertools.split(out, '\n'):
if not line:
continue
try:
group, pkg = line.split()[0:2]
except ValueError:
log.error('Problem parsing pacman -Qg: Unexpected formatting in '
'line: \'%s\'', line)
else:
installed.setdefault(group, []).append(pkg)
# move installed and partially-installed items from available to appropriate other places
for group in installed:
if group not in available:
log.error(
'Pacman reports group %s installed, but it is not in the '
'available list (%s)!', group, available
)
continue
if len(installed[group]) == len(available[group]):
ret['installed'].append(group)
else:
ret['partially_installed'].append(group)
available.pop(group)
ret['installed'].sort()
ret['partially_installed'].sort()
# Now installed and partially installed are set, whatever is left is the available list.
# In Python 3, .keys() returns an iterable view instead of a list. sort() cannot be
# called on views. Use sorted() instead. Plus it's just as efficient as sort().
ret['available'] = sorted(available.keys())
return ret | python | def group_list():
'''
.. versionadded:: 2016.11.0
Lists all groups known by pacman on this system
CLI Example:
.. code-block:: bash
salt '*' pkg.group_list
'''
ret = {'installed': [],
'partially_installed': [],
'available': []}
# find out what's available
cmd = ['pacman', '-Sgg']
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
available = {}
for line in salt.utils.itertools.split(out, '\n'):
if not line:
continue
try:
group, pkg = line.split()[0:2]
except ValueError:
log.error('Problem parsing pacman -Sgg: Unexpected formatting in '
'line: \'%s\'', line)
else:
available.setdefault(group, []).append(pkg)
# now get what's installed
cmd = ['pacman', '-Qg']
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
installed = {}
for line in salt.utils.itertools.split(out, '\n'):
if not line:
continue
try:
group, pkg = line.split()[0:2]
except ValueError:
log.error('Problem parsing pacman -Qg: Unexpected formatting in '
'line: \'%s\'', line)
else:
installed.setdefault(group, []).append(pkg)
# move installed and partially-installed items from available to appropriate other places
for group in installed:
if group not in available:
log.error(
'Pacman reports group %s installed, but it is not in the '
'available list (%s)!', group, available
)
continue
if len(installed[group]) == len(available[group]):
ret['installed'].append(group)
else:
ret['partially_installed'].append(group)
available.pop(group)
ret['installed'].sort()
ret['partially_installed'].sort()
# Now installed and partially installed are set, whatever is left is the available list.
# In Python 3, .keys() returns an iterable view instead of a list. sort() cannot be
# called on views. Use sorted() instead. Plus it's just as efficient as sort().
ret['available'] = sorted(available.keys())
return ret | [
"def",
"group_list",
"(",
")",
":",
"ret",
"=",
"{",
"'installed'",
":",
"[",
"]",
",",
"'partially_installed'",
":",
"[",
"]",
",",
"'available'",
":",
"[",
"]",
"}",
"# find out what's available",
"cmd",
"=",
"[",
"'pacman'",
",",
"'-Sgg'",
"]",
"out",... | .. versionadded:: 2016.11.0
Lists all groups known by pacman on this system
CLI Example:
.. code-block:: bash
salt '*' pkg.group_list | [
"..",
"versionadded",
"::",
"2016",
".",
"11",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pacmanpkg.py#L244-L318 | train |
saltstack/salt | salt/modules/pacmanpkg.py | group_info | def group_info(name):
'''
.. versionadded:: 2016.11.0
Lists all packages in the specified group
CLI Example:
.. code-block:: bash
salt '*' pkg.group_info 'xorg'
'''
pkgtypes = ('mandatory', 'optional', 'default', 'conditional')
ret = {}
for pkgtype in pkgtypes:
ret[pkgtype] = set()
cmd = ['pacman', '-Sgg', name]
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
if not line:
continue
try:
pkg = line.split()[1]
except ValueError:
log.error('Problem parsing pacman -Sgg: Unexpected formatting in '
'line: \'%s\'', line)
else:
ret['default'].add(pkg)
for pkgtype in pkgtypes:
ret[pkgtype] = sorted(ret[pkgtype])
return ret | python | def group_info(name):
'''
.. versionadded:: 2016.11.0
Lists all packages in the specified group
CLI Example:
.. code-block:: bash
salt '*' pkg.group_info 'xorg'
'''
pkgtypes = ('mandatory', 'optional', 'default', 'conditional')
ret = {}
for pkgtype in pkgtypes:
ret[pkgtype] = set()
cmd = ['pacman', '-Sgg', name]
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
if not line:
continue
try:
pkg = line.split()[1]
except ValueError:
log.error('Problem parsing pacman -Sgg: Unexpected formatting in '
'line: \'%s\'', line)
else:
ret['default'].add(pkg)
for pkgtype in pkgtypes:
ret[pkgtype] = sorted(ret[pkgtype])
return ret | [
"def",
"group_info",
"(",
"name",
")",
":",
"pkgtypes",
"=",
"(",
"'mandatory'",
",",
"'optional'",
",",
"'default'",
",",
"'conditional'",
")",
"ret",
"=",
"{",
"}",
"for",
"pkgtype",
"in",
"pkgtypes",
":",
"ret",
"[",
"pkgtype",
"]",
"=",
"set",
"(",... | .. versionadded:: 2016.11.0
Lists all packages in the specified group
CLI Example:
.. code-block:: bash
salt '*' pkg.group_info 'xorg' | [
"..",
"versionadded",
"::",
"2016",
".",
"11",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pacmanpkg.py#L321-L356 | train |
saltstack/salt | salt/modules/pacmanpkg.py | group_diff | def group_diff(name):
'''
.. versionadded:: 2016.11.0
Lists which of a group's packages are installed and which are not
installed
Compatible with yumpkg.group_diff for easy support of state.pkg.group_installed
CLI Example:
.. code-block:: bash
salt '*' pkg.group_diff 'xorg'
'''
# Use a compatible structure with yum, so we can leverage the existing state.group_installed
# In pacmanworld, everything is the default, but nothing is mandatory
pkgtypes = ('mandatory', 'optional', 'default', 'conditional')
ret = {}
for pkgtype in pkgtypes:
ret[pkgtype] = {'installed': [], 'not installed': []}
# use indirect references to simplify unit testing
pkgs = __salt__['pkg.list_pkgs']()
group_pkgs = __salt__['pkg.group_info'](name)
for pkgtype in pkgtypes:
for member in group_pkgs.get(pkgtype, []):
if member in pkgs:
ret[pkgtype]['installed'].append(member)
else:
ret[pkgtype]['not installed'].append(member)
return ret | python | def group_diff(name):
'''
.. versionadded:: 2016.11.0
Lists which of a group's packages are installed and which are not
installed
Compatible with yumpkg.group_diff for easy support of state.pkg.group_installed
CLI Example:
.. code-block:: bash
salt '*' pkg.group_diff 'xorg'
'''
# Use a compatible structure with yum, so we can leverage the existing state.group_installed
# In pacmanworld, everything is the default, but nothing is mandatory
pkgtypes = ('mandatory', 'optional', 'default', 'conditional')
ret = {}
for pkgtype in pkgtypes:
ret[pkgtype] = {'installed': [], 'not installed': []}
# use indirect references to simplify unit testing
pkgs = __salt__['pkg.list_pkgs']()
group_pkgs = __salt__['pkg.group_info'](name)
for pkgtype in pkgtypes:
for member in group_pkgs.get(pkgtype, []):
if member in pkgs:
ret[pkgtype]['installed'].append(member)
else:
ret[pkgtype]['not installed'].append(member)
return ret | [
"def",
"group_diff",
"(",
"name",
")",
":",
"# Use a compatible structure with yum, so we can leverage the existing state.group_installed",
"# In pacmanworld, everything is the default, but nothing is mandatory",
"pkgtypes",
"=",
"(",
"'mandatory'",
",",
"'optional'",
",",
"'default'",... | .. versionadded:: 2016.11.0
Lists which of a group's packages are installed and which are not
installed
Compatible with yumpkg.group_diff for easy support of state.pkg.group_installed
CLI Example:
.. code-block:: bash
salt '*' pkg.group_diff 'xorg' | [
"..",
"versionadded",
"::",
"2016",
".",
"11",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pacmanpkg.py#L359-L393 | train |
saltstack/salt | salt/modules/pacmanpkg.py | refresh_db | def refresh_db(root=None, **kwargs):
'''
Just run a ``pacman -Sy``, return a dict::
{'<database name>': Bool}
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
cmd = ['pacman', '-Sy']
if root is not None:
cmd.extend(('-r', root))
ret = {}
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
env={'LANG': 'C'},
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += ': ' + call['stderr']
raise CommandExecutionError(
'Error refreshing package database' + comment
)
else:
out = call['stdout']
for line in salt.utils.itertools.split(out, '\n'):
if line.strip().startswith('::'):
continue
if not line:
continue
key = line.strip().split()[0]
if 'is up to date' in line:
ret[key] = False
elif 'downloading' in line:
key = line.strip().split()[1].split('.')[0]
ret[key] = True
return ret | python | def refresh_db(root=None, **kwargs):
'''
Just run a ``pacman -Sy``, return a dict::
{'<database name>': Bool}
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
cmd = ['pacman', '-Sy']
if root is not None:
cmd.extend(('-r', root))
ret = {}
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
env={'LANG': 'C'},
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += ': ' + call['stderr']
raise CommandExecutionError(
'Error refreshing package database' + comment
)
else:
out = call['stdout']
for line in salt.utils.itertools.split(out, '\n'):
if line.strip().startswith('::'):
continue
if not line:
continue
key = line.strip().split()[0]
if 'is up to date' in line:
ret[key] = False
elif 'downloading' in line:
key = line.strip().split()[1].split('.')[0]
ret[key] = True
return ret | [
"def",
"refresh_db",
"(",
"root",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Remove rtag file to keep multiple refreshes from happening in pkg states",
"salt",
".",
"utils",
".",
"pkg",
".",
"clear_rtag",
"(",
"__opts__",
")",
"cmd",
"=",
"[",
"'pacman'",
... | Just run a ``pacman -Sy``, return a dict::
{'<database name>': Bool}
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db | [
"Just",
"run",
"a",
"pacman",
"-",
"Sy",
"return",
"a",
"dict",
"::"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pacmanpkg.py#L396-L441 | train |
saltstack/salt | salt/modules/pacmanpkg.py | install | def install(name=None,
refresh=False,
sysupgrade=None,
pkgs=None,
sources=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any pacman commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install (``pacman -S``) the specified packag(s). Add ``refresh=True`` to
install with ``-y``, add ``sysupgrade=True`` to install with ``-u``.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
sysupgrade
Whether or not to upgrade the system packages before installing.
If refresh is set to ``True`` but sysupgrade is not specified, ``-u`` will be
applied
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install \
sources='[{"foo": "salt://foo.pkg.tar.xz"}, \
{"bar": "salt://bar.pkg.tar.xz"}]'
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
if 'root' in kwargs:
pkg_params['-r'] = kwargs['root']
cmd = []
if salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.append('pacman')
targets = []
errors = []
targets = []
if pkg_type == 'file':
cmd.extend(['-U', '--noprogressbar', '--noconfirm'])
cmd.extend(pkg_params)
elif pkg_type == 'repository':
cmd.append('-S')
if refresh is True:
cmd.append('-y')
if sysupgrade is True or (sysupgrade is None and refresh is True):
cmd.append('-u')
cmd.extend(['--noprogressbar', '--noconfirm', '--needed'])
wildcards = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
if '*' in verstr:
if prefix == '=':
wildcards.append((param, verstr))
else:
errors.append(
'Invalid wildcard for {0}{1}{2}'.format(
param, prefix, verstr
)
)
continue
targets.append('{0}{1}{2}'.format(param, prefix, verstr))
if wildcards:
# Resolve wildcard matches
_available = list_repo_pkgs(*[x[0] for x in wildcards], refresh=refresh)
for pkgname, verstr in wildcards:
candidates = _available.get(pkgname, [])
match = salt.utils.itertools.fnmatch_multiple(candidates, verstr)
if match is not None:
targets.append('='.join((pkgname, match)))
else:
errors.append(
'No version matching \'{0}\' found for package \'{1}\' '
'(available: {2})'.format(
verstr,
pkgname,
', '.join(candidates) if candidates else 'none'
)
)
if refresh:
try:
# Prevent a second refresh when we run the install command
cmd.remove('-y')
except ValueError:
# Shouldn't happen since we only add -y when refresh is True,
# but just in case that code above is inadvertently changed,
# don't let this result in a traceback.
pass
if not errors:
cmd.extend(targets)
old = list_pkgs()
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
try:
changes = ret
except UnboundLocalError:
# We ran into errors before we attempted to install anything, so
# there are no changes.
changes = {}
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': changes}
)
return ret | python | def install(name=None,
refresh=False,
sysupgrade=None,
pkgs=None,
sources=None,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any pacman commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install (``pacman -S``) the specified packag(s). Add ``refresh=True`` to
install with ``-y``, add ``sysupgrade=True`` to install with ``-u``.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
sysupgrade
Whether or not to upgrade the system packages before installing.
If refresh is set to ``True`` but sysupgrade is not specified, ``-u`` will be
applied
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install \
sources='[{"foo": "salt://foo.pkg.tar.xz"}, \
{"bar": "salt://bar.pkg.tar.xz"}]'
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
if 'root' in kwargs:
pkg_params['-r'] = kwargs['root']
cmd = []
if salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.append('pacman')
targets = []
errors = []
targets = []
if pkg_type == 'file':
cmd.extend(['-U', '--noprogressbar', '--noconfirm'])
cmd.extend(pkg_params)
elif pkg_type == 'repository':
cmd.append('-S')
if refresh is True:
cmd.append('-y')
if sysupgrade is True or (sysupgrade is None and refresh is True):
cmd.append('-u')
cmd.extend(['--noprogressbar', '--noconfirm', '--needed'])
wildcards = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
if '*' in verstr:
if prefix == '=':
wildcards.append((param, verstr))
else:
errors.append(
'Invalid wildcard for {0}{1}{2}'.format(
param, prefix, verstr
)
)
continue
targets.append('{0}{1}{2}'.format(param, prefix, verstr))
if wildcards:
# Resolve wildcard matches
_available = list_repo_pkgs(*[x[0] for x in wildcards], refresh=refresh)
for pkgname, verstr in wildcards:
candidates = _available.get(pkgname, [])
match = salt.utils.itertools.fnmatch_multiple(candidates, verstr)
if match is not None:
targets.append('='.join((pkgname, match)))
else:
errors.append(
'No version matching \'{0}\' found for package \'{1}\' '
'(available: {2})'.format(
verstr,
pkgname,
', '.join(candidates) if candidates else 'none'
)
)
if refresh:
try:
# Prevent a second refresh when we run the install command
cmd.remove('-y')
except ValueError:
# Shouldn't happen since we only add -y when refresh is True,
# but just in case that code above is inadvertently changed,
# don't let this result in a traceback.
pass
if not errors:
cmd.extend(targets)
old = list_pkgs()
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
try:
changes = ret
except UnboundLocalError:
# We ran into errors before we attempted to install anything, so
# there are no changes.
changes = {}
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': changes}
)
return ret | [
"def",
"install",
"(",
"name",
"=",
"None",
",",
"refresh",
"=",
"False",
",",
"sysupgrade",
"=",
"None",
",",
"pkgs",
"=",
"None",
",",
"sources",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"pkg_params",
",",
"pkg_type",
"=",
"__s... | .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any pacman commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install (``pacman -S``) the specified packag(s). Add ``refresh=True`` to
install with ``-y``, add ``sysupgrade=True`` to install with ``-u``.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
sysupgrade
Whether or not to upgrade the system packages before installing.
If refresh is set to ``True`` but sysupgrade is not specified, ``-u`` will be
applied
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install \
sources='[{"foo": "salt://foo.pkg.tar.xz"}, \
{"bar": "salt://bar.pkg.tar.xz"}]'
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}} | [
"..",
"versionchanged",
"::",
"2015",
".",
"8",
".",
"12",
"2016",
".",
"3",
".",
"3",
"2016",
".",
"11",
".",
"0",
"On",
"minions",
"running",
"systemd",
">",
"=",
"205",
"systemd",
"-",
"run",
"(",
"1",
")",
"_",
"is",
"now",
"used",
"to",
"i... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pacmanpkg.py#L444-L635 | train |
saltstack/salt | salt/modules/pacmanpkg.py | upgrade | def upgrade(refresh=False, root=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any pacman commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a pacman -Syu
refresh
Whether or not to refresh the package database before installing.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': ''}
old = list_pkgs()
cmd = []
if salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(['pacman', '-Su', '--noprogressbar', '--noconfirm'])
if salt.utils.data.is_true(refresh):
cmd.append('-y')
if root is not None:
cmd.extend(('-r', root))
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret | python | def upgrade(refresh=False, root=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any pacman commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a pacman -Syu
refresh
Whether or not to refresh the package database before installing.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': ''}
old = list_pkgs()
cmd = []
if salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(['pacman', '-Su', '--noprogressbar', '--noconfirm'])
if salt.utils.data.is_true(refresh):
cmd.append('-y')
if root is not None:
cmd.extend(('-r', root))
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret | [
"def",
"upgrade",
"(",
"refresh",
"=",
"False",
",",
"root",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"old",
"=",
"list_pkgs",
"("... | .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any pacman commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a pacman -Syu
refresh
Whether or not to refresh the package database before installing.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade | [
"..",
"versionchanged",
"::",
"2015",
".",
"8",
".",
"12",
"2016",
".",
"3",
".",
"3",
"2016",
".",
"11",
".",
"0",
"On",
"minions",
"running",
"systemd",
">",
"=",
"205",
"systemd",
"-",
"run",
"(",
"1",
")",
"_",
"is",
"now",
"used",
"to",
"i... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pacmanpkg.py#L638-L703 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.