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/mac_pkgutil.py | install | def install(source, package_id):
'''
Install a .pkg from an URI or an absolute path.
:param str source: The path to a package.
:param str package_id: The package ID
:return: True if successful, otherwise False
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' pkgutil.install source=/vagrant/build_essentials.pkg package_id=com.apple.pkg.gcc4.2Leo
'''
if is_installed(package_id):
return True
uri = urllib.parse.urlparse(source)
if not uri.scheme == '':
msg = 'Unsupported scheme for source uri: {0}'.format(uri.scheme)
raise SaltInvocationError(msg)
_install_from_path(source)
return is_installed(package_id) | python | def install(source, package_id):
'''
Install a .pkg from an URI or an absolute path.
:param str source: The path to a package.
:param str package_id: The package ID
:return: True if successful, otherwise False
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' pkgutil.install source=/vagrant/build_essentials.pkg package_id=com.apple.pkg.gcc4.2Leo
'''
if is_installed(package_id):
return True
uri = urllib.parse.urlparse(source)
if not uri.scheme == '':
msg = 'Unsupported scheme for source uri: {0}'.format(uri.scheme)
raise SaltInvocationError(msg)
_install_from_path(source)
return is_installed(package_id) | [
"def",
"install",
"(",
"source",
",",
"package_id",
")",
":",
"if",
"is_installed",
"(",
"package_id",
")",
":",
"return",
"True",
"uri",
"=",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"source",
")",
"if",
"not",
"uri",
".",
"scheme",
"==",
"''",
... | Install a .pkg from an URI or an absolute path.
:param str source: The path to a package.
:param str package_id: The package ID
:return: True if successful, otherwise False
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' pkgutil.install source=/vagrant/build_essentials.pkg package_id=com.apple.pkg.gcc4.2Leo | [
"Install",
"a",
".",
"pkg",
"from",
"an",
"URI",
"or",
"an",
"absolute",
"path",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_pkgutil.py#L85-L112 | train |
saltstack/salt | salt/modules/mac_pkgutil.py | forget | def forget(package_id):
'''
.. versionadded:: 2016.3.0
Remove the receipt data about the specified package. Does not remove files.
.. warning::
DO NOT use this command to fix broken package design
:param str package_id: The name of the package to forget
:return: True if successful, otherwise False
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' pkgutil.forget com.apple.pkg.gcc4.2Leo
'''
cmd = 'pkgutil --forget {0}'.format(package_id)
salt.utils.mac_utils.execute_return_success(cmd)
return not is_installed(package_id) | python | def forget(package_id):
'''
.. versionadded:: 2016.3.0
Remove the receipt data about the specified package. Does not remove files.
.. warning::
DO NOT use this command to fix broken package design
:param str package_id: The name of the package to forget
:return: True if successful, otherwise False
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' pkgutil.forget com.apple.pkg.gcc4.2Leo
'''
cmd = 'pkgutil --forget {0}'.format(package_id)
salt.utils.mac_utils.execute_return_success(cmd)
return not is_installed(package_id) | [
"def",
"forget",
"(",
"package_id",
")",
":",
"cmd",
"=",
"'pkgutil --forget {0}'",
".",
"format",
"(",
"package_id",
")",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_success",
"(",
"cmd",
")",
"return",
"not",
"is_installed",
"(",
"package_id... | .. versionadded:: 2016.3.0
Remove the receipt data about the specified package. Does not remove files.
.. warning::
DO NOT use this command to fix broken package design
:param str package_id: The name of the package to forget
:return: True if successful, otherwise False
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' pkgutil.forget com.apple.pkg.gcc4.2Leo | [
"..",
"versionadded",
"::",
"2016",
".",
"3",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_pkgutil.py#L115-L137 | train |
saltstack/salt | salt/modules/marathon.py | apps | def apps():
'''
Return a list of the currently installed app ids.
CLI Example:
.. code-block:: bash
salt marathon-minion-id marathon.apps
'''
response = salt.utils.http.query(
"{0}/v2/apps".format(_base_url()),
decode_type='json',
decode=True,
)
return {'apps': [app['id'] for app in response['dict']['apps']]} | python | def apps():
'''
Return a list of the currently installed app ids.
CLI Example:
.. code-block:: bash
salt marathon-minion-id marathon.apps
'''
response = salt.utils.http.query(
"{0}/v2/apps".format(_base_url()),
decode_type='json',
decode=True,
)
return {'apps': [app['id'] for app in response['dict']['apps']]} | [
"def",
"apps",
"(",
")",
":",
"response",
"=",
"salt",
".",
"utils",
".",
"http",
".",
"query",
"(",
"\"{0}/v2/apps\"",
".",
"format",
"(",
"_base_url",
"(",
")",
")",
",",
"decode_type",
"=",
"'json'",
",",
"decode",
"=",
"True",
",",
")",
"return",... | Return a list of the currently installed app ids.
CLI Example:
.. code-block:: bash
salt marathon-minion-id marathon.apps | [
"Return",
"a",
"list",
"of",
"the",
"currently",
"installed",
"app",
"ids",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/marathon.py#L55-L70 | train |
saltstack/salt | salt/modules/marathon.py | update_app | def update_app(id, config):
'''
Update the specified app with the given configuration.
CLI Example:
.. code-block:: bash
salt marathon-minion-id marathon.update_app my-app '<config yaml>'
'''
if 'id' not in config:
config['id'] = id
config.pop('version', None)
# mirror marathon-ui handling for uris deprecation (see
# mesosphere/marathon-ui#594 for more details)
config.pop('fetch', None)
data = salt.utils.json.dumps(config)
try:
response = salt.utils.http.query(
"{0}/v2/apps/{1}?force=true".format(_base_url(), id),
method='PUT',
decode_type='json',
decode=True,
data=data,
header_dict={
'Content-Type': 'application/json',
'Accept': 'application/json',
},
)
log.debug('update response: %s', response)
return response['dict']
except Exception as ex:
log.error('unable to update marathon app: %s', get_error_message(ex))
return {
'exception': {
'message': get_error_message(ex),
}
} | python | def update_app(id, config):
'''
Update the specified app with the given configuration.
CLI Example:
.. code-block:: bash
salt marathon-minion-id marathon.update_app my-app '<config yaml>'
'''
if 'id' not in config:
config['id'] = id
config.pop('version', None)
# mirror marathon-ui handling for uris deprecation (see
# mesosphere/marathon-ui#594 for more details)
config.pop('fetch', None)
data = salt.utils.json.dumps(config)
try:
response = salt.utils.http.query(
"{0}/v2/apps/{1}?force=true".format(_base_url(), id),
method='PUT',
decode_type='json',
decode=True,
data=data,
header_dict={
'Content-Type': 'application/json',
'Accept': 'application/json',
},
)
log.debug('update response: %s', response)
return response['dict']
except Exception as ex:
log.error('unable to update marathon app: %s', get_error_message(ex))
return {
'exception': {
'message': get_error_message(ex),
}
} | [
"def",
"update_app",
"(",
"id",
",",
"config",
")",
":",
"if",
"'id'",
"not",
"in",
"config",
":",
"config",
"[",
"'id'",
"]",
"=",
"id",
"config",
".",
"pop",
"(",
"'version'",
",",
"None",
")",
"# mirror marathon-ui handling for uris deprecation (see",
"# ... | Update the specified app with the given configuration.
CLI Example:
.. code-block:: bash
salt marathon-minion-id marathon.update_app my-app '<config yaml>' | [
"Update",
"the",
"specified",
"app",
"with",
"the",
"given",
"configuration",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/marathon.py#L104-L141 | train |
saltstack/salt | salt/modules/marathon.py | rm_app | def rm_app(id):
'''
Remove the specified app from the server.
CLI Example:
.. code-block:: bash
salt marathon-minion-id marathon.rm_app my-app
'''
response = salt.utils.http.query(
"{0}/v2/apps/{1}".format(_base_url(), id),
method='DELETE',
decode_type='json',
decode=True,
)
return response['dict'] | python | def rm_app(id):
'''
Remove the specified app from the server.
CLI Example:
.. code-block:: bash
salt marathon-minion-id marathon.rm_app my-app
'''
response = salt.utils.http.query(
"{0}/v2/apps/{1}".format(_base_url(), id),
method='DELETE',
decode_type='json',
decode=True,
)
return response['dict'] | [
"def",
"rm_app",
"(",
"id",
")",
":",
"response",
"=",
"salt",
".",
"utils",
".",
"http",
".",
"query",
"(",
"\"{0}/v2/apps/{1}\"",
".",
"format",
"(",
"_base_url",
"(",
")",
",",
"id",
")",
",",
"method",
"=",
"'DELETE'",
",",
"decode_type",
"=",
"'... | Remove the specified app from the server.
CLI Example:
.. code-block:: bash
salt marathon-minion-id marathon.rm_app my-app | [
"Remove",
"the",
"specified",
"app",
"from",
"the",
"server",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/marathon.py#L144-L160 | train |
saltstack/salt | salt/modules/marathon.py | info | def info():
'''
Return configuration and status information about the marathon instance.
CLI Example:
.. code-block:: bash
salt marathon-minion-id marathon.info
'''
response = salt.utils.http.query(
"{0}/v2/info".format(_base_url()),
decode_type='json',
decode=True,
)
return response['dict'] | python | def info():
'''
Return configuration and status information about the marathon instance.
CLI Example:
.. code-block:: bash
salt marathon-minion-id marathon.info
'''
response = salt.utils.http.query(
"{0}/v2/info".format(_base_url()),
decode_type='json',
decode=True,
)
return response['dict'] | [
"def",
"info",
"(",
")",
":",
"response",
"=",
"salt",
".",
"utils",
".",
"http",
".",
"query",
"(",
"\"{0}/v2/info\"",
".",
"format",
"(",
"_base_url",
"(",
")",
")",
",",
"decode_type",
"=",
"'json'",
",",
"decode",
"=",
"True",
",",
")",
"return",... | Return configuration and status information about the marathon instance.
CLI Example:
.. code-block:: bash
salt marathon-minion-id marathon.info | [
"Return",
"configuration",
"and",
"status",
"information",
"about",
"the",
"marathon",
"instance",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/marathon.py#L163-L178 | train |
saltstack/salt | salt/modules/marathon.py | restart_app | def restart_app(id, restart=False, force=True):
'''
Restart the current server configuration for the specified app.
:param restart: Restart the app
:param force: Override the current deployment
CLI Example:
.. code-block:: bash
salt marathon-minion-id marathon.restart_app my-app
By default, this will only check if the app exists in marathon. It does
not check if there are any tasks associated with it or if the app is suspended.
.. code-block:: bash
salt marathon-minion-id marathon.restart_app my-app true true
The restart option needs to be set to True to actually issue a rolling
restart to marathon.
The force option tells marathon to ignore the current app deployment if
there is one.
'''
ret = {'restarted': None}
if not restart:
ret['restarted'] = False
return ret
try:
response = salt.utils.http.query(
"{0}/v2/apps/{1}/restart?force={2}".format(_base_url(), _app_id(id), force),
method='POST',
decode_type='json',
decode=True,
header_dict={
'Content-Type': 'application/json',
'Accept': 'application/json',
},
)
log.debug('restart response: %s', response)
ret['restarted'] = True
ret.update(response['dict'])
return ret
except Exception as ex:
log.error('unable to restart marathon app: %s', ex.message)
return {
'exception': {
'message': ex.message,
}
} | python | def restart_app(id, restart=False, force=True):
'''
Restart the current server configuration for the specified app.
:param restart: Restart the app
:param force: Override the current deployment
CLI Example:
.. code-block:: bash
salt marathon-minion-id marathon.restart_app my-app
By default, this will only check if the app exists in marathon. It does
not check if there are any tasks associated with it or if the app is suspended.
.. code-block:: bash
salt marathon-minion-id marathon.restart_app my-app true true
The restart option needs to be set to True to actually issue a rolling
restart to marathon.
The force option tells marathon to ignore the current app deployment if
there is one.
'''
ret = {'restarted': None}
if not restart:
ret['restarted'] = False
return ret
try:
response = salt.utils.http.query(
"{0}/v2/apps/{1}/restart?force={2}".format(_base_url(), _app_id(id), force),
method='POST',
decode_type='json',
decode=True,
header_dict={
'Content-Type': 'application/json',
'Accept': 'application/json',
},
)
log.debug('restart response: %s', response)
ret['restarted'] = True
ret.update(response['dict'])
return ret
except Exception as ex:
log.error('unable to restart marathon app: %s', ex.message)
return {
'exception': {
'message': ex.message,
}
} | [
"def",
"restart_app",
"(",
"id",
",",
"restart",
"=",
"False",
",",
"force",
"=",
"True",
")",
":",
"ret",
"=",
"{",
"'restarted'",
":",
"None",
"}",
"if",
"not",
"restart",
":",
"ret",
"[",
"'restarted'",
"]",
"=",
"False",
"return",
"ret",
"try",
... | Restart the current server configuration for the specified app.
:param restart: Restart the app
:param force: Override the current deployment
CLI Example:
.. code-block:: bash
salt marathon-minion-id marathon.restart_app my-app
By default, this will only check if the app exists in marathon. It does
not check if there are any tasks associated with it or if the app is suspended.
.. code-block:: bash
salt marathon-minion-id marathon.restart_app my-app true true
The restart option needs to be set to True to actually issue a rolling
restart to marathon.
The force option tells marathon to ignore the current app deployment if
there is one. | [
"Restart",
"the",
"current",
"server",
"configuration",
"for",
"the",
"specified",
"app",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/marathon.py#L181-L233 | train |
saltstack/salt | salt/modules/win_dns_client.py | get_dns_servers | def get_dns_servers(interface='Local Area Connection'):
'''
Return a list of the configured DNS servers of the specified interface
CLI Example:
.. code-block:: bash
salt '*' win_dns_client.get_dns_servers 'Local Area Connection'
'''
# remove any escape characters
interface = interface.split('\\')
interface = ''.join(interface)
with salt.utils.winapi.Com():
c = wmi.WMI()
for iface in c.Win32_NetworkAdapter(NetEnabled=True):
if interface == iface.NetConnectionID:
iface_config = c.Win32_NetworkAdapterConfiguration(Index=iface.Index).pop()
try:
return list(iface_config.DNSServerSearchOrder)
except TypeError:
return []
log.debug('Interface "%s" not found', interface)
return False | python | def get_dns_servers(interface='Local Area Connection'):
'''
Return a list of the configured DNS servers of the specified interface
CLI Example:
.. code-block:: bash
salt '*' win_dns_client.get_dns_servers 'Local Area Connection'
'''
# remove any escape characters
interface = interface.split('\\')
interface = ''.join(interface)
with salt.utils.winapi.Com():
c = wmi.WMI()
for iface in c.Win32_NetworkAdapter(NetEnabled=True):
if interface == iface.NetConnectionID:
iface_config = c.Win32_NetworkAdapterConfiguration(Index=iface.Index).pop()
try:
return list(iface_config.DNSServerSearchOrder)
except TypeError:
return []
log.debug('Interface "%s" not found', interface)
return False | [
"def",
"get_dns_servers",
"(",
"interface",
"=",
"'Local Area Connection'",
")",
":",
"# remove any escape characters",
"interface",
"=",
"interface",
".",
"split",
"(",
"'\\\\'",
")",
"interface",
"=",
"''",
".",
"join",
"(",
"interface",
")",
"with",
"salt",
"... | Return a list of the configured DNS servers of the specified interface
CLI Example:
.. code-block:: bash
salt '*' win_dns_client.get_dns_servers 'Local Area Connection' | [
"Return",
"a",
"list",
"of",
"the",
"configured",
"DNS",
"servers",
"of",
"the",
"specified",
"interface"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dns_client.py#L30-L54 | train |
saltstack/salt | salt/modules/win_dns_client.py | rm_dns | def rm_dns(ip, interface='Local Area Connection'):
'''
Remove the DNS server from the network interface
CLI Example:
.. code-block:: bash
salt '*' win_dns_client.rm_dns <ip> <interface>
'''
cmd = ['netsh', 'interface', 'ip', 'delete', 'dns', interface, ip, 'validate=no']
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 | python | def rm_dns(ip, interface='Local Area Connection'):
'''
Remove the DNS server from the network interface
CLI Example:
.. code-block:: bash
salt '*' win_dns_client.rm_dns <ip> <interface>
'''
cmd = ['netsh', 'interface', 'ip', 'delete', 'dns', interface, ip, 'validate=no']
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 | [
"def",
"rm_dns",
"(",
"ip",
",",
"interface",
"=",
"'Local Area Connection'",
")",
":",
"cmd",
"=",
"[",
"'netsh'",
",",
"'interface'",
",",
"'ip'",
",",
"'delete'",
",",
"'dns'",
",",
"interface",
",",
"ip",
",",
"'validate=no'",
"]",
"return",
"__salt__"... | Remove the DNS server from the network interface
CLI Example:
.. code-block:: bash
salt '*' win_dns_client.rm_dns <ip> <interface> | [
"Remove",
"the",
"DNS",
"server",
"from",
"the",
"network",
"interface"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dns_client.py#L57-L68 | train |
saltstack/salt | salt/modules/win_dns_client.py | add_dns | def add_dns(ip, interface='Local Area Connection', index=1):
'''
Add the DNS server to the network interface
(index starts from 1)
Note: if the interface DNS is configured by DHCP, all the DNS servers will
be removed from the interface and the requested DNS will be the only one
CLI Example:
.. code-block:: bash
salt '*' win_dns_client.add_dns <ip> <interface> <index>
'''
servers = get_dns_servers(interface)
# Return False if could not find the interface
if servers is False:
return False
# Return true if configured
try:
if servers[index - 1] == ip:
return True
except IndexError:
pass
# If configured in the wrong order delete it
if ip in servers:
rm_dns(ip, interface)
cmd = ['netsh', 'interface', 'ip', 'add', 'dns',
interface, ip, 'index={0}'.format(index), 'validate=no']
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 | python | def add_dns(ip, interface='Local Area Connection', index=1):
'''
Add the DNS server to the network interface
(index starts from 1)
Note: if the interface DNS is configured by DHCP, all the DNS servers will
be removed from the interface and the requested DNS will be the only one
CLI Example:
.. code-block:: bash
salt '*' win_dns_client.add_dns <ip> <interface> <index>
'''
servers = get_dns_servers(interface)
# Return False if could not find the interface
if servers is False:
return False
# Return true if configured
try:
if servers[index - 1] == ip:
return True
except IndexError:
pass
# If configured in the wrong order delete it
if ip in servers:
rm_dns(ip, interface)
cmd = ['netsh', 'interface', 'ip', 'add', 'dns',
interface, ip, 'index={0}'.format(index), 'validate=no']
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 | [
"def",
"add_dns",
"(",
"ip",
",",
"interface",
"=",
"'Local Area Connection'",
",",
"index",
"=",
"1",
")",
":",
"servers",
"=",
"get_dns_servers",
"(",
"interface",
")",
"# Return False if could not find the interface",
"if",
"servers",
"is",
"False",
":",
"retur... | Add the DNS server to the network interface
(index starts from 1)
Note: if the interface DNS is configured by DHCP, all the DNS servers will
be removed from the interface and the requested DNS will be the only one
CLI Example:
.. code-block:: bash
salt '*' win_dns_client.add_dns <ip> <interface> <index> | [
"Add",
"the",
"DNS",
"server",
"to",
"the",
"network",
"interface",
"(",
"index",
"starts",
"from",
"1",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dns_client.py#L71-L105 | train |
saltstack/salt | salt/modules/win_dns_client.py | get_dns_config | def get_dns_config(interface='Local Area Connection'):
'''
Get the type of DNS configuration (dhcp / static)
CLI Example:
.. code-block:: bash
salt '*' win_dns_client.get_dns_config 'Local Area Connection'
'''
# remove any escape characters
interface = interface.split('\\')
interface = ''.join(interface)
with salt.utils.winapi.Com():
c = wmi.WMI()
for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1):
if interface == iface.Description:
return iface.DHCPEnabled | python | def get_dns_config(interface='Local Area Connection'):
'''
Get the type of DNS configuration (dhcp / static)
CLI Example:
.. code-block:: bash
salt '*' win_dns_client.get_dns_config 'Local Area Connection'
'''
# remove any escape characters
interface = interface.split('\\')
interface = ''.join(interface)
with salt.utils.winapi.Com():
c = wmi.WMI()
for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1):
if interface == iface.Description:
return iface.DHCPEnabled | [
"def",
"get_dns_config",
"(",
"interface",
"=",
"'Local Area Connection'",
")",
":",
"# remove any escape characters",
"interface",
"=",
"interface",
".",
"split",
"(",
"'\\\\'",
")",
"interface",
"=",
"''",
".",
"join",
"(",
"interface",
")",
"with",
"salt",
".... | Get the type of DNS configuration (dhcp / static)
CLI Example:
.. code-block:: bash
salt '*' win_dns_client.get_dns_config 'Local Area Connection' | [
"Get",
"the",
"type",
"of",
"DNS",
"configuration",
"(",
"dhcp",
"/",
"static",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dns_client.py#L122-L140 | train |
saltstack/salt | salt/states/bower.py | installed | def installed(name,
dir,
pkgs=None,
user=None,
env=None):
'''
Verify that the given package is installed and is at the correct version
(if specified).
.. code-block:: yaml
underscore:
bower.installed:
- dir: /path/to/project
- user: someuser
jquery#2.0:
bower.installed:
- dir: /path/to/project
name
The package to install
dir
The target directory in which to install the package
pkgs
A list of packages to install with a single Bower invocation;
specifying this argument will ignore the ``name`` argument
user
The user to run Bower with
env
A list of environment variables to be set prior to execution. The
format is the same as the :py:func:`cmd.run <salt.states.cmd.run>`.
state function.
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if pkgs is not None:
pkg_list = pkgs
else:
pkg_list = [name]
try:
installed_pkgs = __salt__['bower.list'](dir=dir, runas=user, env=env)
except (CommandNotFoundError, CommandExecutionError) as err:
ret['result'] = False
ret['comment'] = 'Error looking up \'{0}\': {1}'.format(name, err)
return ret
else:
installed_pkgs = dict((p, info) for p, info in
six.iteritems(installed_pkgs))
pkgs_satisfied = []
pkgs_to_install = []
for pkg in pkg_list:
pkg_name, _, pkg_ver = pkg.partition('#')
pkg_name = pkg_name.strip()
if pkg_name not in installed_pkgs:
pkgs_to_install.append(pkg)
continue
if pkg_name in installed_pkgs:
installed_pkg = installed_pkgs[pkg_name]
installed_pkg_ver = installed_pkg.get('pkgMeta').get('version')
installed_name_ver = '{0}#{1}'.format(
pkg_name,
installed_pkg_ver)
# If given an explicit version check the installed version matches.
if pkg_ver:
if installed_pkg_ver != pkg_ver:
pkgs_to_install.append(pkg)
else:
pkgs_satisfied.append(installed_name_ver)
continue
else:
pkgs_satisfied.append(installed_name_ver)
continue
if __opts__['test']:
ret['result'] = None
comment_msg = []
if pkgs_to_install:
comment_msg.append(
'Bower package(s) \'{0}\' are set to be installed'.format(
', '.join(pkgs_to_install)))
ret['changes'] = {'old': [], 'new': pkgs_to_install}
if pkgs_satisfied:
comment_msg.append(
'Package(s) \'{0}\' satisfied by {1}'.format(
', '.join(pkg_list), ', '.join(pkgs_satisfied)))
ret['comment'] = '. '.join(comment_msg)
return ret
if not pkgs_to_install:
ret['result'] = True
ret['comment'] = ('Package(s) \'{0}\' satisfied by {1}'.format(
', '.join(pkg_list), ', '.join(pkgs_satisfied)))
return ret
try:
cmd_args = {
'pkg': None,
'dir': dir,
'pkgs': None,
'runas': user,
'env': env,
}
if pkgs is not None:
cmd_args['pkgs'] = pkgs
else:
cmd_args['pkg'] = pkg_name
call = __salt__['bower.install'](**cmd_args)
except (CommandNotFoundError, CommandExecutionError) as err:
ret['result'] = False
ret['comment'] = 'Error installing \'{0}\': {1}'.format(
', '.join(pkg_list), err)
return ret
if call:
ret['result'] = True
ret['changes'] = {'old': [], 'new': pkgs_to_install}
ret['comment'] = 'Package(s) \'{0}\' successfully installed'.format(
', '.join(pkgs_to_install))
else:
ret['result'] = False
ret['comment'] = 'Could not install package(s) \'{0}\''.format(
', '.join(pkg_list))
return ret | python | def installed(name,
dir,
pkgs=None,
user=None,
env=None):
'''
Verify that the given package is installed and is at the correct version
(if specified).
.. code-block:: yaml
underscore:
bower.installed:
- dir: /path/to/project
- user: someuser
jquery#2.0:
bower.installed:
- dir: /path/to/project
name
The package to install
dir
The target directory in which to install the package
pkgs
A list of packages to install with a single Bower invocation;
specifying this argument will ignore the ``name`` argument
user
The user to run Bower with
env
A list of environment variables to be set prior to execution. The
format is the same as the :py:func:`cmd.run <salt.states.cmd.run>`.
state function.
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if pkgs is not None:
pkg_list = pkgs
else:
pkg_list = [name]
try:
installed_pkgs = __salt__['bower.list'](dir=dir, runas=user, env=env)
except (CommandNotFoundError, CommandExecutionError) as err:
ret['result'] = False
ret['comment'] = 'Error looking up \'{0}\': {1}'.format(name, err)
return ret
else:
installed_pkgs = dict((p, info) for p, info in
six.iteritems(installed_pkgs))
pkgs_satisfied = []
pkgs_to_install = []
for pkg in pkg_list:
pkg_name, _, pkg_ver = pkg.partition('#')
pkg_name = pkg_name.strip()
if pkg_name not in installed_pkgs:
pkgs_to_install.append(pkg)
continue
if pkg_name in installed_pkgs:
installed_pkg = installed_pkgs[pkg_name]
installed_pkg_ver = installed_pkg.get('pkgMeta').get('version')
installed_name_ver = '{0}#{1}'.format(
pkg_name,
installed_pkg_ver)
# If given an explicit version check the installed version matches.
if pkg_ver:
if installed_pkg_ver != pkg_ver:
pkgs_to_install.append(pkg)
else:
pkgs_satisfied.append(installed_name_ver)
continue
else:
pkgs_satisfied.append(installed_name_ver)
continue
if __opts__['test']:
ret['result'] = None
comment_msg = []
if pkgs_to_install:
comment_msg.append(
'Bower package(s) \'{0}\' are set to be installed'.format(
', '.join(pkgs_to_install)))
ret['changes'] = {'old': [], 'new': pkgs_to_install}
if pkgs_satisfied:
comment_msg.append(
'Package(s) \'{0}\' satisfied by {1}'.format(
', '.join(pkg_list), ', '.join(pkgs_satisfied)))
ret['comment'] = '. '.join(comment_msg)
return ret
if not pkgs_to_install:
ret['result'] = True
ret['comment'] = ('Package(s) \'{0}\' satisfied by {1}'.format(
', '.join(pkg_list), ', '.join(pkgs_satisfied)))
return ret
try:
cmd_args = {
'pkg': None,
'dir': dir,
'pkgs': None,
'runas': user,
'env': env,
}
if pkgs is not None:
cmd_args['pkgs'] = pkgs
else:
cmd_args['pkg'] = pkg_name
call = __salt__['bower.install'](**cmd_args)
except (CommandNotFoundError, CommandExecutionError) as err:
ret['result'] = False
ret['comment'] = 'Error installing \'{0}\': {1}'.format(
', '.join(pkg_list), err)
return ret
if call:
ret['result'] = True
ret['changes'] = {'old': [], 'new': pkgs_to_install}
ret['comment'] = 'Package(s) \'{0}\' successfully installed'.format(
', '.join(pkgs_to_install))
else:
ret['result'] = False
ret['comment'] = 'Could not install package(s) \'{0}\''.format(
', '.join(pkg_list))
return ret | [
"def",
"installed",
"(",
"name",
",",
"dir",
",",
"pkgs",
"=",
"None",
",",
"user",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
",",
"'changes'... | Verify that the given package is installed and is at the correct version
(if specified).
.. code-block:: yaml
underscore:
bower.installed:
- dir: /path/to/project
- user: someuser
jquery#2.0:
bower.installed:
- dir: /path/to/project
name
The package to install
dir
The target directory in which to install the package
pkgs
A list of packages to install with a single Bower invocation;
specifying this argument will ignore the ``name`` argument
user
The user to run Bower with
env
A list of environment variables to be set prior to execution. The
format is the same as the :py:func:`cmd.run <salt.states.cmd.run>`.
state function. | [
"Verify",
"that",
"the",
"given",
"package",
"is",
"installed",
"and",
"is",
"at",
"the",
"correct",
"version",
"(",
"if",
"specified",
")",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bower.py#L49-L190 | train |
saltstack/salt | salt/states/bower.py | bootstrap | def bootstrap(name, user=None):
'''
Bootstraps a frontend distribution.
Will execute 'bower install' on the specified directory.
user
The user to run Bower with
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Directory \'{0}\' is set to be bootstrapped'.format(
name)
return ret
try:
call = __salt__['bower.install'](pkg=None, dir=name, runas=user)
except (CommandNotFoundError, CommandExecutionError) as err:
ret['result'] = False
ret['comment'] = 'Error bootstrapping \'{0}\': {1}'.format(name, err)
return ret
if not call:
ret['result'] = True
ret['comment'] = 'Directory is already bootstrapped'
return ret
ret['result'] = True
ret['changes'] = {name: 'Bootstrapped'}
ret['comment'] = 'Directory was successfully bootstrapped'
return ret | python | def bootstrap(name, user=None):
'''
Bootstraps a frontend distribution.
Will execute 'bower install' on the specified directory.
user
The user to run Bower with
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Directory \'{0}\' is set to be bootstrapped'.format(
name)
return ret
try:
call = __salt__['bower.install'](pkg=None, dir=name, runas=user)
except (CommandNotFoundError, CommandExecutionError) as err:
ret['result'] = False
ret['comment'] = 'Error bootstrapping \'{0}\': {1}'.format(name, err)
return ret
if not call:
ret['result'] = True
ret['comment'] = 'Directory is already bootstrapped'
return ret
ret['result'] = True
ret['changes'] = {name: 'Bootstrapped'}
ret['comment'] = 'Directory was successfully bootstrapped'
return ret | [
"def",
"bootstrap",
"(",
"name",
",",
"user",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"if",
"__opts__",
"[",
"'test'",
"]",
":... | Bootstraps a frontend distribution.
Will execute 'bower install' on the specified directory.
user
The user to run Bower with | [
"Bootstraps",
"a",
"frontend",
"distribution",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bower.py#L239-L273 | train |
saltstack/salt | salt/states/bower.py | pruned | def pruned(name, user=None, env=None):
'''
.. versionadded:: 2017.7.0
Cleans up local bower_components directory.
Will execute 'bower prune' on the specified directory (param: name)
user
The user to run Bower with
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Directory \'{0}\' is set to be pruned'.format(
name)
return ret
try:
call = __salt__['bower.prune'](dir=name, runas=user, env=env)
except (CommandNotFoundError, CommandExecutionError) as err:
ret['result'] = False
ret['comment'] = 'Error pruning \'{0}\': {1}'.format(name, err)
return ret
ret['result'] = True
if call:
ret['comment'] = 'Directory \'{0}\' was successfully pruned'.format(name)
ret['changes'] = {'old': [], 'new': call}
else:
ret['comment'] = 'No packages were pruned from directory \'{0}\''.format(name)
return ret | python | def pruned(name, user=None, env=None):
'''
.. versionadded:: 2017.7.0
Cleans up local bower_components directory.
Will execute 'bower prune' on the specified directory (param: name)
user
The user to run Bower with
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Directory \'{0}\' is set to be pruned'.format(
name)
return ret
try:
call = __salt__['bower.prune'](dir=name, runas=user, env=env)
except (CommandNotFoundError, CommandExecutionError) as err:
ret['result'] = False
ret['comment'] = 'Error pruning \'{0}\': {1}'.format(name, err)
return ret
ret['result'] = True
if call:
ret['comment'] = 'Directory \'{0}\' was successfully pruned'.format(name)
ret['changes'] = {'old': [], 'new': call}
else:
ret['comment'] = 'No packages were pruned from directory \'{0}\''.format(name)
return ret | [
"def",
"pruned",
"(",
"name",
",",
"user",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"if",
"__opts__",
... | .. versionadded:: 2017.7.0
Cleans up local bower_components directory.
Will execute 'bower prune' on the specified directory (param: name)
user
The user to run Bower with | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bower.py#L276-L310 | train |
saltstack/salt | salt/states/nfs_export.py | present | def present(name,
clients=None,
hosts=None,
options=None,
exports='/etc/exports'):
'''
Ensure that the named export is present with the given options
name
The export path to configure
clients
A list of hosts and the options applied to them.
This option may not be used in combination with
the 'hosts' or 'options' shortcuts.
.. code-block:: yaml
- clients:
# First export
- hosts: '10.0.2.0/24'
options:
- 'rw'
# Second export
- hosts: '*.example.com'
options:
- 'ro'
- 'subtree_check'
hosts
A string matching a number of hosts, for example:
.. code-block:: yaml
hosts: '10.0.2.123'
hosts: '10.0.2.0/24'
hosts: 'minion1.example.com'
hosts: '*.example.com'
hosts: '*'
options
A list of NFS options, for example:
.. code-block:: yaml
options:
- 'rw'
- 'subtree_check'
'''
path = name
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if not clients:
if not hosts:
ret['result'] = False
ret['comment'] = 'Either \'clients\' or \'hosts\' must be defined'
return ret
# options being None is handled by add_export()
clients = [{'hosts': hosts, 'options': options}]
old = __salt__['nfs3.list_exports'](exports)
if path in old:
if old[path] == clients:
ret['result'] = True
ret['comment'] = 'Export {0} already configured'.format(path)
return ret
ret['changes']['new'] = clients
ret['changes']['old'] = old[path]
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Export {0} would be changed'.format(path)
return ret
__salt__['nfs3.del_export'](exports, path)
else:
ret['changes']['old'] = None
ret['changes']['new'] = clients
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Export {0} would be added'.format(path)
return ret
add_export = __salt__['nfs3.add_export']
for exp in clients:
add_export(exports, path, exp['hosts'], exp['options'])
ret['changes']['new'] = clients
try_reload = __salt__['nfs3.reload_exports']()
ret['comment'] = try_reload['stderr']
ret['result'] = try_reload['result']
return ret | python | def present(name,
clients=None,
hosts=None,
options=None,
exports='/etc/exports'):
'''
Ensure that the named export is present with the given options
name
The export path to configure
clients
A list of hosts and the options applied to them.
This option may not be used in combination with
the 'hosts' or 'options' shortcuts.
.. code-block:: yaml
- clients:
# First export
- hosts: '10.0.2.0/24'
options:
- 'rw'
# Second export
- hosts: '*.example.com'
options:
- 'ro'
- 'subtree_check'
hosts
A string matching a number of hosts, for example:
.. code-block:: yaml
hosts: '10.0.2.123'
hosts: '10.0.2.0/24'
hosts: 'minion1.example.com'
hosts: '*.example.com'
hosts: '*'
options
A list of NFS options, for example:
.. code-block:: yaml
options:
- 'rw'
- 'subtree_check'
'''
path = name
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if not clients:
if not hosts:
ret['result'] = False
ret['comment'] = 'Either \'clients\' or \'hosts\' must be defined'
return ret
# options being None is handled by add_export()
clients = [{'hosts': hosts, 'options': options}]
old = __salt__['nfs3.list_exports'](exports)
if path in old:
if old[path] == clients:
ret['result'] = True
ret['comment'] = 'Export {0} already configured'.format(path)
return ret
ret['changes']['new'] = clients
ret['changes']['old'] = old[path]
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Export {0} would be changed'.format(path)
return ret
__salt__['nfs3.del_export'](exports, path)
else:
ret['changes']['old'] = None
ret['changes']['new'] = clients
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Export {0} would be added'.format(path)
return ret
add_export = __salt__['nfs3.add_export']
for exp in clients:
add_export(exports, path, exp['hosts'], exp['options'])
ret['changes']['new'] = clients
try_reload = __salt__['nfs3.reload_exports']()
ret['comment'] = try_reload['stderr']
ret['result'] = try_reload['result']
return ret | [
"def",
"present",
"(",
"name",
",",
"clients",
"=",
"None",
",",
"hosts",
"=",
"None",
",",
"options",
"=",
"None",
",",
"exports",
"=",
"'/etc/exports'",
")",
":",
"path",
"=",
"name",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
... | Ensure that the named export is present with the given options
name
The export path to configure
clients
A list of hosts and the options applied to them.
This option may not be used in combination with
the 'hosts' or 'options' shortcuts.
.. code-block:: yaml
- clients:
# First export
- hosts: '10.0.2.0/24'
options:
- 'rw'
# Second export
- hosts: '*.example.com'
options:
- 'ro'
- 'subtree_check'
hosts
A string matching a number of hosts, for example:
.. code-block:: yaml
hosts: '10.0.2.123'
hosts: '10.0.2.0/24'
hosts: 'minion1.example.com'
hosts: '*.example.com'
hosts: '*'
options
A list of NFS options, for example:
.. code-block:: yaml
options:
- 'rw'
- 'subtree_check' | [
"Ensure",
"that",
"the",
"named",
"export",
"is",
"present",
"with",
"the",
"given",
"options"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/nfs_export.py#L79-L180 | train |
saltstack/salt | salt/states/nfs_export.py | absent | def absent(name, exports='/etc/exports'):
'''
Ensure that the named path is not exported
name
The export path to remove
'''
path = name
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
old = __salt__['nfs3.list_exports'](exports)
if path in old:
if __opts__['test']:
ret['comment'] = 'Export {0} would be removed'.format(path)
ret['changes'][path] = old[path]
ret['result'] = None
return ret
__salt__['nfs3.del_export'](exports, path)
try_reload = __salt__['nfs3.reload_exports']()
if not try_reload['result']:
ret['comment'] = try_reload['stderr']
else:
ret['comment'] = 'Export {0} removed'.format(path)
ret['result'] = try_reload['result']
ret['changes'][path] = old[path]
else:
ret['comment'] = 'Export {0} already absent'.format(path)
ret['result'] = True
return ret | python | def absent(name, exports='/etc/exports'):
'''
Ensure that the named path is not exported
name
The export path to remove
'''
path = name
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
old = __salt__['nfs3.list_exports'](exports)
if path in old:
if __opts__['test']:
ret['comment'] = 'Export {0} would be removed'.format(path)
ret['changes'][path] = old[path]
ret['result'] = None
return ret
__salt__['nfs3.del_export'](exports, path)
try_reload = __salt__['nfs3.reload_exports']()
if not try_reload['result']:
ret['comment'] = try_reload['stderr']
else:
ret['comment'] = 'Export {0} removed'.format(path)
ret['result'] = try_reload['result']
ret['changes'][path] = old[path]
else:
ret['comment'] = 'Export {0} already absent'.format(path)
ret['result'] = True
return ret | [
"def",
"absent",
"(",
"name",
",",
"exports",
"=",
"'/etc/exports'",
")",
":",
"path",
"=",
"name",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"old",
"=",... | Ensure that the named path is not exported
name
The export path to remove | [
"Ensure",
"that",
"the",
"named",
"path",
"is",
"not",
"exported"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/nfs_export.py#L183-L218 | train |
saltstack/salt | salt/utils/slack.py | query | def query(function,
api_key=None,
args=None,
method='GET',
header_dict=None,
data=None,
opts=None):
'''
Slack object method function to construct and execute on the API URL.
:param api_key: The Slack api key.
:param function: The Slack api function to perform.
:param method: The HTTP method, e.g. GET or POST.
:param data: The data to be sent for POST method.
:return: The json response from the API call or False.
'''
ret = {'message': '',
'res': True}
slack_functions = {
'rooms': {
'request': 'channels.list',
'response': 'channels',
},
'users': {
'request': 'users.list',
'response': 'members',
},
'message': {
'request': 'chat.postMessage',
'response': 'channel',
},
}
if not api_key:
api_key = __salt__['config.get']('slack.api_key') or \
__salt__['config.get']('slack:api_key')
if not api_key:
log.error('No Slack api key found.')
ret['message'] = 'No Slack api key found.'
ret['res'] = False
return ret
api_url = 'https://slack.com'
base_url = _urljoin(api_url, '/api/')
path = slack_functions.get(function).get('request')
url = _urljoin(base_url, path, False)
if not isinstance(args, dict):
query_params = {}
else:
query_params = args.copy()
query_params['token'] = api_key
if header_dict is None:
header_dict = {}
if method != 'POST':
header_dict['Accept'] = 'application/json'
result = salt.utils.http.query(
url,
method,
params=query_params,
data=data,
decode=True,
status=True,
header_dict=header_dict,
opts=opts
)
if result.get('status', None) == salt.ext.six.moves.http_client.OK:
_result = result['dict']
response = slack_functions.get(function).get('response')
if 'error' in _result:
ret['message'] = _result['error']
ret['res'] = False
return ret
ret['message'] = _result.get(response)
return ret
elif result.get('status', None) == salt.ext.six.moves.http_client.NO_CONTENT:
return True
else:
log.debug(url)
log.debug(query_params)
log.debug(data)
log.debug(result)
if 'dict' in result:
_result = result['dict']
if 'error' in _result:
ret['message'] = result['error']
ret['res'] = False
return ret
ret['message'] = _result.get(response)
else:
ret['message'] = 'invalid_auth'
ret['res'] = False
return ret | python | def query(function,
api_key=None,
args=None,
method='GET',
header_dict=None,
data=None,
opts=None):
'''
Slack object method function to construct and execute on the API URL.
:param api_key: The Slack api key.
:param function: The Slack api function to perform.
:param method: The HTTP method, e.g. GET or POST.
:param data: The data to be sent for POST method.
:return: The json response from the API call or False.
'''
ret = {'message': '',
'res': True}
slack_functions = {
'rooms': {
'request': 'channels.list',
'response': 'channels',
},
'users': {
'request': 'users.list',
'response': 'members',
},
'message': {
'request': 'chat.postMessage',
'response': 'channel',
},
}
if not api_key:
api_key = __salt__['config.get']('slack.api_key') or \
__salt__['config.get']('slack:api_key')
if not api_key:
log.error('No Slack api key found.')
ret['message'] = 'No Slack api key found.'
ret['res'] = False
return ret
api_url = 'https://slack.com'
base_url = _urljoin(api_url, '/api/')
path = slack_functions.get(function).get('request')
url = _urljoin(base_url, path, False)
if not isinstance(args, dict):
query_params = {}
else:
query_params = args.copy()
query_params['token'] = api_key
if header_dict is None:
header_dict = {}
if method != 'POST':
header_dict['Accept'] = 'application/json'
result = salt.utils.http.query(
url,
method,
params=query_params,
data=data,
decode=True,
status=True,
header_dict=header_dict,
opts=opts
)
if result.get('status', None) == salt.ext.six.moves.http_client.OK:
_result = result['dict']
response = slack_functions.get(function).get('response')
if 'error' in _result:
ret['message'] = _result['error']
ret['res'] = False
return ret
ret['message'] = _result.get(response)
return ret
elif result.get('status', None) == salt.ext.six.moves.http_client.NO_CONTENT:
return True
else:
log.debug(url)
log.debug(query_params)
log.debug(data)
log.debug(result)
if 'dict' in result:
_result = result['dict']
if 'error' in _result:
ret['message'] = result['error']
ret['res'] = False
return ret
ret['message'] = _result.get(response)
else:
ret['message'] = 'invalid_auth'
ret['res'] = False
return ret | [
"def",
"query",
"(",
"function",
",",
"api_key",
"=",
"None",
",",
"args",
"=",
"None",
",",
"method",
"=",
"'GET'",
",",
"header_dict",
"=",
"None",
",",
"data",
"=",
"None",
",",
"opts",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'message'",
":",
... | Slack object method function to construct and execute on the API URL.
:param api_key: The Slack api key.
:param function: The Slack api function to perform.
:param method: The HTTP method, e.g. GET or POST.
:param data: The data to be sent for POST method.
:return: The json response from the API call or False. | [
"Slack",
"object",
"method",
"function",
"to",
"construct",
"and",
"execute",
"on",
"the",
"API",
"URL",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/slack.py#L32-L131 | train |
saltstack/salt | salt/beacons/pkg.py | validate | def validate(config):
'''
Validate the beacon configuration
'''
# Configuration for pkg beacon should be a list
if not isinstance(config, list):
return False, ('Configuration for pkg beacon must be a list.')
# Configuration for pkg beacon should contain pkgs
pkgs_found = False
pkgs_not_list = False
for config_item in config:
if 'pkgs' in config_item:
pkgs_found = True
if isinstance(config_item['pkgs'], list):
pkgs_not_list = True
if not pkgs_found or not pkgs_not_list:
return False, 'Configuration for pkg beacon requires list of pkgs.'
return True, 'Valid beacon configuration' | python | def validate(config):
'''
Validate the beacon configuration
'''
# Configuration for pkg beacon should be a list
if not isinstance(config, list):
return False, ('Configuration for pkg beacon must be a list.')
# Configuration for pkg beacon should contain pkgs
pkgs_found = False
pkgs_not_list = False
for config_item in config:
if 'pkgs' in config_item:
pkgs_found = True
if isinstance(config_item['pkgs'], list):
pkgs_not_list = True
if not pkgs_found or not pkgs_not_list:
return False, 'Configuration for pkg beacon requires list of pkgs.'
return True, 'Valid beacon configuration' | [
"def",
"validate",
"(",
"config",
")",
":",
"# Configuration for pkg beacon should be a list",
"if",
"not",
"isinstance",
"(",
"config",
",",
"list",
")",
":",
"return",
"False",
",",
"(",
"'Configuration for pkg beacon must be a list.'",
")",
"# Configuration for pkg bea... | Validate the beacon configuration | [
"Validate",
"the",
"beacon",
"configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/pkg.py#L25-L44 | train |
saltstack/salt | salt/beacons/pkg.py | beacon | def beacon(config):
'''
Check if installed packages are the latest versions
and fire an event for those that have upgrades.
.. code-block:: yaml
beacons:
pkg:
- pkgs:
- zsh
- apache2
- refresh: True
'''
ret = []
_refresh = False
pkgs = []
for config_item in config:
if 'pkgs' in config_item:
pkgs += config_item['pkgs']
if 'refresh' in config and config['refresh']:
_refresh = True
for pkg in pkgs:
_installed = __salt__['pkg.version'](pkg)
_latest = __salt__['pkg.latest_version'](pkg, refresh=_refresh)
if _installed and _latest:
_pkg = {'pkg': pkg,
'version': _latest
}
ret.append(_pkg)
return ret | python | def beacon(config):
'''
Check if installed packages are the latest versions
and fire an event for those that have upgrades.
.. code-block:: yaml
beacons:
pkg:
- pkgs:
- zsh
- apache2
- refresh: True
'''
ret = []
_refresh = False
pkgs = []
for config_item in config:
if 'pkgs' in config_item:
pkgs += config_item['pkgs']
if 'refresh' in config and config['refresh']:
_refresh = True
for pkg in pkgs:
_installed = __salt__['pkg.version'](pkg)
_latest = __salt__['pkg.latest_version'](pkg, refresh=_refresh)
if _installed and _latest:
_pkg = {'pkg': pkg,
'version': _latest
}
ret.append(_pkg)
return ret | [
"def",
"beacon",
"(",
"config",
")",
":",
"ret",
"=",
"[",
"]",
"_refresh",
"=",
"False",
"pkgs",
"=",
"[",
"]",
"for",
"config_item",
"in",
"config",
":",
"if",
"'pkgs'",
"in",
"config_item",
":",
"pkgs",
"+=",
"config_item",
"[",
"'pkgs'",
"]",
"if... | Check if installed packages are the latest versions
and fire an event for those that have upgrades.
.. code-block:: yaml
beacons:
pkg:
- pkgs:
- zsh
- apache2
- refresh: True | [
"Check",
"if",
"installed",
"packages",
"are",
"the",
"latest",
"versions",
"and",
"fire",
"an",
"event",
"for",
"those",
"that",
"have",
"upgrades",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/pkg.py#L47-L79 | train |
saltstack/salt | salt/states/logrotate.py | set_ | def set_(name, key, value, setting=None, conf_file=_DEFAULT_CONF):
'''
Set a new value for a specific configuration line.
:param str key: The command or block to configure.
:param str value: The command value or command of the block specified by the key parameter.
:param str setting: The command value for the command specified by the value parameter.
:param str conf_file: The logrotate configuration file.
Example of usage with only the required arguments:
.. code-block:: yaml
logrotate-rotate:
logrotate.set:
- key: rotate
- value: 2
Example of usage specifying all available arguments:
.. code-block:: yaml
logrotate-wtmp-rotate:
logrotate.set:
- key: /var/log/wtmp
- value: rotate
- setting: 2
- conf_file: /etc/logrotate.conf
'''
ret = {'name': name,
'changes': dict(),
'comment': six.text_type(),
'result': None}
try:
if setting is None:
current_value = __salt__['logrotate.get'](key=key, conf_file=conf_file)
else:
current_value = __salt__['logrotate.get'](key=key, value=value, conf_file=conf_file)
except (AttributeError, KeyError):
current_value = False
if setting is None:
value = _convert_if_int(value)
if current_value == value:
ret['comment'] = "Command '{0}' already has value: {1}".format(key, value)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = "Command '{0}' will be set to value: {1}".format(key, value)
ret['changes'] = {'old': current_value,
'new': value}
else:
ret['changes'] = {'old': current_value,
'new': value}
ret['result'] = __salt__['logrotate.set'](key=key, value=value, conf_file=conf_file)
if ret['result']:
ret['comment'] = "Set command '{0}' value: {1}".format(key, value)
else:
ret['comment'] = "Unable to set command '{0}' value: {1}".format(key, value)
return ret
setting = _convert_if_int(setting)
if current_value == setting:
ret['comment'] = "Block '{0}' command '{1}' already has value: {2}".format(key, value, setting)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = "Block '{0}' command '{1}' will be set to value: {2}".format(key, value, setting)
ret['changes'] = {'old': current_value,
'new': setting}
else:
ret['changes'] = {'old': current_value,
'new': setting}
ret['result'] = __salt__['logrotate.set'](key=key, value=value, setting=setting,
conf_file=conf_file)
if ret['result']:
ret['comment'] = "Set block '{0}' command '{1}' value: {2}".format(key, value, setting)
else:
ret['comment'] = "Unable to set block '{0}' command '{1}' value: {2}".format(key, value, setting)
return ret | python | def set_(name, key, value, setting=None, conf_file=_DEFAULT_CONF):
'''
Set a new value for a specific configuration line.
:param str key: The command or block to configure.
:param str value: The command value or command of the block specified by the key parameter.
:param str setting: The command value for the command specified by the value parameter.
:param str conf_file: The logrotate configuration file.
Example of usage with only the required arguments:
.. code-block:: yaml
logrotate-rotate:
logrotate.set:
- key: rotate
- value: 2
Example of usage specifying all available arguments:
.. code-block:: yaml
logrotate-wtmp-rotate:
logrotate.set:
- key: /var/log/wtmp
- value: rotate
- setting: 2
- conf_file: /etc/logrotate.conf
'''
ret = {'name': name,
'changes': dict(),
'comment': six.text_type(),
'result': None}
try:
if setting is None:
current_value = __salt__['logrotate.get'](key=key, conf_file=conf_file)
else:
current_value = __salt__['logrotate.get'](key=key, value=value, conf_file=conf_file)
except (AttributeError, KeyError):
current_value = False
if setting is None:
value = _convert_if_int(value)
if current_value == value:
ret['comment'] = "Command '{0}' already has value: {1}".format(key, value)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = "Command '{0}' will be set to value: {1}".format(key, value)
ret['changes'] = {'old': current_value,
'new': value}
else:
ret['changes'] = {'old': current_value,
'new': value}
ret['result'] = __salt__['logrotate.set'](key=key, value=value, conf_file=conf_file)
if ret['result']:
ret['comment'] = "Set command '{0}' value: {1}".format(key, value)
else:
ret['comment'] = "Unable to set command '{0}' value: {1}".format(key, value)
return ret
setting = _convert_if_int(setting)
if current_value == setting:
ret['comment'] = "Block '{0}' command '{1}' already has value: {2}".format(key, value, setting)
ret['result'] = True
elif __opts__['test']:
ret['comment'] = "Block '{0}' command '{1}' will be set to value: {2}".format(key, value, setting)
ret['changes'] = {'old': current_value,
'new': setting}
else:
ret['changes'] = {'old': current_value,
'new': setting}
ret['result'] = __salt__['logrotate.set'](key=key, value=value, setting=setting,
conf_file=conf_file)
if ret['result']:
ret['comment'] = "Set block '{0}' command '{1}' value: {2}".format(key, value, setting)
else:
ret['comment'] = "Unable to set block '{0}' command '{1}' value: {2}".format(key, value, setting)
return ret | [
"def",
"set_",
"(",
"name",
",",
"key",
",",
"value",
",",
"setting",
"=",
"None",
",",
"conf_file",
"=",
"_DEFAULT_CONF",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"dict",
"(",
")",
",",
"'comment'",
":",
"six",
".",... | Set a new value for a specific configuration line.
:param str key: The command or block to configure.
:param str value: The command value or command of the block specified by the key parameter.
:param str setting: The command value for the command specified by the value parameter.
:param str conf_file: The logrotate configuration file.
Example of usage with only the required arguments:
.. code-block:: yaml
logrotate-rotate:
logrotate.set:
- key: rotate
- value: 2
Example of usage specifying all available arguments:
.. code-block:: yaml
logrotate-wtmp-rotate:
logrotate.set:
- key: /var/log/wtmp
- value: rotate
- setting: 2
- conf_file: /etc/logrotate.conf | [
"Set",
"a",
"new",
"value",
"for",
"a",
"specific",
"configuration",
"line",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/logrotate.py#L51-L131 | train |
saltstack/salt | salt/fileserver/__init__.py | _unlock_cache | def _unlock_cache(w_lock):
'''
Unlock a FS file/dir based lock
'''
if not os.path.exists(w_lock):
return
try:
if os.path.isdir(w_lock):
os.rmdir(w_lock)
elif os.path.isfile(w_lock):
os.unlink(w_lock)
except (OSError, IOError) as exc:
log.trace('Error removing lockfile %s: %s', w_lock, exc) | python | def _unlock_cache(w_lock):
'''
Unlock a FS file/dir based lock
'''
if not os.path.exists(w_lock):
return
try:
if os.path.isdir(w_lock):
os.rmdir(w_lock)
elif os.path.isfile(w_lock):
os.unlink(w_lock)
except (OSError, IOError) as exc:
log.trace('Error removing lockfile %s: %s', w_lock, exc) | [
"def",
"_unlock_cache",
"(",
"w_lock",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"w_lock",
")",
":",
"return",
"try",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"w_lock",
")",
":",
"os",
".",
"rmdir",
"(",
"w_lock",
")",... | Unlock a FS file/dir based lock | [
"Unlock",
"a",
"FS",
"file",
"/",
"dir",
"based",
"lock"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L39-L51 | train |
saltstack/salt | salt/fileserver/__init__.py | wait_lock | def wait_lock(lk_fn, dest, wait_timeout=0):
'''
If the write lock is there, check to see if the file is actually being
written. If there is no change in the file size after a short sleep,
remove the lock and move forward.
'''
if not os.path.exists(lk_fn):
return False
if not os.path.exists(dest):
# The dest is not here, sleep for a bit, if the dest is not here yet
# kill the lockfile and start the write
time.sleep(1)
if not os.path.isfile(dest):
_unlock_cache(lk_fn)
return False
timeout = None
if wait_timeout:
timeout = time.time() + wait_timeout
# There is a lock file, the dest is there, stat the dest, sleep and check
# that the dest is being written, if it is not being written kill the lock
# file and continue. Also check if the lock file is gone.
s_count = 0
s_size = os.stat(dest).st_size
while True:
time.sleep(1)
if not os.path.exists(lk_fn):
return False
size = os.stat(dest).st_size
if size == s_size:
s_count += 1
if s_count >= 3:
# The file is not being written to, kill the lock and proceed
_unlock_cache(lk_fn)
return False
else:
s_size = size
if timeout:
if time.time() > timeout:
raise ValueError(
'Timeout({0}s) for {1} (lock: {2}) elapsed'.format(
wait_timeout, dest, lk_fn
)
)
return False | python | def wait_lock(lk_fn, dest, wait_timeout=0):
'''
If the write lock is there, check to see if the file is actually being
written. If there is no change in the file size after a short sleep,
remove the lock and move forward.
'''
if not os.path.exists(lk_fn):
return False
if not os.path.exists(dest):
# The dest is not here, sleep for a bit, if the dest is not here yet
# kill the lockfile and start the write
time.sleep(1)
if not os.path.isfile(dest):
_unlock_cache(lk_fn)
return False
timeout = None
if wait_timeout:
timeout = time.time() + wait_timeout
# There is a lock file, the dest is there, stat the dest, sleep and check
# that the dest is being written, if it is not being written kill the lock
# file and continue. Also check if the lock file is gone.
s_count = 0
s_size = os.stat(dest).st_size
while True:
time.sleep(1)
if not os.path.exists(lk_fn):
return False
size = os.stat(dest).st_size
if size == s_size:
s_count += 1
if s_count >= 3:
# The file is not being written to, kill the lock and proceed
_unlock_cache(lk_fn)
return False
else:
s_size = size
if timeout:
if time.time() > timeout:
raise ValueError(
'Timeout({0}s) for {1} (lock: {2}) elapsed'.format(
wait_timeout, dest, lk_fn
)
)
return False | [
"def",
"wait_lock",
"(",
"lk_fn",
",",
"dest",
",",
"wait_timeout",
"=",
"0",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"lk_fn",
")",
":",
"return",
"False",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dest",
")",
":"... | If the write lock is there, check to see if the file is actually being
written. If there is no change in the file size after a short sleep,
remove the lock and move forward. | [
"If",
"the",
"write",
"lock",
"is",
"there",
"check",
"to",
"see",
"if",
"the",
"file",
"is",
"actually",
"being",
"written",
".",
"If",
"there",
"is",
"no",
"change",
"in",
"the",
"file",
"size",
"after",
"a",
"short",
"sleep",
"remove",
"the",
"lock"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L66-L109 | train |
saltstack/salt | salt/fileserver/__init__.py | check_file_list_cache | def check_file_list_cache(opts, form, list_cache, w_lock):
'''
Checks the cache file to see if there is a new enough file list cache, and
returns the match (if found, along with booleans used by the fileserver
backend to determine if the cache needs to be refreshed/written).
'''
refresh_cache = False
save_cache = True
serial = salt.payload.Serial(opts)
wait_lock(w_lock, list_cache, 5 * 60)
if not os.path.isfile(list_cache) and _lock_cache(w_lock):
refresh_cache = True
else:
attempt = 0
while attempt < 11:
try:
if os.path.exists(w_lock):
# wait for a filelist lock for max 15min
wait_lock(w_lock, list_cache, 15 * 60)
if os.path.exists(list_cache):
# calculate filelist age is possible
cache_stat = os.stat(list_cache)
# st_time can have a greater precision than time, removing
# float precision makes sure age will never be a negative
# number.
current_time = int(time.time())
file_mtime = int(cache_stat.st_mtime)
if file_mtime > current_time:
log.debug(
'Cache file modified time is in the future, ignoring. '
'file=%s mtime=%s current_time=%s',
list_cache, current_time, file_mtime
)
age = 0
else:
age = current_time - file_mtime
else:
# if filelist does not exists yet, mark it as expired
age = opts.get('fileserver_list_cache_time', 20) + 1
if age < 0:
# Cache is from the future! Warn and mark cache invalid.
log.warning('The file list_cache was created in the future!')
if 0 <= age < opts.get('fileserver_list_cache_time', 20):
# Young enough! Load this sucker up!
with salt.utils.files.fopen(list_cache, 'rb') as fp_:
log.debug(
"Returning file list from cache: age=%s cache_time=%s %s",
age, opts.get('fileserver_list_cache_time', 20), list_cache
)
return salt.utils.data.decode(serial.load(fp_).get(form, [])), False, False
elif _lock_cache(w_lock):
# Set the w_lock and go
refresh_cache = True
break
except Exception:
time.sleep(0.2)
attempt += 1
continue
if attempt > 10:
save_cache = False
refresh_cache = True
return None, refresh_cache, save_cache | python | def check_file_list_cache(opts, form, list_cache, w_lock):
'''
Checks the cache file to see if there is a new enough file list cache, and
returns the match (if found, along with booleans used by the fileserver
backend to determine if the cache needs to be refreshed/written).
'''
refresh_cache = False
save_cache = True
serial = salt.payload.Serial(opts)
wait_lock(w_lock, list_cache, 5 * 60)
if not os.path.isfile(list_cache) and _lock_cache(w_lock):
refresh_cache = True
else:
attempt = 0
while attempt < 11:
try:
if os.path.exists(w_lock):
# wait for a filelist lock for max 15min
wait_lock(w_lock, list_cache, 15 * 60)
if os.path.exists(list_cache):
# calculate filelist age is possible
cache_stat = os.stat(list_cache)
# st_time can have a greater precision than time, removing
# float precision makes sure age will never be a negative
# number.
current_time = int(time.time())
file_mtime = int(cache_stat.st_mtime)
if file_mtime > current_time:
log.debug(
'Cache file modified time is in the future, ignoring. '
'file=%s mtime=%s current_time=%s',
list_cache, current_time, file_mtime
)
age = 0
else:
age = current_time - file_mtime
else:
# if filelist does not exists yet, mark it as expired
age = opts.get('fileserver_list_cache_time', 20) + 1
if age < 0:
# Cache is from the future! Warn and mark cache invalid.
log.warning('The file list_cache was created in the future!')
if 0 <= age < opts.get('fileserver_list_cache_time', 20):
# Young enough! Load this sucker up!
with salt.utils.files.fopen(list_cache, 'rb') as fp_:
log.debug(
"Returning file list from cache: age=%s cache_time=%s %s",
age, opts.get('fileserver_list_cache_time', 20), list_cache
)
return salt.utils.data.decode(serial.load(fp_).get(form, [])), False, False
elif _lock_cache(w_lock):
# Set the w_lock and go
refresh_cache = True
break
except Exception:
time.sleep(0.2)
attempt += 1
continue
if attempt > 10:
save_cache = False
refresh_cache = True
return None, refresh_cache, save_cache | [
"def",
"check_file_list_cache",
"(",
"opts",
",",
"form",
",",
"list_cache",
",",
"w_lock",
")",
":",
"refresh_cache",
"=",
"False",
"save_cache",
"=",
"True",
"serial",
"=",
"salt",
".",
"payload",
".",
"Serial",
"(",
"opts",
")",
"wait_lock",
"(",
"w_loc... | Checks the cache file to see if there is a new enough file list cache, and
returns the match (if found, along with booleans used by the fileserver
backend to determine if the cache needs to be refreshed/written). | [
"Checks",
"the",
"cache",
"file",
"to",
"see",
"if",
"there",
"is",
"a",
"new",
"enough",
"file",
"list",
"cache",
"and",
"returns",
"the",
"match",
"(",
"if",
"found",
"along",
"with",
"booleans",
"used",
"by",
"the",
"fileserver",
"backend",
"to",
"det... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L112-L173 | train |
saltstack/salt | salt/fileserver/__init__.py | write_file_list_cache | def write_file_list_cache(opts, data, list_cache, w_lock):
'''
Checks the cache file to see if there is a new enough file list cache, and
returns the match (if found, along with booleans used by the fileserver
backend to determine if the cache needs to be refreshed/written).
'''
serial = salt.payload.Serial(opts)
with salt.utils.files.fopen(list_cache, 'w+b') as fp_:
fp_.write(serial.dumps(data))
_unlock_cache(w_lock)
log.trace('Lockfile %s removed', w_lock) | python | def write_file_list_cache(opts, data, list_cache, w_lock):
'''
Checks the cache file to see if there is a new enough file list cache, and
returns the match (if found, along with booleans used by the fileserver
backend to determine if the cache needs to be refreshed/written).
'''
serial = salt.payload.Serial(opts)
with salt.utils.files.fopen(list_cache, 'w+b') as fp_:
fp_.write(serial.dumps(data))
_unlock_cache(w_lock)
log.trace('Lockfile %s removed', w_lock) | [
"def",
"write_file_list_cache",
"(",
"opts",
",",
"data",
",",
"list_cache",
",",
"w_lock",
")",
":",
"serial",
"=",
"salt",
".",
"payload",
".",
"Serial",
"(",
"opts",
")",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"list_cache",
"... | Checks the cache file to see if there is a new enough file list cache, and
returns the match (if found, along with booleans used by the fileserver
backend to determine if the cache needs to be refreshed/written). | [
"Checks",
"the",
"cache",
"file",
"to",
"see",
"if",
"there",
"is",
"a",
"new",
"enough",
"file",
"list",
"cache",
"and",
"returns",
"the",
"match",
"(",
"if",
"found",
"along",
"with",
"booleans",
"used",
"by",
"the",
"fileserver",
"backend",
"to",
"det... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L176-L186 | train |
saltstack/salt | salt/fileserver/__init__.py | check_env_cache | def check_env_cache(opts, env_cache):
'''
Returns cached env names, if present. Otherwise returns None.
'''
if not os.path.isfile(env_cache):
return None
try:
with salt.utils.files.fopen(env_cache, 'rb') as fp_:
log.trace('Returning env cache data from %s', env_cache)
serial = salt.payload.Serial(opts)
return salt.utils.data.decode(serial.load(fp_))
except (IOError, OSError):
pass
return None | python | def check_env_cache(opts, env_cache):
'''
Returns cached env names, if present. Otherwise returns None.
'''
if not os.path.isfile(env_cache):
return None
try:
with salt.utils.files.fopen(env_cache, 'rb') as fp_:
log.trace('Returning env cache data from %s', env_cache)
serial = salt.payload.Serial(opts)
return salt.utils.data.decode(serial.load(fp_))
except (IOError, OSError):
pass
return None | [
"def",
"check_env_cache",
"(",
"opts",
",",
"env_cache",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"env_cache",
")",
":",
"return",
"None",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"env_cache",
",... | Returns cached env names, if present. Otherwise returns None. | [
"Returns",
"cached",
"env",
"names",
"if",
"present",
".",
"Otherwise",
"returns",
"None",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L189-L202 | train |
saltstack/salt | salt/fileserver/__init__.py | generate_mtime_map | def generate_mtime_map(opts, path_map):
'''
Generate a dict of filename -> mtime
'''
file_map = {}
for saltenv, path_list in six.iteritems(path_map):
for path in path_list:
for directory, _, filenames in salt.utils.path.os_walk(path):
for item in filenames:
try:
file_path = os.path.join(directory, item)
# Don't walk any directories that match
# file_ignore_regex or glob
if is_file_ignored(opts, file_path):
continue
file_map[file_path] = os.path.getmtime(file_path)
except (OSError, IOError):
# skip dangling symlinks
log.info(
'Failed to get mtime on %s, dangling symlink?',
file_path
)
continue
return file_map | python | def generate_mtime_map(opts, path_map):
'''
Generate a dict of filename -> mtime
'''
file_map = {}
for saltenv, path_list in six.iteritems(path_map):
for path in path_list:
for directory, _, filenames in salt.utils.path.os_walk(path):
for item in filenames:
try:
file_path = os.path.join(directory, item)
# Don't walk any directories that match
# file_ignore_regex or glob
if is_file_ignored(opts, file_path):
continue
file_map[file_path] = os.path.getmtime(file_path)
except (OSError, IOError):
# skip dangling symlinks
log.info(
'Failed to get mtime on %s, dangling symlink?',
file_path
)
continue
return file_map | [
"def",
"generate_mtime_map",
"(",
"opts",
",",
"path_map",
")",
":",
"file_map",
"=",
"{",
"}",
"for",
"saltenv",
",",
"path_list",
"in",
"six",
".",
"iteritems",
"(",
"path_map",
")",
":",
"for",
"path",
"in",
"path_list",
":",
"for",
"directory",
",",
... | Generate a dict of filename -> mtime | [
"Generate",
"a",
"dict",
"of",
"filename",
"-",
">",
"mtime"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L205-L228 | train |
saltstack/salt | salt/fileserver/__init__.py | diff_mtime_map | def diff_mtime_map(map1, map2):
'''
Is there a change to the mtime map? return a boolean
'''
# check if the mtimes are the same
if sorted(map1) != sorted(map2):
return True
# map1 and map2 are guaranteed to have same keys,
# so compare mtimes
for filename, mtime in six.iteritems(map1):
if map2[filename] != mtime:
return True
# we made it, that means we have no changes
return False | python | def diff_mtime_map(map1, map2):
'''
Is there a change to the mtime map? return a boolean
'''
# check if the mtimes are the same
if sorted(map1) != sorted(map2):
return True
# map1 and map2 are guaranteed to have same keys,
# so compare mtimes
for filename, mtime in six.iteritems(map1):
if map2[filename] != mtime:
return True
# we made it, that means we have no changes
return False | [
"def",
"diff_mtime_map",
"(",
"map1",
",",
"map2",
")",
":",
"# check if the mtimes are the same",
"if",
"sorted",
"(",
"map1",
")",
"!=",
"sorted",
"(",
"map2",
")",
":",
"return",
"True",
"# map1 and map2 are guaranteed to have same keys,",
"# so compare mtimes",
"f... | Is there a change to the mtime map? return a boolean | [
"Is",
"there",
"a",
"change",
"to",
"the",
"mtime",
"map?",
"return",
"a",
"boolean"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L231-L246 | train |
saltstack/salt | salt/fileserver/__init__.py | reap_fileserver_cache_dir | def reap_fileserver_cache_dir(cache_base, find_func):
'''
Remove unused cache items assuming the cache directory follows a directory
convention:
cache_base -> saltenv -> relpath
'''
for saltenv in os.listdir(cache_base):
env_base = os.path.join(cache_base, saltenv)
for root, dirs, files in salt.utils.path.os_walk(env_base):
# if we have an empty directory, lets cleanup
# This will only remove the directory on the second time
# "_reap_cache" is called (which is intentional)
if not dirs and not files:
# only remove if empty directory is older than 60s
if time.time() - os.path.getctime(root) > 60:
os.rmdir(root)
continue
# if not, lets check the files in the directory
for file_ in files:
file_path = os.path.join(root, file_)
file_rel_path = os.path.relpath(file_path, env_base)
try:
filename, _, hash_type = file_rel_path.rsplit('.', 2)
except ValueError:
log.warning(
'Found invalid hash file [%s] when attempting to reap '
'cache directory', file_
)
continue
# do we have the file?
ret = find_func(filename, saltenv=saltenv)
# if we don't actually have the file, lets clean up the cache
# object
if ret['path'] == '':
os.unlink(file_path) | python | def reap_fileserver_cache_dir(cache_base, find_func):
'''
Remove unused cache items assuming the cache directory follows a directory
convention:
cache_base -> saltenv -> relpath
'''
for saltenv in os.listdir(cache_base):
env_base = os.path.join(cache_base, saltenv)
for root, dirs, files in salt.utils.path.os_walk(env_base):
# if we have an empty directory, lets cleanup
# This will only remove the directory on the second time
# "_reap_cache" is called (which is intentional)
if not dirs and not files:
# only remove if empty directory is older than 60s
if time.time() - os.path.getctime(root) > 60:
os.rmdir(root)
continue
# if not, lets check the files in the directory
for file_ in files:
file_path = os.path.join(root, file_)
file_rel_path = os.path.relpath(file_path, env_base)
try:
filename, _, hash_type = file_rel_path.rsplit('.', 2)
except ValueError:
log.warning(
'Found invalid hash file [%s] when attempting to reap '
'cache directory', file_
)
continue
# do we have the file?
ret = find_func(filename, saltenv=saltenv)
# if we don't actually have the file, lets clean up the cache
# object
if ret['path'] == '':
os.unlink(file_path) | [
"def",
"reap_fileserver_cache_dir",
"(",
"cache_base",
",",
"find_func",
")",
":",
"for",
"saltenv",
"in",
"os",
".",
"listdir",
"(",
"cache_base",
")",
":",
"env_base",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cache_base",
",",
"saltenv",
")",
"for",
... | Remove unused cache items assuming the cache directory follows a directory
convention:
cache_base -> saltenv -> relpath | [
"Remove",
"unused",
"cache",
"items",
"assuming",
"the",
"cache",
"directory",
"follows",
"a",
"directory",
"convention",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L249-L284 | train |
saltstack/salt | salt/fileserver/__init__.py | is_file_ignored | def is_file_ignored(opts, fname):
'''
If file_ignore_regex or file_ignore_glob were given in config,
compare the given file path against all of them and return True
on the first match.
'''
if opts['file_ignore_regex']:
for regex in opts['file_ignore_regex']:
if re.search(regex, fname):
log.debug(
'File matching file_ignore_regex. Skipping: %s',
fname
)
return True
if opts['file_ignore_glob']:
for glob in opts['file_ignore_glob']:
if fnmatch.fnmatch(fname, glob):
log.debug(
'File matching file_ignore_glob. Skipping: %s',
fname
)
return True
return False | python | def is_file_ignored(opts, fname):
'''
If file_ignore_regex or file_ignore_glob were given in config,
compare the given file path against all of them and return True
on the first match.
'''
if opts['file_ignore_regex']:
for regex in opts['file_ignore_regex']:
if re.search(regex, fname):
log.debug(
'File matching file_ignore_regex. Skipping: %s',
fname
)
return True
if opts['file_ignore_glob']:
for glob in opts['file_ignore_glob']:
if fnmatch.fnmatch(fname, glob):
log.debug(
'File matching file_ignore_glob. Skipping: %s',
fname
)
return True
return False | [
"def",
"is_file_ignored",
"(",
"opts",
",",
"fname",
")",
":",
"if",
"opts",
"[",
"'file_ignore_regex'",
"]",
":",
"for",
"regex",
"in",
"opts",
"[",
"'file_ignore_regex'",
"]",
":",
"if",
"re",
".",
"search",
"(",
"regex",
",",
"fname",
")",
":",
"log... | If file_ignore_regex or file_ignore_glob were given in config,
compare the given file path against all of them and return True
on the first match. | [
"If",
"file_ignore_regex",
"or",
"file_ignore_glob",
"were",
"given",
"in",
"config",
"compare",
"the",
"given",
"file",
"path",
"against",
"all",
"of",
"them",
"and",
"return",
"True",
"on",
"the",
"first",
"match",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L287-L310 | train |
saltstack/salt | salt/fileserver/__init__.py | clear_lock | def clear_lock(clear_func, role, remote=None, lock_type='update'):
'''
Function to allow non-fileserver functions to clear update locks
clear_func
A function reference. This function will be run (with the ``remote``
param as an argument) to clear the lock, and must return a 2-tuple of
lists, one containing messages describing successfully cleared locks,
and one containing messages describing errors encountered.
role
What type of lock is being cleared (gitfs, git_pillar, etc.). Used
solely for logging purposes.
remote
Optional string which should be used in ``func`` to pattern match so
that a subset of remotes can be targeted.
lock_type : update
Which type of lock to clear
Returns the return data from ``clear_func``.
'''
msg = 'Clearing {0} lock for {1} remotes'.format(lock_type, role)
if remote:
msg += ' matching {0}'.format(remote)
log.debug(msg)
return clear_func(remote=remote, lock_type=lock_type) | python | def clear_lock(clear_func, role, remote=None, lock_type='update'):
'''
Function to allow non-fileserver functions to clear update locks
clear_func
A function reference. This function will be run (with the ``remote``
param as an argument) to clear the lock, and must return a 2-tuple of
lists, one containing messages describing successfully cleared locks,
and one containing messages describing errors encountered.
role
What type of lock is being cleared (gitfs, git_pillar, etc.). Used
solely for logging purposes.
remote
Optional string which should be used in ``func`` to pattern match so
that a subset of remotes can be targeted.
lock_type : update
Which type of lock to clear
Returns the return data from ``clear_func``.
'''
msg = 'Clearing {0} lock for {1} remotes'.format(lock_type, role)
if remote:
msg += ' matching {0}'.format(remote)
log.debug(msg)
return clear_func(remote=remote, lock_type=lock_type) | [
"def",
"clear_lock",
"(",
"clear_func",
",",
"role",
",",
"remote",
"=",
"None",
",",
"lock_type",
"=",
"'update'",
")",
":",
"msg",
"=",
"'Clearing {0} lock for {1} remotes'",
".",
"format",
"(",
"lock_type",
",",
"role",
")",
"if",
"remote",
":",
"msg",
... | Function to allow non-fileserver functions to clear update locks
clear_func
A function reference. This function will be run (with the ``remote``
param as an argument) to clear the lock, and must return a 2-tuple of
lists, one containing messages describing successfully cleared locks,
and one containing messages describing errors encountered.
role
What type of lock is being cleared (gitfs, git_pillar, etc.). Used
solely for logging purposes.
remote
Optional string which should be used in ``func`` to pattern match so
that a subset of remotes can be targeted.
lock_type : update
Which type of lock to clear
Returns the return data from ``clear_func``. | [
"Function",
"to",
"allow",
"non",
"-",
"fileserver",
"functions",
"to",
"clear",
"update",
"locks"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L313-L340 | train |
saltstack/salt | salt/fileserver/__init__.py | Fileserver.backends | def backends(self, back=None):
'''
Return the backend list
'''
if not back:
back = self.opts['fileserver_backend']
else:
if not isinstance(back, list):
try:
back = back.split(',')
except AttributeError:
back = six.text_type(back).split(',')
if isinstance(back, Sequence):
# The test suite uses an ImmutableList type (based on
# collections.Sequence) for lists, which breaks this function in
# the test suite. This normalizes the value from the opts into a
# list if it is based on collections.Sequence.
back = list(back)
ret = []
if not isinstance(back, list):
return ret
# Avoid error logging when performing lookups in the LazyDict by
# instead doing the membership check on the result of a call to its
# .keys() attribute rather than on the LazyDict itself.
server_funcs = self.servers.keys()
try:
subtract_only = all((x.startswith('-') for x in back))
except AttributeError:
pass
else:
if subtract_only:
# Only subtracting backends from enabled ones
ret = self.opts['fileserver_backend']
for sub in back:
if '{0}.envs'.format(sub[1:]) in server_funcs:
ret.remove(sub[1:])
elif '{0}.envs'.format(sub[1:-2]) in server_funcs:
ret.remove(sub[1:-2])
return ret
for sub in back:
if '{0}.envs'.format(sub) in server_funcs:
ret.append(sub)
elif '{0}.envs'.format(sub[:-2]) in server_funcs:
ret.append(sub[:-2])
return ret | python | def backends(self, back=None):
'''
Return the backend list
'''
if not back:
back = self.opts['fileserver_backend']
else:
if not isinstance(back, list):
try:
back = back.split(',')
except AttributeError:
back = six.text_type(back).split(',')
if isinstance(back, Sequence):
# The test suite uses an ImmutableList type (based on
# collections.Sequence) for lists, which breaks this function in
# the test suite. This normalizes the value from the opts into a
# list if it is based on collections.Sequence.
back = list(back)
ret = []
if not isinstance(back, list):
return ret
# Avoid error logging when performing lookups in the LazyDict by
# instead doing the membership check on the result of a call to its
# .keys() attribute rather than on the LazyDict itself.
server_funcs = self.servers.keys()
try:
subtract_only = all((x.startswith('-') for x in back))
except AttributeError:
pass
else:
if subtract_only:
# Only subtracting backends from enabled ones
ret = self.opts['fileserver_backend']
for sub in back:
if '{0}.envs'.format(sub[1:]) in server_funcs:
ret.remove(sub[1:])
elif '{0}.envs'.format(sub[1:-2]) in server_funcs:
ret.remove(sub[1:-2])
return ret
for sub in back:
if '{0}.envs'.format(sub) in server_funcs:
ret.append(sub)
elif '{0}.envs'.format(sub[:-2]) in server_funcs:
ret.append(sub[:-2])
return ret | [
"def",
"backends",
"(",
"self",
",",
"back",
"=",
"None",
")",
":",
"if",
"not",
"back",
":",
"back",
"=",
"self",
".",
"opts",
"[",
"'fileserver_backend'",
"]",
"else",
":",
"if",
"not",
"isinstance",
"(",
"back",
",",
"list",
")",
":",
"try",
":"... | Return the backend list | [
"Return",
"the",
"backend",
"list"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L353-L401 | train |
saltstack/salt | salt/fileserver/__init__.py | Fileserver.clear_cache | def clear_cache(self, back=None):
'''
Clear the cache of all of the fileserver backends that support the
clear_cache function or the named backend(s) only.
'''
back = self.backends(back)
cleared = []
errors = []
for fsb in back:
fstr = '{0}.clear_cache'.format(fsb)
if fstr in self.servers:
log.debug('Clearing %s fileserver cache', fsb)
failed = self.servers[fstr]()
if failed:
errors.extend(failed)
else:
cleared.append(
'The {0} fileserver cache was successfully cleared'
.format(fsb)
)
return cleared, errors | python | def clear_cache(self, back=None):
'''
Clear the cache of all of the fileserver backends that support the
clear_cache function or the named backend(s) only.
'''
back = self.backends(back)
cleared = []
errors = []
for fsb in back:
fstr = '{0}.clear_cache'.format(fsb)
if fstr in self.servers:
log.debug('Clearing %s fileserver cache', fsb)
failed = self.servers[fstr]()
if failed:
errors.extend(failed)
else:
cleared.append(
'The {0} fileserver cache was successfully cleared'
.format(fsb)
)
return cleared, errors | [
"def",
"clear_cache",
"(",
"self",
",",
"back",
"=",
"None",
")",
":",
"back",
"=",
"self",
".",
"backends",
"(",
"back",
")",
"cleared",
"=",
"[",
"]",
"errors",
"=",
"[",
"]",
"for",
"fsb",
"in",
"back",
":",
"fstr",
"=",
"'{0}.clear_cache'",
"."... | Clear the cache of all of the fileserver backends that support the
clear_cache function or the named backend(s) only. | [
"Clear",
"the",
"cache",
"of",
"all",
"of",
"the",
"fileserver",
"backends",
"that",
"support",
"the",
"clear_cache",
"function",
"or",
"the",
"named",
"backend",
"(",
"s",
")",
"only",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L418-L438 | train |
saltstack/salt | salt/fileserver/__init__.py | Fileserver.lock | def lock(self, back=None, remote=None):
'''
``remote`` can either be a dictionary containing repo configuration
information, or a pattern. If the latter, then remotes for which the URL
matches the pattern will be locked.
'''
back = self.backends(back)
locked = []
errors = []
for fsb in back:
fstr = '{0}.lock'.format(fsb)
if fstr in self.servers:
msg = 'Setting update lock for {0} remotes'.format(fsb)
if remote:
if not isinstance(remote, six.string_types):
errors.append(
'Badly formatted remote pattern \'{0}\''
.format(remote)
)
continue
else:
msg += ' matching {0}'.format(remote)
log.debug(msg)
good, bad = self.servers[fstr](remote=remote)
locked.extend(good)
errors.extend(bad)
return locked, errors | python | def lock(self, back=None, remote=None):
'''
``remote`` can either be a dictionary containing repo configuration
information, or a pattern. If the latter, then remotes for which the URL
matches the pattern will be locked.
'''
back = self.backends(back)
locked = []
errors = []
for fsb in back:
fstr = '{0}.lock'.format(fsb)
if fstr in self.servers:
msg = 'Setting update lock for {0} remotes'.format(fsb)
if remote:
if not isinstance(remote, six.string_types):
errors.append(
'Badly formatted remote pattern \'{0}\''
.format(remote)
)
continue
else:
msg += ' matching {0}'.format(remote)
log.debug(msg)
good, bad = self.servers[fstr](remote=remote)
locked.extend(good)
errors.extend(bad)
return locked, errors | [
"def",
"lock",
"(",
"self",
",",
"back",
"=",
"None",
",",
"remote",
"=",
"None",
")",
":",
"back",
"=",
"self",
".",
"backends",
"(",
"back",
")",
"locked",
"=",
"[",
"]",
"errors",
"=",
"[",
"]",
"for",
"fsb",
"in",
"back",
":",
"fstr",
"=",
... | ``remote`` can either be a dictionary containing repo configuration
information, or a pattern. If the latter, then remotes for which the URL
matches the pattern will be locked. | [
"remote",
"can",
"either",
"be",
"a",
"dictionary",
"containing",
"repo",
"configuration",
"information",
"or",
"a",
"pattern",
".",
"If",
"the",
"latter",
"then",
"remotes",
"for",
"which",
"the",
"URL",
"matches",
"the",
"pattern",
"will",
"be",
"locked",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L440-L466 | train |
saltstack/salt | salt/fileserver/__init__.py | Fileserver.clear_lock | def clear_lock(self, back=None, remote=None):
'''
Clear the update lock for the enabled fileserver backends
back
Only clear the update lock for the specified backend(s). The
default is to clear the lock for all enabled backends
remote
If specified, then any remotes which contain the passed string will
have their lock cleared.
'''
back = self.backends(back)
cleared = []
errors = []
for fsb in back:
fstr = '{0}.clear_lock'.format(fsb)
if fstr in self.servers:
good, bad = clear_lock(self.servers[fstr],
fsb,
remote=remote)
cleared.extend(good)
errors.extend(bad)
return cleared, errors | python | def clear_lock(self, back=None, remote=None):
'''
Clear the update lock for the enabled fileserver backends
back
Only clear the update lock for the specified backend(s). The
default is to clear the lock for all enabled backends
remote
If specified, then any remotes which contain the passed string will
have their lock cleared.
'''
back = self.backends(back)
cleared = []
errors = []
for fsb in back:
fstr = '{0}.clear_lock'.format(fsb)
if fstr in self.servers:
good, bad = clear_lock(self.servers[fstr],
fsb,
remote=remote)
cleared.extend(good)
errors.extend(bad)
return cleared, errors | [
"def",
"clear_lock",
"(",
"self",
",",
"back",
"=",
"None",
",",
"remote",
"=",
"None",
")",
":",
"back",
"=",
"self",
".",
"backends",
"(",
"back",
")",
"cleared",
"=",
"[",
"]",
"errors",
"=",
"[",
"]",
"for",
"fsb",
"in",
"back",
":",
"fstr",
... | Clear the update lock for the enabled fileserver backends
back
Only clear the update lock for the specified backend(s). The
default is to clear the lock for all enabled backends
remote
If specified, then any remotes which contain the passed string will
have their lock cleared. | [
"Clear",
"the",
"update",
"lock",
"for",
"the",
"enabled",
"fileserver",
"backends"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L468-L491 | train |
saltstack/salt | salt/fileserver/__init__.py | Fileserver.update | def update(self, back=None):
'''
Update all of the enabled fileserver backends which support the update
function, or
'''
back = self.backends(back)
for fsb in back:
fstr = '{0}.update'.format(fsb)
if fstr in self.servers:
log.debug('Updating %s fileserver cache', fsb)
self.servers[fstr]() | python | def update(self, back=None):
'''
Update all of the enabled fileserver backends which support the update
function, or
'''
back = self.backends(back)
for fsb in back:
fstr = '{0}.update'.format(fsb)
if fstr in self.servers:
log.debug('Updating %s fileserver cache', fsb)
self.servers[fstr]() | [
"def",
"update",
"(",
"self",
",",
"back",
"=",
"None",
")",
":",
"back",
"=",
"self",
".",
"backends",
"(",
"back",
")",
"for",
"fsb",
"in",
"back",
":",
"fstr",
"=",
"'{0}.update'",
".",
"format",
"(",
"fsb",
")",
"if",
"fstr",
"in",
"self",
".... | Update all of the enabled fileserver backends which support the update
function, or | [
"Update",
"all",
"of",
"the",
"enabled",
"fileserver",
"backends",
"which",
"support",
"the",
"update",
"function",
"or"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L493-L503 | train |
saltstack/salt | salt/fileserver/__init__.py | Fileserver.update_intervals | def update_intervals(self, back=None):
'''
Return the update intervals for all of the enabled fileserver backends
which support variable update intervals.
'''
back = self.backends(back)
ret = {}
for fsb in back:
fstr = '{0}.update_intervals'.format(fsb)
if fstr in self.servers:
ret[fsb] = self.servers[fstr]()
return ret | python | def update_intervals(self, back=None):
'''
Return the update intervals for all of the enabled fileserver backends
which support variable update intervals.
'''
back = self.backends(back)
ret = {}
for fsb in back:
fstr = '{0}.update_intervals'.format(fsb)
if fstr in self.servers:
ret[fsb] = self.servers[fstr]()
return ret | [
"def",
"update_intervals",
"(",
"self",
",",
"back",
"=",
"None",
")",
":",
"back",
"=",
"self",
".",
"backends",
"(",
"back",
")",
"ret",
"=",
"{",
"}",
"for",
"fsb",
"in",
"back",
":",
"fstr",
"=",
"'{0}.update_intervals'",
".",
"format",
"(",
"fsb... | Return the update intervals for all of the enabled fileserver backends
which support variable update intervals. | [
"Return",
"the",
"update",
"intervals",
"for",
"all",
"of",
"the",
"enabled",
"fileserver",
"backends",
"which",
"support",
"variable",
"update",
"intervals",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L505-L516 | train |
saltstack/salt | salt/fileserver/__init__.py | Fileserver.envs | def envs(self, back=None, sources=False):
'''
Return the environments for the named backend or all backends
'''
back = self.backends(back)
ret = set()
if sources:
ret = {}
for fsb in back:
fstr = '{0}.envs'.format(fsb)
kwargs = {'ignore_cache': True} \
if 'ignore_cache' in _argspec(self.servers[fstr]).args \
and self.opts['__role'] == 'minion' \
else {}
if sources:
ret[fsb] = self.servers[fstr](**kwargs)
else:
ret.update(self.servers[fstr](**kwargs))
if sources:
return ret
return list(ret) | python | def envs(self, back=None, sources=False):
'''
Return the environments for the named backend or all backends
'''
back = self.backends(back)
ret = set()
if sources:
ret = {}
for fsb in back:
fstr = '{0}.envs'.format(fsb)
kwargs = {'ignore_cache': True} \
if 'ignore_cache' in _argspec(self.servers[fstr]).args \
and self.opts['__role'] == 'minion' \
else {}
if sources:
ret[fsb] = self.servers[fstr](**kwargs)
else:
ret.update(self.servers[fstr](**kwargs))
if sources:
return ret
return list(ret) | [
"def",
"envs",
"(",
"self",
",",
"back",
"=",
"None",
",",
"sources",
"=",
"False",
")",
":",
"back",
"=",
"self",
".",
"backends",
"(",
"back",
")",
"ret",
"=",
"set",
"(",
")",
"if",
"sources",
":",
"ret",
"=",
"{",
"}",
"for",
"fsb",
"in",
... | Return the environments for the named backend or all backends | [
"Return",
"the",
"environments",
"for",
"the",
"named",
"backend",
"or",
"all",
"backends"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L518-L538 | train |
saltstack/salt | salt/fileserver/__init__.py | Fileserver.file_envs | def file_envs(self, load=None):
'''
Return environments for all backends for requests from fileclient
'''
if load is None:
load = {}
load.pop('cmd', None)
return self.envs(**load) | python | def file_envs(self, load=None):
'''
Return environments for all backends for requests from fileclient
'''
if load is None:
load = {}
load.pop('cmd', None)
return self.envs(**load) | [
"def",
"file_envs",
"(",
"self",
",",
"load",
"=",
"None",
")",
":",
"if",
"load",
"is",
"None",
":",
"load",
"=",
"{",
"}",
"load",
".",
"pop",
"(",
"'cmd'",
",",
"None",
")",
"return",
"self",
".",
"envs",
"(",
"*",
"*",
"load",
")"
] | Return environments for all backends for requests from fileclient | [
"Return",
"environments",
"for",
"all",
"backends",
"for",
"requests",
"from",
"fileclient"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L540-L547 | train |
saltstack/salt | salt/fileserver/__init__.py | Fileserver.init | def init(self, back=None):
'''
Initialize the backend, only do so if the fs supports an init function
'''
back = self.backends(back)
for fsb in back:
fstr = '{0}.init'.format(fsb)
if fstr in self.servers:
self.servers[fstr]() | python | def init(self, back=None):
'''
Initialize the backend, only do so if the fs supports an init function
'''
back = self.backends(back)
for fsb in back:
fstr = '{0}.init'.format(fsb)
if fstr in self.servers:
self.servers[fstr]() | [
"def",
"init",
"(",
"self",
",",
"back",
"=",
"None",
")",
":",
"back",
"=",
"self",
".",
"backends",
"(",
"back",
")",
"for",
"fsb",
"in",
"back",
":",
"fstr",
"=",
"'{0}.init'",
".",
"format",
"(",
"fsb",
")",
"if",
"fstr",
"in",
"self",
".",
... | Initialize the backend, only do so if the fs supports an init function | [
"Initialize",
"the",
"backend",
"only",
"do",
"so",
"if",
"the",
"fs",
"supports",
"an",
"init",
"function"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L549-L557 | train |
saltstack/salt | salt/fileserver/__init__.py | Fileserver._find_file | def _find_file(self, load):
'''
Convenience function for calls made using the RemoteClient
'''
path = load.get('path')
if not path:
return {'path': '',
'rel': ''}
tgt_env = load.get('saltenv', 'base')
return self.find_file(path, tgt_env) | python | def _find_file(self, load):
'''
Convenience function for calls made using the RemoteClient
'''
path = load.get('path')
if not path:
return {'path': '',
'rel': ''}
tgt_env = load.get('saltenv', 'base')
return self.find_file(path, tgt_env) | [
"def",
"_find_file",
"(",
"self",
",",
"load",
")",
":",
"path",
"=",
"load",
".",
"get",
"(",
"'path'",
")",
"if",
"not",
"path",
":",
"return",
"{",
"'path'",
":",
"''",
",",
"'rel'",
":",
"''",
"}",
"tgt_env",
"=",
"load",
".",
"get",
"(",
"... | Convenience function for calls made using the RemoteClient | [
"Convenience",
"function",
"for",
"calls",
"made",
"using",
"the",
"RemoteClient"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L559-L568 | train |
saltstack/salt | salt/fileserver/__init__.py | Fileserver.file_find | def file_find(self, load):
'''
Convenience function for calls made using the LocalClient
'''
path = load.get('path')
if not path:
return {'path': '',
'rel': ''}
tgt_env = load.get('saltenv', 'base')
return self.find_file(path, tgt_env) | python | def file_find(self, load):
'''
Convenience function for calls made using the LocalClient
'''
path = load.get('path')
if not path:
return {'path': '',
'rel': ''}
tgt_env = load.get('saltenv', 'base')
return self.find_file(path, tgt_env) | [
"def",
"file_find",
"(",
"self",
",",
"load",
")",
":",
"path",
"=",
"load",
".",
"get",
"(",
"'path'",
")",
"if",
"not",
"path",
":",
"return",
"{",
"'path'",
":",
"''",
",",
"'rel'",
":",
"''",
"}",
"tgt_env",
"=",
"load",
".",
"get",
"(",
"'... | Convenience function for calls made using the LocalClient | [
"Convenience",
"function",
"for",
"calls",
"made",
"using",
"the",
"LocalClient"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L570-L579 | train |
saltstack/salt | salt/fileserver/__init__.py | Fileserver.find_file | def find_file(self, path, saltenv, back=None):
'''
Find the path and return the fnd structure, this structure is passed
to other backend interfaces.
'''
path = salt.utils.stringutils.to_unicode(path)
saltenv = salt.utils.stringutils.to_unicode(saltenv)
back = self.backends(back)
kwargs = {}
fnd = {'path': '',
'rel': ''}
if os.path.isabs(path):
return fnd
if '../' in path:
return fnd
if salt.utils.url.is_escaped(path):
# don't attempt to find URL query arguments in the path
path = salt.utils.url.unescape(path)
else:
if '?' in path:
hcomps = path.split('?')
path = hcomps[0]
comps = hcomps[1].split('&')
for comp in comps:
if '=' not in comp:
# Invalid option, skip it
continue
args = comp.split('=', 1)
kwargs[args[0]] = args[1]
if 'env' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('env')
if 'saltenv' in kwargs:
saltenv = kwargs.pop('saltenv')
if not isinstance(saltenv, six.string_types):
saltenv = six.text_type(saltenv)
for fsb in back:
fstr = '{0}.find_file'.format(fsb)
if fstr in self.servers:
fnd = self.servers[fstr](path, saltenv, **kwargs)
if fnd.get('path'):
fnd['back'] = fsb
return fnd
return fnd | python | def find_file(self, path, saltenv, back=None):
'''
Find the path and return the fnd structure, this structure is passed
to other backend interfaces.
'''
path = salt.utils.stringutils.to_unicode(path)
saltenv = salt.utils.stringutils.to_unicode(saltenv)
back = self.backends(back)
kwargs = {}
fnd = {'path': '',
'rel': ''}
if os.path.isabs(path):
return fnd
if '../' in path:
return fnd
if salt.utils.url.is_escaped(path):
# don't attempt to find URL query arguments in the path
path = salt.utils.url.unescape(path)
else:
if '?' in path:
hcomps = path.split('?')
path = hcomps[0]
comps = hcomps[1].split('&')
for comp in comps:
if '=' not in comp:
# Invalid option, skip it
continue
args = comp.split('=', 1)
kwargs[args[0]] = args[1]
if 'env' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('env')
if 'saltenv' in kwargs:
saltenv = kwargs.pop('saltenv')
if not isinstance(saltenv, six.string_types):
saltenv = six.text_type(saltenv)
for fsb in back:
fstr = '{0}.find_file'.format(fsb)
if fstr in self.servers:
fnd = self.servers[fstr](path, saltenv, **kwargs)
if fnd.get('path'):
fnd['back'] = fsb
return fnd
return fnd | [
"def",
"find_file",
"(",
"self",
",",
"path",
",",
"saltenv",
",",
"back",
"=",
"None",
")",
":",
"path",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_unicode",
"(",
"path",
")",
"saltenv",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".... | Find the path and return the fnd structure, this structure is passed
to other backend interfaces. | [
"Find",
"the",
"path",
"and",
"return",
"the",
"fnd",
"structure",
"this",
"structure",
"is",
"passed",
"to",
"other",
"backend",
"interfaces",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L581-L627 | train |
saltstack/salt | salt/fileserver/__init__.py | Fileserver.serve_file | def serve_file(self, load):
'''
Serve up a chunk of a file
'''
ret = {'data': '',
'dest': ''}
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
if 'path' not in load or 'loc' not in load or 'saltenv' not in load:
return ret
if not isinstance(load['saltenv'], six.string_types):
load['saltenv'] = six.text_type(load['saltenv'])
fnd = self.find_file(load['path'], load['saltenv'])
if not fnd.get('back'):
return ret
fstr = '{0}.serve_file'.format(fnd['back'])
if fstr in self.servers:
return self.servers[fstr](load, fnd)
return ret | python | def serve_file(self, load):
'''
Serve up a chunk of a file
'''
ret = {'data': '',
'dest': ''}
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
if 'path' not in load or 'loc' not in load or 'saltenv' not in load:
return ret
if not isinstance(load['saltenv'], six.string_types):
load['saltenv'] = six.text_type(load['saltenv'])
fnd = self.find_file(load['path'], load['saltenv'])
if not fnd.get('back'):
return ret
fstr = '{0}.serve_file'.format(fnd['back'])
if fstr in self.servers:
return self.servers[fstr](load, fnd)
return ret | [
"def",
"serve_file",
"(",
"self",
",",
"load",
")",
":",
"ret",
"=",
"{",
"'data'",
":",
"''",
",",
"'dest'",
":",
"''",
"}",
"if",
"'env'",
"in",
"load",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"load",
".",
"pop",
"(",
"'env'",
")",
"if",
... | Serve up a chunk of a file | [
"Serve",
"up",
"a",
"chunk",
"of",
"a",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L629-L651 | train |
saltstack/salt | salt/fileserver/__init__.py | Fileserver.__file_hash_and_stat | def __file_hash_and_stat(self, load):
'''
Common code for hashing and stating files
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
if 'path' not in load or 'saltenv' not in load:
return '', None
if not isinstance(load['saltenv'], six.string_types):
load['saltenv'] = six.text_type(load['saltenv'])
fnd = self.find_file(salt.utils.stringutils.to_unicode(load['path']),
load['saltenv'])
if not fnd.get('back'):
return '', None
stat_result = fnd.get('stat', None)
fstr = '{0}.file_hash'.format(fnd['back'])
if fstr in self.servers:
return self.servers[fstr](load, fnd), stat_result
return '', None | python | def __file_hash_and_stat(self, load):
'''
Common code for hashing and stating files
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
if 'path' not in load or 'saltenv' not in load:
return '', None
if not isinstance(load['saltenv'], six.string_types):
load['saltenv'] = six.text_type(load['saltenv'])
fnd = self.find_file(salt.utils.stringutils.to_unicode(load['path']),
load['saltenv'])
if not fnd.get('back'):
return '', None
stat_result = fnd.get('stat', None)
fstr = '{0}.file_hash'.format(fnd['back'])
if fstr in self.servers:
return self.servers[fstr](load, fnd), stat_result
return '', None | [
"def",
"__file_hash_and_stat",
"(",
"self",
",",
"load",
")",
":",
"if",
"'env'",
"in",
"load",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"load",
".",
"pop",
"(",
"'env'",
")",
"if",
"'path'",
"not",
"in",
"load",
"or",
"'saltenv'",
"not",
"in",
"... | Common code for hashing and stating files | [
"Common",
"code",
"for",
"hashing",
"and",
"stating",
"files"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L653-L674 | train |
saltstack/salt | salt/fileserver/__init__.py | Fileserver.clear_file_list_cache | def clear_file_list_cache(self, load):
'''
Deletes the file_lists cache files
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
saltenv = load.get('saltenv', [])
if saltenv is not None:
if not isinstance(saltenv, list):
try:
saltenv = [x.strip() for x in saltenv.split(',')]
except AttributeError:
saltenv = [x.strip() for x in six.text_type(saltenv).split(',')]
for idx, val in enumerate(saltenv):
if not isinstance(val, six.string_types):
saltenv[idx] = six.text_type(val)
ret = {}
fsb = self.backends(load.pop('fsbackend', None))
list_cachedir = os.path.join(self.opts['cachedir'], 'file_lists')
try:
file_list_backends = os.listdir(list_cachedir)
except OSError as exc:
if exc.errno == errno.ENOENT:
log.debug('No file list caches found')
return {}
else:
log.error(
'Failed to get list of saltenvs for which the master has '
'cached file lists: %s', exc
)
for back in file_list_backends:
# Account for the fact that the file_list cache directory for gitfs
# is 'git', hgfs is 'hg', etc.
back_virtualname = re.sub('fs$', '', back)
try:
cache_files = os.listdir(os.path.join(list_cachedir, back))
except OSError as exc:
log.error(
'Failed to find file list caches for saltenv \'%s\': %s',
back, exc
)
continue
for cache_file in cache_files:
try:
cache_saltenv, extension = cache_file.rsplit('.', 1)
except ValueError:
# Filename has no dot in it. Not a cache file, ignore.
continue
if extension != 'p':
# Filename does not end in ".p". Not a cache file, ignore.
continue
elif back_virtualname not in fsb or \
(saltenv is not None and cache_saltenv not in saltenv):
log.debug(
'Skipping %s file list cache for saltenv \'%s\'',
back, cache_saltenv
)
continue
try:
os.remove(os.path.join(list_cachedir, back, cache_file))
except OSError as exc:
if exc.errno != errno.ENOENT:
log.error('Failed to remove %s: %s',
exc.filename, exc.strerror)
else:
ret.setdefault(back, []).append(cache_saltenv)
log.debug(
'Removed %s file list cache for saltenv \'%s\'',
cache_saltenv, back
)
return ret | python | def clear_file_list_cache(self, load):
'''
Deletes the file_lists cache files
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
saltenv = load.get('saltenv', [])
if saltenv is not None:
if not isinstance(saltenv, list):
try:
saltenv = [x.strip() for x in saltenv.split(',')]
except AttributeError:
saltenv = [x.strip() for x in six.text_type(saltenv).split(',')]
for idx, val in enumerate(saltenv):
if not isinstance(val, six.string_types):
saltenv[idx] = six.text_type(val)
ret = {}
fsb = self.backends(load.pop('fsbackend', None))
list_cachedir = os.path.join(self.opts['cachedir'], 'file_lists')
try:
file_list_backends = os.listdir(list_cachedir)
except OSError as exc:
if exc.errno == errno.ENOENT:
log.debug('No file list caches found')
return {}
else:
log.error(
'Failed to get list of saltenvs for which the master has '
'cached file lists: %s', exc
)
for back in file_list_backends:
# Account for the fact that the file_list cache directory for gitfs
# is 'git', hgfs is 'hg', etc.
back_virtualname = re.sub('fs$', '', back)
try:
cache_files = os.listdir(os.path.join(list_cachedir, back))
except OSError as exc:
log.error(
'Failed to find file list caches for saltenv \'%s\': %s',
back, exc
)
continue
for cache_file in cache_files:
try:
cache_saltenv, extension = cache_file.rsplit('.', 1)
except ValueError:
# Filename has no dot in it. Not a cache file, ignore.
continue
if extension != 'p':
# Filename does not end in ".p". Not a cache file, ignore.
continue
elif back_virtualname not in fsb or \
(saltenv is not None and cache_saltenv not in saltenv):
log.debug(
'Skipping %s file list cache for saltenv \'%s\'',
back, cache_saltenv
)
continue
try:
os.remove(os.path.join(list_cachedir, back, cache_file))
except OSError as exc:
if exc.errno != errno.ENOENT:
log.error('Failed to remove %s: %s',
exc.filename, exc.strerror)
else:
ret.setdefault(back, []).append(cache_saltenv)
log.debug(
'Removed %s file list cache for saltenv \'%s\'',
cache_saltenv, back
)
return ret | [
"def",
"clear_file_list_cache",
"(",
"self",
",",
"load",
")",
":",
"if",
"'env'",
"in",
"load",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"load",
".",
"pop",
"(",
"'env'",
")",
"saltenv",
"=",
"load",
".",
"get",
"(",
"'saltenv'",
",",
"[",
"]",
... | Deletes the file_lists cache files | [
"Deletes",
"the",
"file_lists",
"cache",
"files"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L694-L769 | train |
saltstack/salt | salt/fileserver/__init__.py | Fileserver.file_list | def file_list(self, load):
'''
Return a list of files from the dominant environment
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
ret = set()
if 'saltenv' not in load:
return []
if not isinstance(load['saltenv'], six.string_types):
load['saltenv'] = six.text_type(load['saltenv'])
for fsb in self.backends(load.pop('fsbackend', None)):
fstr = '{0}.file_list'.format(fsb)
if fstr in self.servers:
ret.update(self.servers[fstr](load))
# some *fs do not handle prefix. Ensure it is filtered
prefix = load.get('prefix', '').strip('/')
if prefix != '':
ret = [f for f in ret if f.startswith(prefix)]
return sorted(ret) | python | def file_list(self, load):
'''
Return a list of files from the dominant environment
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
ret = set()
if 'saltenv' not in load:
return []
if not isinstance(load['saltenv'], six.string_types):
load['saltenv'] = six.text_type(load['saltenv'])
for fsb in self.backends(load.pop('fsbackend', None)):
fstr = '{0}.file_list'.format(fsb)
if fstr in self.servers:
ret.update(self.servers[fstr](load))
# some *fs do not handle prefix. Ensure it is filtered
prefix = load.get('prefix', '').strip('/')
if prefix != '':
ret = [f for f in ret if f.startswith(prefix)]
return sorted(ret) | [
"def",
"file_list",
"(",
"self",
",",
"load",
")",
":",
"if",
"'env'",
"in",
"load",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"load",
".",
"pop",
"(",
"'env'",
")",
"ret",
"=",
"set",
"(",
")",
"if",
"'saltenv'",
"not",
"in",
"load",
":",
"re... | Return a list of files from the dominant environment | [
"Return",
"a",
"list",
"of",
"files",
"from",
"the",
"dominant",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L772-L794 | train |
saltstack/salt | salt/fileserver/__init__.py | Fileserver.symlink_list | def symlink_list(self, load):
'''
Return a list of symlinked files and dirs
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
ret = {}
if 'saltenv' not in load:
return {}
if not isinstance(load['saltenv'], six.string_types):
load['saltenv'] = six.text_type(load['saltenv'])
for fsb in self.backends(load.pop('fsbackend', None)):
symlstr = '{0}.symlink_list'.format(fsb)
if symlstr in self.servers:
ret = self.servers[symlstr](load)
# some *fs do not handle prefix. Ensure it is filtered
prefix = load.get('prefix', '').strip('/')
if prefix != '':
ret = dict([
(x, y) for x, y in six.iteritems(ret) if x.startswith(prefix)
])
return ret | python | def symlink_list(self, load):
'''
Return a list of symlinked files and dirs
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
ret = {}
if 'saltenv' not in load:
return {}
if not isinstance(load['saltenv'], six.string_types):
load['saltenv'] = six.text_type(load['saltenv'])
for fsb in self.backends(load.pop('fsbackend', None)):
symlstr = '{0}.symlink_list'.format(fsb)
if symlstr in self.servers:
ret = self.servers[symlstr](load)
# some *fs do not handle prefix. Ensure it is filtered
prefix = load.get('prefix', '').strip('/')
if prefix != '':
ret = dict([
(x, y) for x, y in six.iteritems(ret) if x.startswith(prefix)
])
return ret | [
"def",
"symlink_list",
"(",
"self",
",",
"load",
")",
":",
"if",
"'env'",
"in",
"load",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"load",
".",
"pop",
"(",
"'env'",
")",
"ret",
"=",
"{",
"}",
"if",
"'saltenv'",
"not",
"in",
"load",
":",
"return",... | Return a list of symlinked files and dirs | [
"Return",
"a",
"list",
"of",
"symlinked",
"files",
"and",
"dirs"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L847-L871 | train |
saltstack/salt | salt/fileserver/__init__.py | FSChan.send | def send(self, load, tries=None, timeout=None, raw=False): # pylint: disable=unused-argument
'''
Emulate the channel send method, the tries and timeout are not used
'''
if 'cmd' not in load:
log.error('Malformed request, no cmd: %s', load)
return {}
cmd = load['cmd'].lstrip('_')
if cmd in self.cmd_stub:
return self.cmd_stub[cmd]
if not hasattr(self.fs, cmd):
log.error('Malformed request, invalid cmd: %s', load)
return {}
return getattr(self.fs, cmd)(load) | python | def send(self, load, tries=None, timeout=None, raw=False): # pylint: disable=unused-argument
'''
Emulate the channel send method, the tries and timeout are not used
'''
if 'cmd' not in load:
log.error('Malformed request, no cmd: %s', load)
return {}
cmd = load['cmd'].lstrip('_')
if cmd in self.cmd_stub:
return self.cmd_stub[cmd]
if not hasattr(self.fs, cmd):
log.error('Malformed request, invalid cmd: %s', load)
return {}
return getattr(self.fs, cmd)(load) | [
"def",
"send",
"(",
"self",
",",
"load",
",",
"tries",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"raw",
"=",
"False",
")",
":",
"# pylint: disable=unused-argument",
"if",
"'cmd'",
"not",
"in",
"load",
":",
"log",
".",
"error",
"(",
"'Malformed reque... | Emulate the channel send method, the tries and timeout are not used | [
"Emulate",
"the",
"channel",
"send",
"method",
"the",
"tries",
"and",
"timeout",
"are",
"not",
"used"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L893-L906 | train |
saltstack/salt | salt/renderers/dson.py | render | def render(dson_input, saltenv='base', sls='', **kwargs):
'''
Accepts DSON data as a string or as a file object and runs it through the
JSON parser.
:rtype: A Python data structure
'''
if not isinstance(dson_input, six.string_types):
dson_input = dson_input.read()
log.debug('DSON input = %s', dson_input)
if dson_input.startswith('#!'):
dson_input = dson_input[(dson_input.find('\n') + 1):]
if not dson_input.strip():
return {}
return dson.loads(dson_input) | python | def render(dson_input, saltenv='base', sls='', **kwargs):
'''
Accepts DSON data as a string or as a file object and runs it through the
JSON parser.
:rtype: A Python data structure
'''
if not isinstance(dson_input, six.string_types):
dson_input = dson_input.read()
log.debug('DSON input = %s', dson_input)
if dson_input.startswith('#!'):
dson_input = dson_input[(dson_input.find('\n') + 1):]
if not dson_input.strip():
return {}
return dson.loads(dson_input) | [
"def",
"render",
"(",
"dson_input",
",",
"saltenv",
"=",
"'base'",
",",
"sls",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"dson_input",
",",
"six",
".",
"string_types",
")",
":",
"dson_input",
"=",
"dson_input",
".",
... | Accepts DSON data as a string or as a file object and runs it through the
JSON parser.
:rtype: A Python data structure | [
"Accepts",
"DSON",
"data",
"as",
"a",
"string",
"or",
"as",
"a",
"file",
"object",
"and",
"runs",
"it",
"through",
"the",
"JSON",
"parser",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/dson.py#L37-L53 | train |
saltstack/salt | salt/roster/scan.py | targets | def targets(tgt, tgt_type='glob', **kwargs):
'''
Return the targets from the flat yaml file, checks opts for location but
defaults to /etc/salt/roster
'''
rmatcher = RosterMatcher(tgt, tgt_type)
return rmatcher.targets() | python | def targets(tgt, tgt_type='glob', **kwargs):
'''
Return the targets from the flat yaml file, checks opts for location but
defaults to /etc/salt/roster
'''
rmatcher = RosterMatcher(tgt, tgt_type)
return rmatcher.targets() | [
"def",
"targets",
"(",
"tgt",
",",
"tgt_type",
"=",
"'glob'",
",",
"*",
"*",
"kwargs",
")",
":",
"rmatcher",
"=",
"RosterMatcher",
"(",
"tgt",
",",
"tgt_type",
")",
"return",
"rmatcher",
".",
"targets",
"(",
")"
] | Return the targets from the flat yaml file, checks opts for location but
defaults to /etc/salt/roster | [
"Return",
"the",
"targets",
"from",
"the",
"flat",
"yaml",
"file",
"checks",
"opts",
"for",
"location",
"but",
"defaults",
"to",
"/",
"etc",
"/",
"salt",
"/",
"roster"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/scan.py#L23-L29 | train |
saltstack/salt | salt/roster/scan.py | RosterMatcher.targets | def targets(self):
'''
Return ip addrs based on netmask, sitting in the "glob" spot because
it is the default
'''
addrs = ()
ret = {}
ports = __opts__['ssh_scan_ports']
if not isinstance(ports, list):
# Comma-separate list of integers
ports = list(map(int, six.text_type(ports).split(',')))
try:
addrs = [ipaddress.ip_address(self.tgt)]
except ValueError:
try:
addrs = ipaddress.ip_network(self.tgt).hosts()
except ValueError:
pass
for addr in addrs:
addr = six.text_type(addr)
ret[addr] = copy.deepcopy(__opts__.get('roster_defaults', {}))
log.trace('Scanning host: %s', addr)
for port in ports:
log.trace('Scanning port: %s', port)
try:
sock = salt.utils.network.get_socket(addr, socket.SOCK_STREAM)
sock.settimeout(float(__opts__['ssh_scan_timeout']))
sock.connect((addr, port))
sock.shutdown(socket.SHUT_RDWR)
sock.close()
ret[addr].update({'host': addr, 'port': port})
except socket.error:
pass
return ret | python | def targets(self):
'''
Return ip addrs based on netmask, sitting in the "glob" spot because
it is the default
'''
addrs = ()
ret = {}
ports = __opts__['ssh_scan_ports']
if not isinstance(ports, list):
# Comma-separate list of integers
ports = list(map(int, six.text_type(ports).split(',')))
try:
addrs = [ipaddress.ip_address(self.tgt)]
except ValueError:
try:
addrs = ipaddress.ip_network(self.tgt).hosts()
except ValueError:
pass
for addr in addrs:
addr = six.text_type(addr)
ret[addr] = copy.deepcopy(__opts__.get('roster_defaults', {}))
log.trace('Scanning host: %s', addr)
for port in ports:
log.trace('Scanning port: %s', port)
try:
sock = salt.utils.network.get_socket(addr, socket.SOCK_STREAM)
sock.settimeout(float(__opts__['ssh_scan_timeout']))
sock.connect((addr, port))
sock.shutdown(socket.SHUT_RDWR)
sock.close()
ret[addr].update({'host': addr, 'port': port})
except socket.error:
pass
return ret | [
"def",
"targets",
"(",
"self",
")",
":",
"addrs",
"=",
"(",
")",
"ret",
"=",
"{",
"}",
"ports",
"=",
"__opts__",
"[",
"'ssh_scan_ports'",
"]",
"if",
"not",
"isinstance",
"(",
"ports",
",",
"list",
")",
":",
"# Comma-separate list of integers",
"ports",
"... | Return ip addrs based on netmask, sitting in the "glob" spot because
it is the default | [
"Return",
"ip",
"addrs",
"based",
"on",
"netmask",
"sitting",
"in",
"the",
"glob",
"spot",
"because",
"it",
"is",
"the",
"default"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/scan.py#L40-L73 | train |
saltstack/salt | salt/modules/jsonnet.py | evaluate | def evaluate(contents, jsonnet_library_paths=None):
'''
Evaluate a jsonnet input string.
contents
Raw jsonnet string to evaluate.
jsonnet_library_paths
List of jsonnet library paths.
'''
if not jsonnet_library_paths:
jsonnet_library_paths = __salt__['config.option'](
'jsonnet.library_paths', ['.'])
return salt.utils.json.loads(
_jsonnet.evaluate_snippet(
"snippet",
contents,
import_callback=partial(
_import_callback, library_paths=jsonnet_library_paths))) | python | def evaluate(contents, jsonnet_library_paths=None):
'''
Evaluate a jsonnet input string.
contents
Raw jsonnet string to evaluate.
jsonnet_library_paths
List of jsonnet library paths.
'''
if not jsonnet_library_paths:
jsonnet_library_paths = __salt__['config.option'](
'jsonnet.library_paths', ['.'])
return salt.utils.json.loads(
_jsonnet.evaluate_snippet(
"snippet",
contents,
import_callback=partial(
_import_callback, library_paths=jsonnet_library_paths))) | [
"def",
"evaluate",
"(",
"contents",
",",
"jsonnet_library_paths",
"=",
"None",
")",
":",
"if",
"not",
"jsonnet_library_paths",
":",
"jsonnet_library_paths",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'jsonnet.library_paths'",
",",
"[",
"'.'",
"]",
")",
... | Evaluate a jsonnet input string.
contents
Raw jsonnet string to evaluate.
jsonnet_library_paths
List of jsonnet library paths. | [
"Evaluate",
"a",
"jsonnet",
"input",
"string",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jsonnet.py#L71-L90 | train |
saltstack/salt | salt/modules/solaris_fmadm.py | _parse_fmdump | def _parse_fmdump(output):
'''
Parses fmdump output
'''
result = []
output = output.split("\n")
# extract header
header = [field for field in output[0].lower().split(" ") if field]
del output[0]
# parse entries
for entry in output:
entry = [item for item in entry.split(" ") if item]
entry = ['{0} {1} {2}'.format(entry[0], entry[1], entry[2])] + entry[3:]
# prepare faults
fault = OrderedDict()
for field in header:
fault[field] = entry[header.index(field)]
result.append(fault)
return result | python | def _parse_fmdump(output):
'''
Parses fmdump output
'''
result = []
output = output.split("\n")
# extract header
header = [field for field in output[0].lower().split(" ") if field]
del output[0]
# parse entries
for entry in output:
entry = [item for item in entry.split(" ") if item]
entry = ['{0} {1} {2}'.format(entry[0], entry[1], entry[2])] + entry[3:]
# prepare faults
fault = OrderedDict()
for field in header:
fault[field] = entry[header.index(field)]
result.append(fault)
return result | [
"def",
"_parse_fmdump",
"(",
"output",
")",
":",
"result",
"=",
"[",
"]",
"output",
"=",
"output",
".",
"split",
"(",
"\"\\n\"",
")",
"# extract header",
"header",
"=",
"[",
"field",
"for",
"field",
"in",
"output",
"[",
"0",
"]",
".",
"lower",
"(",
"... | Parses fmdump output | [
"Parses",
"fmdump",
"output"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_fmadm.py#L63-L86 | train |
saltstack/salt | salt/modules/solaris_fmadm.py | _parse_fmdump_verbose | def _parse_fmdump_verbose(output):
'''
Parses fmdump verbose output
'''
result = []
output = output.split("\n")
fault = []
verbose_fault = {}
for line in output:
if line.startswith('TIME'):
fault.append(line)
if verbose_fault:
result.append(verbose_fault)
verbose_fault = {}
elif len(fault) == 1:
fault.append(line)
verbose_fault = _parse_fmdump("\n".join(fault))[0]
fault = []
elif verbose_fault:
if 'details' not in verbose_fault:
verbose_fault['details'] = ""
if line.strip() == '':
continue
verbose_fault['details'] = '{0}{1}\n'.format(
verbose_fault['details'],
line
)
if verbose_fault:
result.append(verbose_fault)
return result | python | def _parse_fmdump_verbose(output):
'''
Parses fmdump verbose output
'''
result = []
output = output.split("\n")
fault = []
verbose_fault = {}
for line in output:
if line.startswith('TIME'):
fault.append(line)
if verbose_fault:
result.append(verbose_fault)
verbose_fault = {}
elif len(fault) == 1:
fault.append(line)
verbose_fault = _parse_fmdump("\n".join(fault))[0]
fault = []
elif verbose_fault:
if 'details' not in verbose_fault:
verbose_fault['details'] = ""
if line.strip() == '':
continue
verbose_fault['details'] = '{0}{1}\n'.format(
verbose_fault['details'],
line
)
if verbose_fault:
result.append(verbose_fault)
return result | [
"def",
"_parse_fmdump_verbose",
"(",
"output",
")",
":",
"result",
"=",
"[",
"]",
"output",
"=",
"output",
".",
"split",
"(",
"\"\\n\"",
")",
"fault",
"=",
"[",
"]",
"verbose_fault",
"=",
"{",
"}",
"for",
"line",
"in",
"output",
":",
"if",
"line",
".... | Parses fmdump verbose output | [
"Parses",
"fmdump",
"verbose",
"output"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_fmadm.py#L89-L120 | train |
saltstack/salt | salt/modules/solaris_fmadm.py | _parse_fmadm_config | def _parse_fmadm_config(output):
'''
Parsbb fmdump/fmadm output
'''
result = []
output = output.split("\n")
# extract header
header = [field for field in output[0].lower().split(" ") if field]
del output[0]
# parse entries
for entry in output:
entry = [item for item in entry.split(" ") if item]
entry = entry[0:3] + [" ".join(entry[3:])]
# prepare component
component = OrderedDict()
for field in header:
component[field] = entry[header.index(field)]
result.append(component)
# keying
keyed_result = OrderedDict()
for component in result:
keyed_result[component['module']] = component
del keyed_result[component['module']]['module']
result = keyed_result
return result | python | def _parse_fmadm_config(output):
'''
Parsbb fmdump/fmadm output
'''
result = []
output = output.split("\n")
# extract header
header = [field for field in output[0].lower().split(" ") if field]
del output[0]
# parse entries
for entry in output:
entry = [item for item in entry.split(" ") if item]
entry = entry[0:3] + [" ".join(entry[3:])]
# prepare component
component = OrderedDict()
for field in header:
component[field] = entry[header.index(field)]
result.append(component)
# keying
keyed_result = OrderedDict()
for component in result:
keyed_result[component['module']] = component
del keyed_result[component['module']]['module']
result = keyed_result
return result | [
"def",
"_parse_fmadm_config",
"(",
"output",
")",
":",
"result",
"=",
"[",
"]",
"output",
"=",
"output",
".",
"split",
"(",
"\"\\n\"",
")",
"# extract header",
"header",
"=",
"[",
"field",
"for",
"field",
"in",
"output",
"[",
"0",
"]",
".",
"lower",
"(... | Parsbb fmdump/fmadm output | [
"Parsbb",
"fmdump",
"/",
"fmadm",
"output"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_fmadm.py#L123-L154 | train |
saltstack/salt | salt/modules/solaris_fmadm.py | _fmadm_action_fmri | def _fmadm_action_fmri(action, fmri):
'''
Internal function for fmadm.repqired, fmadm.replaced, fmadm.flush
'''
ret = {}
fmadm = _check_fmadm()
cmd = '{cmd} {action} {fmri}'.format(
cmd=fmadm,
action=action,
fmri=fmri
)
res = __salt__['cmd.run_all'](cmd)
retcode = res['retcode']
result = {}
if retcode != 0:
result['Error'] = res['stderr']
else:
result = True
return result | python | def _fmadm_action_fmri(action, fmri):
'''
Internal function for fmadm.repqired, fmadm.replaced, fmadm.flush
'''
ret = {}
fmadm = _check_fmadm()
cmd = '{cmd} {action} {fmri}'.format(
cmd=fmadm,
action=action,
fmri=fmri
)
res = __salt__['cmd.run_all'](cmd)
retcode = res['retcode']
result = {}
if retcode != 0:
result['Error'] = res['stderr']
else:
result = True
return result | [
"def",
"_fmadm_action_fmri",
"(",
"action",
",",
"fmri",
")",
":",
"ret",
"=",
"{",
"}",
"fmadm",
"=",
"_check_fmadm",
"(",
")",
"cmd",
"=",
"'{cmd} {action} {fmri}'",
".",
"format",
"(",
"cmd",
"=",
"fmadm",
",",
"action",
"=",
"action",
",",
"fmri",
... | Internal function for fmadm.repqired, fmadm.replaced, fmadm.flush | [
"Internal",
"function",
"for",
"fmadm",
".",
"repqired",
"fmadm",
".",
"replaced",
"fmadm",
".",
"flush"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_fmadm.py#L157-L176 | train |
saltstack/salt | salt/modules/solaris_fmadm.py | _parse_fmadm_faulty | def _parse_fmadm_faulty(output):
'''
Parse fmadm faulty output
'''
def _merge_data(summary, fault):
result = {}
uuid = summary['event-id']
del summary['event-id']
result[uuid] = OrderedDict()
result[uuid]['summary'] = summary
result[uuid]['fault'] = fault
return result
result = {}
summary = []
summary_data = {}
fault_data = {}
data_key = None
for line in output.split("\n"):
# we hit a divider
if line.startswith('-'):
if summary and summary_data and fault_data:
# we have data, store it and reset
result.update(_merge_data(summary_data, fault_data))
summary = []
summary_data = {}
fault_data = {}
continue
else:
# we don't have all data, colelct more
continue
# if we do not have the header, store it
if not summary:
summary.append(line)
continue
# if we have the header but no data, store the data and parse it
if summary and not summary_data:
summary.append(line)
summary_data = _parse_fmdump("\n".join(summary))[0]
continue
# if we have a header and data, assume the other lines are details
if summary and summary_data:
# if line starts with a whitespace and we already have a key, append
if line.startswith(' ') and data_key:
fault_data[data_key] = "{0}\n{1}".format(
fault_data[data_key],
line.strip()
)
# we have a key : value line, parse it
elif ':' in line:
line = line.split(':')
data_key = line[0].strip()
fault_data[data_key] = ":".join(line[1:]).strip()
# note: for some reason Chassis_id is lobbed ofter Platform, fix that here
if data_key == 'Platform':
fault_data['Chassis_id'] = fault_data[data_key][fault_data[data_key].index('Chassis_id'):].split(':')[-1].strip()
fault_data[data_key] = fault_data[data_key][0:fault_data[data_key].index('Chassis_id')].strip()
# we have data, store it and reset
result.update(_merge_data(summary_data, fault_data))
return result | python | def _parse_fmadm_faulty(output):
'''
Parse fmadm faulty output
'''
def _merge_data(summary, fault):
result = {}
uuid = summary['event-id']
del summary['event-id']
result[uuid] = OrderedDict()
result[uuid]['summary'] = summary
result[uuid]['fault'] = fault
return result
result = {}
summary = []
summary_data = {}
fault_data = {}
data_key = None
for line in output.split("\n"):
# we hit a divider
if line.startswith('-'):
if summary and summary_data and fault_data:
# we have data, store it and reset
result.update(_merge_data(summary_data, fault_data))
summary = []
summary_data = {}
fault_data = {}
continue
else:
# we don't have all data, colelct more
continue
# if we do not have the header, store it
if not summary:
summary.append(line)
continue
# if we have the header but no data, store the data and parse it
if summary and not summary_data:
summary.append(line)
summary_data = _parse_fmdump("\n".join(summary))[0]
continue
# if we have a header and data, assume the other lines are details
if summary and summary_data:
# if line starts with a whitespace and we already have a key, append
if line.startswith(' ') and data_key:
fault_data[data_key] = "{0}\n{1}".format(
fault_data[data_key],
line.strip()
)
# we have a key : value line, parse it
elif ':' in line:
line = line.split(':')
data_key = line[0].strip()
fault_data[data_key] = ":".join(line[1:]).strip()
# note: for some reason Chassis_id is lobbed ofter Platform, fix that here
if data_key == 'Platform':
fault_data['Chassis_id'] = fault_data[data_key][fault_data[data_key].index('Chassis_id'):].split(':')[-1].strip()
fault_data[data_key] = fault_data[data_key][0:fault_data[data_key].index('Chassis_id')].strip()
# we have data, store it and reset
result.update(_merge_data(summary_data, fault_data))
return result | [
"def",
"_parse_fmadm_faulty",
"(",
"output",
")",
":",
"def",
"_merge_data",
"(",
"summary",
",",
"fault",
")",
":",
"result",
"=",
"{",
"}",
"uuid",
"=",
"summary",
"[",
"'event-id'",
"]",
"del",
"summary",
"[",
"'event-id'",
"]",
"result",
"[",
"uuid",... | Parse fmadm faulty output | [
"Parse",
"fmadm",
"faulty",
"output"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_fmadm.py#L179-L246 | train |
saltstack/salt | salt/modules/solaris_fmadm.py | list_records | def list_records(after=None, before=None):
'''
Display fault management logs
after : string
filter events after time, see man fmdump for format
before : string
filter events before time, see man fmdump for format
CLI Example:
.. code-block:: bash
salt '*' fmadm.list
'''
ret = {}
fmdump = _check_fmdump()
cmd = '{cmd}{after}{before}'.format(
cmd=fmdump,
after=' -t {0}'.format(after) if after else '',
before=' -T {0}'.format(before) if before else ''
)
res = __salt__['cmd.run_all'](cmd)
retcode = res['retcode']
result = {}
if retcode != 0:
result['Error'] = 'error executing fmdump'
else:
result = _parse_fmdump(res['stdout'])
return result | python | def list_records(after=None, before=None):
'''
Display fault management logs
after : string
filter events after time, see man fmdump for format
before : string
filter events before time, see man fmdump for format
CLI Example:
.. code-block:: bash
salt '*' fmadm.list
'''
ret = {}
fmdump = _check_fmdump()
cmd = '{cmd}{after}{before}'.format(
cmd=fmdump,
after=' -t {0}'.format(after) if after else '',
before=' -T {0}'.format(before) if before else ''
)
res = __salt__['cmd.run_all'](cmd)
retcode = res['retcode']
result = {}
if retcode != 0:
result['Error'] = 'error executing fmdump'
else:
result = _parse_fmdump(res['stdout'])
return result | [
"def",
"list_records",
"(",
"after",
"=",
"None",
",",
"before",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"fmdump",
"=",
"_check_fmdump",
"(",
")",
"cmd",
"=",
"'{cmd}{after}{before}'",
".",
"format",
"(",
"cmd",
"=",
"fmdump",
",",
"after",
"=",
... | Display fault management logs
after : string
filter events after time, see man fmdump for format
before : string
filter events before time, see man fmdump for format
CLI Example:
.. code-block:: bash
salt '*' fmadm.list | [
"Display",
"fault",
"management",
"logs"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_fmadm.py#L249-L280 | train |
saltstack/salt | salt/modules/solaris_fmadm.py | show | def show(uuid):
'''
Display log details
uuid: string
uuid of fault
CLI Example:
.. code-block:: bash
salt '*' fmadm.show 11b4070f-4358-62fa-9e1e-998f485977e1
'''
ret = {}
fmdump = _check_fmdump()
cmd = '{cmd} -u {uuid} -V'.format(
cmd=fmdump,
uuid=uuid
)
res = __salt__['cmd.run_all'](cmd)
retcode = res['retcode']
result = {}
if retcode != 0:
result['Error'] = 'error executing fmdump'
else:
result = _parse_fmdump_verbose(res['stdout'])
return result | python | def show(uuid):
'''
Display log details
uuid: string
uuid of fault
CLI Example:
.. code-block:: bash
salt '*' fmadm.show 11b4070f-4358-62fa-9e1e-998f485977e1
'''
ret = {}
fmdump = _check_fmdump()
cmd = '{cmd} -u {uuid} -V'.format(
cmd=fmdump,
uuid=uuid
)
res = __salt__['cmd.run_all'](cmd)
retcode = res['retcode']
result = {}
if retcode != 0:
result['Error'] = 'error executing fmdump'
else:
result = _parse_fmdump_verbose(res['stdout'])
return result | [
"def",
"show",
"(",
"uuid",
")",
":",
"ret",
"=",
"{",
"}",
"fmdump",
"=",
"_check_fmdump",
"(",
")",
"cmd",
"=",
"'{cmd} -u {uuid} -V'",
".",
"format",
"(",
"cmd",
"=",
"fmdump",
",",
"uuid",
"=",
"uuid",
")",
"res",
"=",
"__salt__",
"[",
"'cmd.run_... | Display log details
uuid: string
uuid of fault
CLI Example:
.. code-block:: bash
salt '*' fmadm.show 11b4070f-4358-62fa-9e1e-998f485977e1 | [
"Display",
"log",
"details"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_fmadm.py#L283-L310 | train |
saltstack/salt | salt/modules/solaris_fmadm.py | config | def config():
'''
Display fault manager configuration
CLI Example:
.. code-block:: bash
salt '*' fmadm.config
'''
ret = {}
fmadm = _check_fmadm()
cmd = '{cmd} config'.format(
cmd=fmadm
)
res = __salt__['cmd.run_all'](cmd)
retcode = res['retcode']
result = {}
if retcode != 0:
result['Error'] = 'error executing fmadm config'
else:
result = _parse_fmadm_config(res['stdout'])
return result | python | def config():
'''
Display fault manager configuration
CLI Example:
.. code-block:: bash
salt '*' fmadm.config
'''
ret = {}
fmadm = _check_fmadm()
cmd = '{cmd} config'.format(
cmd=fmadm
)
res = __salt__['cmd.run_all'](cmd)
retcode = res['retcode']
result = {}
if retcode != 0:
result['Error'] = 'error executing fmadm config'
else:
result = _parse_fmadm_config(res['stdout'])
return result | [
"def",
"config",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"fmadm",
"=",
"_check_fmadm",
"(",
")",
"cmd",
"=",
"'{cmd} config'",
".",
"format",
"(",
"cmd",
"=",
"fmadm",
")",
"res",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
")",
"retcode",
... | Display fault manager configuration
CLI Example:
.. code-block:: bash
salt '*' fmadm.config | [
"Display",
"fault",
"manager",
"configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_fmadm.py#L313-L336 | train |
saltstack/salt | salt/modules/solaris_fmadm.py | load | def load(path):
'''
Load specified fault manager module
path: string
path of fault manager module
CLI Example:
.. code-block:: bash
salt '*' fmadm.load /module/path
'''
ret = {}
fmadm = _check_fmadm()
cmd = '{cmd} load {path}'.format(
cmd=fmadm,
path=path
)
res = __salt__['cmd.run_all'](cmd)
retcode = res['retcode']
result = {}
if retcode != 0:
result['Error'] = res['stderr']
else:
result = True
return result | python | def load(path):
'''
Load specified fault manager module
path: string
path of fault manager module
CLI Example:
.. code-block:: bash
salt '*' fmadm.load /module/path
'''
ret = {}
fmadm = _check_fmadm()
cmd = '{cmd} load {path}'.format(
cmd=fmadm,
path=path
)
res = __salt__['cmd.run_all'](cmd)
retcode = res['retcode']
result = {}
if retcode != 0:
result['Error'] = res['stderr']
else:
result = True
return result | [
"def",
"load",
"(",
"path",
")",
":",
"ret",
"=",
"{",
"}",
"fmadm",
"=",
"_check_fmadm",
"(",
")",
"cmd",
"=",
"'{cmd} load {path}'",
".",
"format",
"(",
"cmd",
"=",
"fmadm",
",",
"path",
"=",
"path",
")",
"res",
"=",
"__salt__",
"[",
"'cmd.run_all'... | Load specified fault manager module
path: string
path of fault manager module
CLI Example:
.. code-block:: bash
salt '*' fmadm.load /module/path | [
"Load",
"specified",
"fault",
"manager",
"module"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_fmadm.py#L339-L366 | train |
saltstack/salt | salt/modules/solaris_fmadm.py | unload | def unload(module):
'''
Unload specified fault manager module
module: string
module to unload
CLI Example:
.. code-block:: bash
salt '*' fmadm.unload software-response
'''
ret = {}
fmadm = _check_fmadm()
cmd = '{cmd} unload {module}'.format(
cmd=fmadm,
module=module
)
res = __salt__['cmd.run_all'](cmd)
retcode = res['retcode']
result = {}
if retcode != 0:
result['Error'] = res['stderr']
else:
result = True
return result | python | def unload(module):
'''
Unload specified fault manager module
module: string
module to unload
CLI Example:
.. code-block:: bash
salt '*' fmadm.unload software-response
'''
ret = {}
fmadm = _check_fmadm()
cmd = '{cmd} unload {module}'.format(
cmd=fmadm,
module=module
)
res = __salt__['cmd.run_all'](cmd)
retcode = res['retcode']
result = {}
if retcode != 0:
result['Error'] = res['stderr']
else:
result = True
return result | [
"def",
"unload",
"(",
"module",
")",
":",
"ret",
"=",
"{",
"}",
"fmadm",
"=",
"_check_fmadm",
"(",
")",
"cmd",
"=",
"'{cmd} unload {module}'",
".",
"format",
"(",
"cmd",
"=",
"fmadm",
",",
"module",
"=",
"module",
")",
"res",
"=",
"__salt__",
"[",
"'... | Unload specified fault manager module
module: string
module to unload
CLI Example:
.. code-block:: bash
salt '*' fmadm.unload software-response | [
"Unload",
"specified",
"fault",
"manager",
"module"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_fmadm.py#L369-L396 | train |
saltstack/salt | salt/modules/solaris_fmadm.py | reset | def reset(module, serd=None):
'''
Reset module or sub-component
module: string
module to unload
serd : string
serd sub module
CLI Example:
.. code-block:: bash
salt '*' fmadm.reset software-response
'''
ret = {}
fmadm = _check_fmadm()
cmd = '{cmd} reset {serd}{module}'.format(
cmd=fmadm,
serd='-s {0} '.format(serd) if serd else '',
module=module
)
res = __salt__['cmd.run_all'](cmd)
retcode = res['retcode']
result = {}
if retcode != 0:
result['Error'] = res['stderr']
else:
result = True
return result | python | def reset(module, serd=None):
'''
Reset module or sub-component
module: string
module to unload
serd : string
serd sub module
CLI Example:
.. code-block:: bash
salt '*' fmadm.reset software-response
'''
ret = {}
fmadm = _check_fmadm()
cmd = '{cmd} reset {serd}{module}'.format(
cmd=fmadm,
serd='-s {0} '.format(serd) if serd else '',
module=module
)
res = __salt__['cmd.run_all'](cmd)
retcode = res['retcode']
result = {}
if retcode != 0:
result['Error'] = res['stderr']
else:
result = True
return result | [
"def",
"reset",
"(",
"module",
",",
"serd",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"fmadm",
"=",
"_check_fmadm",
"(",
")",
"cmd",
"=",
"'{cmd} reset {serd}{module}'",
".",
"format",
"(",
"cmd",
"=",
"fmadm",
",",
"serd",
"=",
"'-s {0} '",
".",
... | Reset module or sub-component
module: string
module to unload
serd : string
serd sub module
CLI Example:
.. code-block:: bash
salt '*' fmadm.reset software-response | [
"Reset",
"module",
"or",
"sub",
"-",
"component"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_fmadm.py#L399-L429 | train |
saltstack/salt | salt/modules/solaris_fmadm.py | faulty | def faulty():
'''
Display list of faulty resources
CLI Example:
.. code-block:: bash
salt '*' fmadm.faulty
'''
fmadm = _check_fmadm()
cmd = '{cmd} faulty'.format(
cmd=fmadm,
)
res = __salt__['cmd.run_all'](cmd)
result = {}
if res['stdout'] == '':
result = False
else:
result = _parse_fmadm_faulty(res['stdout'])
return result | python | def faulty():
'''
Display list of faulty resources
CLI Example:
.. code-block:: bash
salt '*' fmadm.faulty
'''
fmadm = _check_fmadm()
cmd = '{cmd} faulty'.format(
cmd=fmadm,
)
res = __salt__['cmd.run_all'](cmd)
result = {}
if res['stdout'] == '':
result = False
else:
result = _parse_fmadm_faulty(res['stdout'])
return result | [
"def",
"faulty",
"(",
")",
":",
"fmadm",
"=",
"_check_fmadm",
"(",
")",
"cmd",
"=",
"'{cmd} faulty'",
".",
"format",
"(",
"cmd",
"=",
"fmadm",
",",
")",
"res",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
")",
"result",
"=",
"{",
"}",
"i... | Display list of faulty resources
CLI Example:
.. code-block:: bash
salt '*' fmadm.faulty | [
"Display",
"list",
"of",
"faulty",
"resources"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_fmadm.py#L496-L517 | train |
saltstack/salt | salt/modules/parted_partition.py | _validate_device | def _validate_device(device):
'''
Ensure the device name supplied is valid in a manner similar to the
`exists` function, but raise errors on invalid input rather than return
False.
This function only validates a block device, it does not check if the block
device is a drive or a partition or a filesystem, etc.
'''
if os.path.exists(device):
dev = os.stat(device).st_mode
if stat.S_ISBLK(dev):
return
raise CommandExecutionError(
'Invalid device passed to partition module.'
) | python | def _validate_device(device):
'''
Ensure the device name supplied is valid in a manner similar to the
`exists` function, but raise errors on invalid input rather than return
False.
This function only validates a block device, it does not check if the block
device is a drive or a partition or a filesystem, etc.
'''
if os.path.exists(device):
dev = os.stat(device).st_mode
if stat.S_ISBLK(dev):
return
raise CommandExecutionError(
'Invalid device passed to partition module.'
) | [
"def",
"_validate_device",
"(",
"device",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"device",
")",
":",
"dev",
"=",
"os",
".",
"stat",
"(",
"device",
")",
".",
"st_mode",
"if",
"stat",
".",
"S_ISBLK",
"(",
"dev",
")",
":",
"return",
... | Ensure the device name supplied is valid in a manner similar to the
`exists` function, but raise errors on invalid input rather than return
False.
This function only validates a block device, it does not check if the block
device is a drive or a partition or a filesystem, etc. | [
"Ensure",
"the",
"device",
"name",
"supplied",
"is",
"valid",
"in",
"a",
"manner",
"similar",
"to",
"the",
"exists",
"function",
"but",
"raise",
"errors",
"on",
"invalid",
"input",
"rather",
"than",
"return",
"False",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L80-L97 | train |
saltstack/salt | salt/modules/parted_partition.py | _validate_partition_boundary | def _validate_partition_boundary(boundary):
'''
Ensure valid partition boundaries are supplied.
'''
boundary = six.text_type(boundary)
match = re.search(r'^([\d.]+)(\D*)$', boundary)
if match:
unit = match.group(2)
if not unit or unit in VALID_UNITS:
return
raise CommandExecutionError(
'Invalid partition boundary passed: "{0}"'.format(boundary)
) | python | def _validate_partition_boundary(boundary):
'''
Ensure valid partition boundaries are supplied.
'''
boundary = six.text_type(boundary)
match = re.search(r'^([\d.]+)(\D*)$', boundary)
if match:
unit = match.group(2)
if not unit or unit in VALID_UNITS:
return
raise CommandExecutionError(
'Invalid partition boundary passed: "{0}"'.format(boundary)
) | [
"def",
"_validate_partition_boundary",
"(",
"boundary",
")",
":",
"boundary",
"=",
"six",
".",
"text_type",
"(",
"boundary",
")",
"match",
"=",
"re",
".",
"search",
"(",
"r'^([\\d.]+)(\\D*)$'",
",",
"boundary",
")",
"if",
"match",
":",
"unit",
"=",
"match",
... | Ensure valid partition boundaries are supplied. | [
"Ensure",
"valid",
"partition",
"boundaries",
"are",
"supplied",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L100-L112 | train |
saltstack/salt | salt/modules/parted_partition.py | probe | def probe(*devices):
'''
Ask the kernel to update its local partition data. When no args are
specified all block devices are tried.
Caution: Generally only works on devices with no mounted partitions and
may take a long time to return if specified devices are in use.
CLI Examples:
.. code-block:: bash
salt '*' partition.probe
salt '*' partition.probe /dev/sda
salt '*' partition.probe /dev/sda /dev/sdb
'''
for device in devices:
_validate_device(device)
cmd = 'partprobe -- {0}'.format(" ".join(devices))
out = __salt__['cmd.run'](cmd).splitlines()
return out | python | def probe(*devices):
'''
Ask the kernel to update its local partition data. When no args are
specified all block devices are tried.
Caution: Generally only works on devices with no mounted partitions and
may take a long time to return if specified devices are in use.
CLI Examples:
.. code-block:: bash
salt '*' partition.probe
salt '*' partition.probe /dev/sda
salt '*' partition.probe /dev/sda /dev/sdb
'''
for device in devices:
_validate_device(device)
cmd = 'partprobe -- {0}'.format(" ".join(devices))
out = __salt__['cmd.run'](cmd).splitlines()
return out | [
"def",
"probe",
"(",
"*",
"devices",
")",
":",
"for",
"device",
"in",
"devices",
":",
"_validate_device",
"(",
"device",
")",
"cmd",
"=",
"'partprobe -- {0}'",
".",
"format",
"(",
"\" \"",
".",
"join",
"(",
"devices",
")",
")",
"out",
"=",
"__salt__",
... | Ask the kernel to update its local partition data. When no args are
specified all block devices are tried.
Caution: Generally only works on devices with no mounted partitions and
may take a long time to return if specified devices are in use.
CLI Examples:
.. code-block:: bash
salt '*' partition.probe
salt '*' partition.probe /dev/sda
salt '*' partition.probe /dev/sda /dev/sdb | [
"Ask",
"the",
"kernel",
"to",
"update",
"its",
"local",
"partition",
"data",
".",
"When",
"no",
"args",
"are",
"specified",
"all",
"block",
"devices",
"are",
"tried",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L115-L136 | train |
saltstack/salt | salt/modules/parted_partition.py | list_ | def list_(device, unit=None):
'''
Prints partition information of given <device>
CLI Examples:
.. code-block:: bash
salt '*' partition.list /dev/sda
salt '*' partition.list /dev/sda unit=s
salt '*' partition.list /dev/sda unit=kB
'''
_validate_device(device)
if unit:
if unit not in VALID_UNITS:
raise CommandExecutionError(
'Invalid unit passed to partition.part_list'
)
cmd = 'parted -m -s {0} unit {1} print'.format(device, unit)
else:
cmd = 'parted -m -s {0} print'.format(device)
out = __salt__['cmd.run_stdout'](cmd).splitlines()
ret = {'info': {}, 'partitions': {}}
mode = 'info'
for line in out:
if line in ('BYT;', 'CHS;', 'CYL;'):
continue
cols = line.rstrip(';').split(':')
if mode == 'info':
if 7 <= len(cols) <= 8:
ret['info'] = {
'disk': cols[0],
'size': cols[1],
'interface': cols[2],
'logical sector': cols[3],
'physical sector': cols[4],
'partition table': cols[5],
'model': cols[6]}
if len(cols) == 8:
ret['info']['disk flags'] = cols[7]
# Older parted (2.x) doesn't show disk flags in the 'print'
# output, and will return a 7-column output for the info
# line. In these cases we just leave this field out of the
# return dict.
mode = 'partitions'
else:
raise CommandExecutionError(
'Problem encountered while parsing output from parted')
else:
# Parted (v3.1) have a variable field list in machine
# readable output:
#
# number:start:end:[size:]([file system:name:flags;]|[free;])
#
# * If units are in CHS 'size' is not printed.
# * If is a logical partition with PED_PARTITION_FREESPACE
# set, the last three fields are replaced with the
# 'free' text.
#
fields = ['number', 'start', 'end']
if unit != 'chs':
fields.append('size')
if cols[-1] == 'free':
# Drop the last element from the list
cols.pop()
else:
fields.extend(['file system', 'name', 'flags'])
if len(fields) == len(cols):
ret['partitions'][cols[0]] = dict(six.moves.zip(fields, cols))
else:
raise CommandExecutionError(
'Problem encountered while parsing output from parted')
return ret | python | def list_(device, unit=None):
'''
Prints partition information of given <device>
CLI Examples:
.. code-block:: bash
salt '*' partition.list /dev/sda
salt '*' partition.list /dev/sda unit=s
salt '*' partition.list /dev/sda unit=kB
'''
_validate_device(device)
if unit:
if unit not in VALID_UNITS:
raise CommandExecutionError(
'Invalid unit passed to partition.part_list'
)
cmd = 'parted -m -s {0} unit {1} print'.format(device, unit)
else:
cmd = 'parted -m -s {0} print'.format(device)
out = __salt__['cmd.run_stdout'](cmd).splitlines()
ret = {'info': {}, 'partitions': {}}
mode = 'info'
for line in out:
if line in ('BYT;', 'CHS;', 'CYL;'):
continue
cols = line.rstrip(';').split(':')
if mode == 'info':
if 7 <= len(cols) <= 8:
ret['info'] = {
'disk': cols[0],
'size': cols[1],
'interface': cols[2],
'logical sector': cols[3],
'physical sector': cols[4],
'partition table': cols[5],
'model': cols[6]}
if len(cols) == 8:
ret['info']['disk flags'] = cols[7]
# Older parted (2.x) doesn't show disk flags in the 'print'
# output, and will return a 7-column output for the info
# line. In these cases we just leave this field out of the
# return dict.
mode = 'partitions'
else:
raise CommandExecutionError(
'Problem encountered while parsing output from parted')
else:
# Parted (v3.1) have a variable field list in machine
# readable output:
#
# number:start:end:[size:]([file system:name:flags;]|[free;])
#
# * If units are in CHS 'size' is not printed.
# * If is a logical partition with PED_PARTITION_FREESPACE
# set, the last three fields are replaced with the
# 'free' text.
#
fields = ['number', 'start', 'end']
if unit != 'chs':
fields.append('size')
if cols[-1] == 'free':
# Drop the last element from the list
cols.pop()
else:
fields.extend(['file system', 'name', 'flags'])
if len(fields) == len(cols):
ret['partitions'][cols[0]] = dict(six.moves.zip(fields, cols))
else:
raise CommandExecutionError(
'Problem encountered while parsing output from parted')
return ret | [
"def",
"list_",
"(",
"device",
",",
"unit",
"=",
"None",
")",
":",
"_validate_device",
"(",
"device",
")",
"if",
"unit",
":",
"if",
"unit",
"not",
"in",
"VALID_UNITS",
":",
"raise",
"CommandExecutionError",
"(",
"'Invalid unit passed to partition.part_list'",
")... | Prints partition information of given <device>
CLI Examples:
.. code-block:: bash
salt '*' partition.list /dev/sda
salt '*' partition.list /dev/sda unit=s
salt '*' partition.list /dev/sda unit=kB | [
"Prints",
"partition",
"information",
"of",
"given",
"<device",
">"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L139-L213 | train |
saltstack/salt | salt/modules/parted_partition.py | align_check | def align_check(device, part_type, partition):
'''
Check if partition satisfies the alignment constraint of part_type.
Type must be "minimal" or "optimal".
CLI Example:
.. code-block:: bash
salt '*' partition.align_check /dev/sda minimal 1
'''
_validate_device(device)
if part_type not in set(['minimal', 'optimal']):
raise CommandExecutionError(
'Invalid part_type passed to partition.align_check'
)
try:
int(partition)
except Exception:
raise CommandExecutionError(
'Invalid partition passed to partition.align_check'
)
cmd = 'parted -m {0} align-check {1} {2}'.format(
device, part_type, partition
)
out = __salt__['cmd.run'](cmd).splitlines()
return out | python | def align_check(device, part_type, partition):
'''
Check if partition satisfies the alignment constraint of part_type.
Type must be "minimal" or "optimal".
CLI Example:
.. code-block:: bash
salt '*' partition.align_check /dev/sda minimal 1
'''
_validate_device(device)
if part_type not in set(['minimal', 'optimal']):
raise CommandExecutionError(
'Invalid part_type passed to partition.align_check'
)
try:
int(partition)
except Exception:
raise CommandExecutionError(
'Invalid partition passed to partition.align_check'
)
cmd = 'parted -m {0} align-check {1} {2}'.format(
device, part_type, partition
)
out = __salt__['cmd.run'](cmd).splitlines()
return out | [
"def",
"align_check",
"(",
"device",
",",
"part_type",
",",
"partition",
")",
":",
"_validate_device",
"(",
"device",
")",
"if",
"part_type",
"not",
"in",
"set",
"(",
"[",
"'minimal'",
",",
"'optimal'",
"]",
")",
":",
"raise",
"CommandExecutionError",
"(",
... | Check if partition satisfies the alignment constraint of part_type.
Type must be "minimal" or "optimal".
CLI Example:
.. code-block:: bash
salt '*' partition.align_check /dev/sda minimal 1 | [
"Check",
"if",
"partition",
"satisfies",
"the",
"alignment",
"constraint",
"of",
"part_type",
".",
"Type",
"must",
"be",
"minimal",
"or",
"optimal",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L216-L245 | train |
saltstack/salt | salt/modules/parted_partition.py | cp | def cp(device, from_minor, to_minor): # pylint: disable=C0103
'''
Copies the file system on the partition <from-minor> to partition
<to-minor>, deleting the original contents of the destination
partition.
CLI Example:
.. code-block:: bash
salt '*' partition.cp /dev/sda 2 3
'''
_validate_device(device)
try:
int(from_minor)
int(to_minor)
except Exception:
raise CommandExecutionError(
'Invalid minor number passed to partition.cp'
)
cmd = 'parted -m -s {0} cp {1} {2}'.format(device, from_minor, to_minor)
out = __salt__['cmd.run'](cmd).splitlines()
return out | python | def cp(device, from_minor, to_minor): # pylint: disable=C0103
'''
Copies the file system on the partition <from-minor> to partition
<to-minor>, deleting the original contents of the destination
partition.
CLI Example:
.. code-block:: bash
salt '*' partition.cp /dev/sda 2 3
'''
_validate_device(device)
try:
int(from_minor)
int(to_minor)
except Exception:
raise CommandExecutionError(
'Invalid minor number passed to partition.cp'
)
cmd = 'parted -m -s {0} cp {1} {2}'.format(device, from_minor, to_minor)
out = __salt__['cmd.run'](cmd).splitlines()
return out | [
"def",
"cp",
"(",
"device",
",",
"from_minor",
",",
"to_minor",
")",
":",
"# pylint: disable=C0103",
"_validate_device",
"(",
"device",
")",
"try",
":",
"int",
"(",
"from_minor",
")",
"int",
"(",
"to_minor",
")",
"except",
"Exception",
":",
"raise",
"Command... | Copies the file system on the partition <from-minor> to partition
<to-minor>, deleting the original contents of the destination
partition.
CLI Example:
.. code-block:: bash
salt '*' partition.cp /dev/sda 2 3 | [
"Copies",
"the",
"file",
"system",
"on",
"the",
"partition",
"<from",
"-",
"minor",
">",
"to",
"partition",
"<to",
"-",
"minor",
">",
"deleting",
"the",
"original",
"contents",
"of",
"the",
"destination",
"partition",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L272-L296 | train |
saltstack/salt | salt/modules/parted_partition.py | set_id | def set_id(device, minor, system_id):
'''
Sets the system ID for the partition. Some typical values are::
b: FAT32 (vfat)
7: HPFS/NTFS
82: Linux Swap
83: Linux
8e: Linux LVM
fd: Linux RAID Auto
CLI Example:
.. code-block:: bash
salt '*' partition.set_id /dev/sda 1 83
'''
_validate_device(device)
try:
int(minor)
except Exception:
raise CommandExecutionError(
'Invalid minor number passed to partition.set_id'
)
if system_id not in system_types():
raise CommandExecutionError(
'Invalid system_id passed to partition.set_id'
)
cmd = 'sfdisk --change-id {0} {1} {2}'.format(device, minor, system_id)
out = __salt__['cmd.run'](cmd).splitlines()
return out | python | def set_id(device, minor, system_id):
'''
Sets the system ID for the partition. Some typical values are::
b: FAT32 (vfat)
7: HPFS/NTFS
82: Linux Swap
83: Linux
8e: Linux LVM
fd: Linux RAID Auto
CLI Example:
.. code-block:: bash
salt '*' partition.set_id /dev/sda 1 83
'''
_validate_device(device)
try:
int(minor)
except Exception:
raise CommandExecutionError(
'Invalid minor number passed to partition.set_id'
)
if system_id not in system_types():
raise CommandExecutionError(
'Invalid system_id passed to partition.set_id'
)
cmd = 'sfdisk --change-id {0} {1} {2}'.format(device, minor, system_id)
out = __salt__['cmd.run'](cmd).splitlines()
return out | [
"def",
"set_id",
"(",
"device",
",",
"minor",
",",
"system_id",
")",
":",
"_validate_device",
"(",
"device",
")",
"try",
":",
"int",
"(",
"minor",
")",
"except",
"Exception",
":",
"raise",
"CommandExecutionError",
"(",
"'Invalid minor number passed to partition.se... | Sets the system ID for the partition. Some typical values are::
b: FAT32 (vfat)
7: HPFS/NTFS
82: Linux Swap
83: Linux
8e: Linux LVM
fd: Linux RAID Auto
CLI Example:
.. code-block:: bash
salt '*' partition.set_id /dev/sda 1 83 | [
"Sets",
"the",
"system",
"ID",
"for",
"the",
"partition",
".",
"Some",
"typical",
"values",
"are",
"::"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L330-L363 | train |
saltstack/salt | salt/modules/parted_partition.py | system_types | def system_types():
'''
List the system types that are supported by the installed version of sfdisk
CLI Example:
.. code-block:: bash
salt '*' partition.system_types
'''
ret = {}
for line in __salt__['cmd.run']('sfdisk -T').splitlines():
if not line:
continue
if line.startswith('Id'):
continue
comps = line.strip().split()
ret[comps[0]] = comps[1]
return ret | python | def system_types():
'''
List the system types that are supported by the installed version of sfdisk
CLI Example:
.. code-block:: bash
salt '*' partition.system_types
'''
ret = {}
for line in __salt__['cmd.run']('sfdisk -T').splitlines():
if not line:
continue
if line.startswith('Id'):
continue
comps = line.strip().split()
ret[comps[0]] = comps[1]
return ret | [
"def",
"system_types",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"line",
"in",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'sfdisk -T'",
")",
".",
"splitlines",
"(",
")",
":",
"if",
"not",
"line",
":",
"continue",
"if",
"line",
".",
"startswith",
"(",... | List the system types that are supported by the installed version of sfdisk
CLI Example:
.. code-block:: bash
salt '*' partition.system_types | [
"List",
"the",
"system",
"types",
"that",
"are",
"supported",
"by",
"the",
"installed",
"version",
"of",
"sfdisk"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L366-L384 | train |
saltstack/salt | salt/modules/parted_partition.py | mkfs | def mkfs(device, fs_type):
'''
Makes a file system <fs_type> on partition <device>, destroying all data
that resides on that partition. <fs_type> must be one of "ext2", "fat32",
"fat16", "linux-swap" or "reiserfs" (if libreiserfs is installed)
CLI Example:
.. code-block:: bash
salt '*' partition.mkfs /dev/sda2 fat32
'''
_validate_device(device)
if not _is_fstype(fs_type):
raise CommandExecutionError('Invalid fs_type passed to partition.mkfs')
if fs_type == 'NTFS':
fs_type = 'ntfs'
if fs_type == 'linux-swap':
mkfs_cmd = 'mkswap'
else:
mkfs_cmd = 'mkfs.{0}'.format(fs_type)
if not salt.utils.path.which(mkfs_cmd):
return 'Error: {0} is unavailable.'.format(mkfs_cmd)
cmd = '{0} {1}'.format(mkfs_cmd, device)
out = __salt__['cmd.run'](cmd).splitlines()
return out | python | def mkfs(device, fs_type):
'''
Makes a file system <fs_type> on partition <device>, destroying all data
that resides on that partition. <fs_type> must be one of "ext2", "fat32",
"fat16", "linux-swap" or "reiserfs" (if libreiserfs is installed)
CLI Example:
.. code-block:: bash
salt '*' partition.mkfs /dev/sda2 fat32
'''
_validate_device(device)
if not _is_fstype(fs_type):
raise CommandExecutionError('Invalid fs_type passed to partition.mkfs')
if fs_type == 'NTFS':
fs_type = 'ntfs'
if fs_type == 'linux-swap':
mkfs_cmd = 'mkswap'
else:
mkfs_cmd = 'mkfs.{0}'.format(fs_type)
if not salt.utils.path.which(mkfs_cmd):
return 'Error: {0} is unavailable.'.format(mkfs_cmd)
cmd = '{0} {1}'.format(mkfs_cmd, device)
out = __salt__['cmd.run'](cmd).splitlines()
return out | [
"def",
"mkfs",
"(",
"device",
",",
"fs_type",
")",
":",
"_validate_device",
"(",
"device",
")",
"if",
"not",
"_is_fstype",
"(",
"fs_type",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'Invalid fs_type passed to partition.mkfs'",
")",
"if",
"fs_type",
"==",
... | Makes a file system <fs_type> on partition <device>, destroying all data
that resides on that partition. <fs_type> must be one of "ext2", "fat32",
"fat16", "linux-swap" or "reiserfs" (if libreiserfs is installed)
CLI Example:
.. code-block:: bash
salt '*' partition.mkfs /dev/sda2 fat32 | [
"Makes",
"a",
"file",
"system",
"<fs_type",
">",
"on",
"partition",
"<device",
">",
"destroying",
"all",
"data",
"that",
"resides",
"on",
"that",
"partition",
".",
"<fs_type",
">",
"must",
"be",
"one",
"of",
"ext2",
"fat32",
"fat16",
"linux",
"-",
"swap",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L397-L426 | train |
saltstack/salt | salt/modules/parted_partition.py | mklabel | def mklabel(device, label_type):
'''
Create a new disklabel (partition table) of label_type.
Type should be one of "aix", "amiga", "bsd", "dvh", "gpt", "loop", "mac",
"msdos", "pc98", or "sun".
CLI Example:
.. code-block:: bash
salt '*' partition.mklabel /dev/sda msdos
'''
if label_type not in set([
'aix', 'amiga', 'bsd', 'dvh', 'gpt', 'loop', 'mac', 'msdos', 'pc98', 'sun'
]):
raise CommandExecutionError(
'Invalid label_type passed to partition.mklabel'
)
cmd = ('parted', '-m', '-s', device, 'mklabel', label_type)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return out | python | def mklabel(device, label_type):
'''
Create a new disklabel (partition table) of label_type.
Type should be one of "aix", "amiga", "bsd", "dvh", "gpt", "loop", "mac",
"msdos", "pc98", or "sun".
CLI Example:
.. code-block:: bash
salt '*' partition.mklabel /dev/sda msdos
'''
if label_type not in set([
'aix', 'amiga', 'bsd', 'dvh', 'gpt', 'loop', 'mac', 'msdos', 'pc98', 'sun'
]):
raise CommandExecutionError(
'Invalid label_type passed to partition.mklabel'
)
cmd = ('parted', '-m', '-s', device, 'mklabel', label_type)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return out | [
"def",
"mklabel",
"(",
"device",
",",
"label_type",
")",
":",
"if",
"label_type",
"not",
"in",
"set",
"(",
"[",
"'aix'",
",",
"'amiga'",
",",
"'bsd'",
",",
"'dvh'",
",",
"'gpt'",
",",
"'loop'",
",",
"'mac'",
",",
"'msdos'",
",",
"'pc98'",
",",
"'sun'... | Create a new disklabel (partition table) of label_type.
Type should be one of "aix", "amiga", "bsd", "dvh", "gpt", "loop", "mac",
"msdos", "pc98", or "sun".
CLI Example:
.. code-block:: bash
salt '*' partition.mklabel /dev/sda msdos | [
"Create",
"a",
"new",
"disklabel",
"(",
"partition",
"table",
")",
"of",
"label_type",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L429-L451 | train |
saltstack/salt | salt/modules/parted_partition.py | mkpart | def mkpart(device, part_type, fs_type=None, start=None, end=None):
'''
Make a part_type partition for filesystem fs_type, beginning at start and
ending at end (by default in megabytes). part_type should be one of
"primary", "logical", or "extended".
CLI Examples:
.. code-block:: bash
salt '*' partition.mkpart /dev/sda primary fs_type=fat32 start=0 end=639
salt '*' partition.mkpart /dev/sda primary start=0 end=639
'''
if part_type not in set(['primary', 'logical', 'extended']):
raise CommandExecutionError(
'Invalid part_type passed to partition.mkpart'
)
if not _is_fstype(fs_type):
raise CommandExecutionError(
'Invalid fs_type passed to partition.mkpart'
)
if start is not None and end is not None:
_validate_partition_boundary(start)
_validate_partition_boundary(end)
if start is None:
start = ''
if end is None:
end = ''
if fs_type:
cmd = ('parted', '-m', '-s', '--', device, 'mkpart', part_type, fs_type, start, end)
else:
cmd = ('parted', '-m', '-s', '--', device, 'mkpart', part_type, start, end)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return out | python | def mkpart(device, part_type, fs_type=None, start=None, end=None):
'''
Make a part_type partition for filesystem fs_type, beginning at start and
ending at end (by default in megabytes). part_type should be one of
"primary", "logical", or "extended".
CLI Examples:
.. code-block:: bash
salt '*' partition.mkpart /dev/sda primary fs_type=fat32 start=0 end=639
salt '*' partition.mkpart /dev/sda primary start=0 end=639
'''
if part_type not in set(['primary', 'logical', 'extended']):
raise CommandExecutionError(
'Invalid part_type passed to partition.mkpart'
)
if not _is_fstype(fs_type):
raise CommandExecutionError(
'Invalid fs_type passed to partition.mkpart'
)
if start is not None and end is not None:
_validate_partition_boundary(start)
_validate_partition_boundary(end)
if start is None:
start = ''
if end is None:
end = ''
if fs_type:
cmd = ('parted', '-m', '-s', '--', device, 'mkpart', part_type, fs_type, start, end)
else:
cmd = ('parted', '-m', '-s', '--', device, 'mkpart', part_type, start, end)
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
return out | [
"def",
"mkpart",
"(",
"device",
",",
"part_type",
",",
"fs_type",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"if",
"part_type",
"not",
"in",
"set",
"(",
"[",
"'primary'",
",",
"'logical'",
",",
"'extended'",
"]",
")",
... | Make a part_type partition for filesystem fs_type, beginning at start and
ending at end (by default in megabytes). part_type should be one of
"primary", "logical", or "extended".
CLI Examples:
.. code-block:: bash
salt '*' partition.mkpart /dev/sda primary fs_type=fat32 start=0 end=639
salt '*' partition.mkpart /dev/sda primary start=0 end=639 | [
"Make",
"a",
"part_type",
"partition",
"for",
"filesystem",
"fs_type",
"beginning",
"at",
"start",
"and",
"ending",
"at",
"end",
"(",
"by",
"default",
"in",
"megabytes",
")",
".",
"part_type",
"should",
"be",
"one",
"of",
"primary",
"logical",
"or",
"extende... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L454-L493 | train |
saltstack/salt | salt/modules/parted_partition.py | mkpartfs | def mkpartfs(device, part_type, fs_type, start, end):
'''
Make a <part_type> partition with a new filesystem of <fs_type>, beginning
at <start> and ending at <end> (by default in megabytes).
<part_type> should be one of "primary", "logical", or "extended". <fs_type>
must be one of "ext2", "fat32", "fat16", "linux-swap" or "reiserfs" (if
libreiserfs is installed)
CLI Example:
.. code-block:: bash
salt '*' partition.mkpartfs /dev/sda logical ext2 440 670
'''
_validate_device(device)
if part_type not in set(['primary', 'logical', 'extended']):
raise CommandExecutionError(
'Invalid part_type passed to partition.mkpartfs'
)
if not _is_fstype(fs_type):
raise CommandExecutionError(
'Invalid fs_type passed to partition.mkpartfs'
)
_validate_partition_boundary(start)
_validate_partition_boundary(end)
cmd = 'parted -m -s -- {0} mkpart {1} {2} {3} {4}'.format(
device, part_type, fs_type, start, end
)
out = __salt__['cmd.run'](cmd).splitlines()
return out | python | def mkpartfs(device, part_type, fs_type, start, end):
'''
Make a <part_type> partition with a new filesystem of <fs_type>, beginning
at <start> and ending at <end> (by default in megabytes).
<part_type> should be one of "primary", "logical", or "extended". <fs_type>
must be one of "ext2", "fat32", "fat16", "linux-swap" or "reiserfs" (if
libreiserfs is installed)
CLI Example:
.. code-block:: bash
salt '*' partition.mkpartfs /dev/sda logical ext2 440 670
'''
_validate_device(device)
if part_type not in set(['primary', 'logical', 'extended']):
raise CommandExecutionError(
'Invalid part_type passed to partition.mkpartfs'
)
if not _is_fstype(fs_type):
raise CommandExecutionError(
'Invalid fs_type passed to partition.mkpartfs'
)
_validate_partition_boundary(start)
_validate_partition_boundary(end)
cmd = 'parted -m -s -- {0} mkpart {1} {2} {3} {4}'.format(
device, part_type, fs_type, start, end
)
out = __salt__['cmd.run'](cmd).splitlines()
return out | [
"def",
"mkpartfs",
"(",
"device",
",",
"part_type",
",",
"fs_type",
",",
"start",
",",
"end",
")",
":",
"_validate_device",
"(",
"device",
")",
"if",
"part_type",
"not",
"in",
"set",
"(",
"[",
"'primary'",
",",
"'logical'",
",",
"'extended'",
"]",
")",
... | Make a <part_type> partition with a new filesystem of <fs_type>, beginning
at <start> and ending at <end> (by default in megabytes).
<part_type> should be one of "primary", "logical", or "extended". <fs_type>
must be one of "ext2", "fat32", "fat16", "linux-swap" or "reiserfs" (if
libreiserfs is installed)
CLI Example:
.. code-block:: bash
salt '*' partition.mkpartfs /dev/sda logical ext2 440 670 | [
"Make",
"a",
"<part_type",
">",
"partition",
"with",
"a",
"new",
"filesystem",
"of",
"<fs_type",
">",
"beginning",
"at",
"<start",
">",
"and",
"ending",
"at",
"<end",
">",
"(",
"by",
"default",
"in",
"megabytes",
")",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L496-L530 | train |
saltstack/salt | salt/modules/parted_partition.py | name | def name(device, partition, name):
'''
Set the name of partition to name. This option works only on Mac, PC98, and
GPT disklabels. The name can be placed in quotes, if necessary.
CLI Example:
.. code-block:: bash
salt '*' partition.name /dev/sda 1 'My Documents'
'''
_validate_device(device)
try:
int(partition)
except Exception:
raise CommandExecutionError(
'Invalid partition passed to partition.name'
)
valid = string.ascii_letters + string.digits + ' _-'
for letter in name:
if letter not in valid:
raise CommandExecutionError(
'Invalid characters passed to partition.name'
)
cmd = '''parted -m -s {0} name {1} "'{2}'"'''.format(device, partition, name)
out = __salt__['cmd.run'](cmd).splitlines()
return out | python | def name(device, partition, name):
'''
Set the name of partition to name. This option works only on Mac, PC98, and
GPT disklabels. The name can be placed in quotes, if necessary.
CLI Example:
.. code-block:: bash
salt '*' partition.name /dev/sda 1 'My Documents'
'''
_validate_device(device)
try:
int(partition)
except Exception:
raise CommandExecutionError(
'Invalid partition passed to partition.name'
)
valid = string.ascii_letters + string.digits + ' _-'
for letter in name:
if letter not in valid:
raise CommandExecutionError(
'Invalid characters passed to partition.name'
)
cmd = '''parted -m -s {0} name {1} "'{2}'"'''.format(device, partition, name)
out = __salt__['cmd.run'](cmd).splitlines()
return out | [
"def",
"name",
"(",
"device",
",",
"partition",
",",
"name",
")",
":",
"_validate_device",
"(",
"device",
")",
"try",
":",
"int",
"(",
"partition",
")",
"except",
"Exception",
":",
"raise",
"CommandExecutionError",
"(",
"'Invalid partition passed to partition.name... | Set the name of partition to name. This option works only on Mac, PC98, and
GPT disklabels. The name can be placed in quotes, if necessary.
CLI Example:
.. code-block:: bash
salt '*' partition.name /dev/sda 1 'My Documents' | [
"Set",
"the",
"name",
"of",
"partition",
"to",
"name",
".",
"This",
"option",
"works",
"only",
"on",
"Mac",
"PC98",
"and",
"GPT",
"disklabels",
".",
"The",
"name",
"can",
"be",
"placed",
"in",
"quotes",
"if",
"necessary",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L533-L562 | train |
saltstack/salt | salt/modules/parted_partition.py | rescue | def rescue(device, start, end):
'''
Rescue a lost partition that was located somewhere between start and end.
If a partition is found, parted will ask if you want to create an
entry for it in the partition table.
CLI Example:
.. code-block:: bash
salt '*' partition.rescue /dev/sda 0 8056
'''
_validate_device(device)
_validate_partition_boundary(start)
_validate_partition_boundary(end)
cmd = 'parted -m -s {0} rescue {1} {2}'.format(device, start, end)
out = __salt__['cmd.run'](cmd).splitlines()
return out | python | def rescue(device, start, end):
'''
Rescue a lost partition that was located somewhere between start and end.
If a partition is found, parted will ask if you want to create an
entry for it in the partition table.
CLI Example:
.. code-block:: bash
salt '*' partition.rescue /dev/sda 0 8056
'''
_validate_device(device)
_validate_partition_boundary(start)
_validate_partition_boundary(end)
cmd = 'parted -m -s {0} rescue {1} {2}'.format(device, start, end)
out = __salt__['cmd.run'](cmd).splitlines()
return out | [
"def",
"rescue",
"(",
"device",
",",
"start",
",",
"end",
")",
":",
"_validate_device",
"(",
"device",
")",
"_validate_partition_boundary",
"(",
"start",
")",
"_validate_partition_boundary",
"(",
"end",
")",
"cmd",
"=",
"'parted -m -s {0} rescue {1} {2}'",
".",
"f... | Rescue a lost partition that was located somewhere between start and end.
If a partition is found, parted will ask if you want to create an
entry for it in the partition table.
CLI Example:
.. code-block:: bash
salt '*' partition.rescue /dev/sda 0 8056 | [
"Rescue",
"a",
"lost",
"partition",
"that",
"was",
"located",
"somewhere",
"between",
"start",
"and",
"end",
".",
"If",
"a",
"partition",
"is",
"found",
"parted",
"will",
"ask",
"if",
"you",
"want",
"to",
"create",
"an",
"entry",
"for",
"it",
"in",
"the"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L565-L583 | train |
saltstack/salt | salt/modules/parted_partition.py | resize | def resize(device, minor, start, end):
'''
Resizes the partition with number <minor>.
The partition will start <start> from the beginning of the disk, and end
<end> from the beginning of the disk. resize never changes the minor number.
Extended partitions can be resized, so long as the new extended partition
completely contains all logical partitions.
CLI Example:
.. code-block:: bash
salt '*' partition.resize /dev/sda 3 200 850
'''
_validate_device(device)
try:
int(minor)
except Exception:
raise CommandExecutionError(
'Invalid minor number passed to partition.resize'
)
_validate_partition_boundary(start)
_validate_partition_boundary(end)
out = __salt__['cmd.run'](
'parted -m -s -- {0} resize {1} {2} {3}'.format(
device, minor, start, end
)
)
return out.splitlines() | python | def resize(device, minor, start, end):
'''
Resizes the partition with number <minor>.
The partition will start <start> from the beginning of the disk, and end
<end> from the beginning of the disk. resize never changes the minor number.
Extended partitions can be resized, so long as the new extended partition
completely contains all logical partitions.
CLI Example:
.. code-block:: bash
salt '*' partition.resize /dev/sda 3 200 850
'''
_validate_device(device)
try:
int(minor)
except Exception:
raise CommandExecutionError(
'Invalid minor number passed to partition.resize'
)
_validate_partition_boundary(start)
_validate_partition_boundary(end)
out = __salt__['cmd.run'](
'parted -m -s -- {0} resize {1} {2} {3}'.format(
device, minor, start, end
)
)
return out.splitlines() | [
"def",
"resize",
"(",
"device",
",",
"minor",
",",
"start",
",",
"end",
")",
":",
"_validate_device",
"(",
"device",
")",
"try",
":",
"int",
"(",
"minor",
")",
"except",
"Exception",
":",
"raise",
"CommandExecutionError",
"(",
"'Invalid minor number passed to ... | Resizes the partition with number <minor>.
The partition will start <start> from the beginning of the disk, and end
<end> from the beginning of the disk. resize never changes the minor number.
Extended partitions can be resized, so long as the new extended partition
completely contains all logical partitions.
CLI Example:
.. code-block:: bash
salt '*' partition.resize /dev/sda 3 200 850 | [
"Resizes",
"the",
"partition",
"with",
"number",
"<minor",
">",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L586-L618 | train |
saltstack/salt | salt/modules/parted_partition.py | rm | def rm(device, minor): # pylint: disable=C0103
'''
Removes the partition with number <minor>.
CLI Example:
.. code-block:: bash
salt '*' partition.rm /dev/sda 5
'''
_validate_device(device)
try:
int(minor)
except Exception:
raise CommandExecutionError(
'Invalid minor number passed to partition.rm'
)
cmd = 'parted -m -s {0} rm {1}'.format(device, minor)
out = __salt__['cmd.run'](cmd).splitlines()
return out | python | def rm(device, minor): # pylint: disable=C0103
'''
Removes the partition with number <minor>.
CLI Example:
.. code-block:: bash
salt '*' partition.rm /dev/sda 5
'''
_validate_device(device)
try:
int(minor)
except Exception:
raise CommandExecutionError(
'Invalid minor number passed to partition.rm'
)
cmd = 'parted -m -s {0} rm {1}'.format(device, minor)
out = __salt__['cmd.run'](cmd).splitlines()
return out | [
"def",
"rm",
"(",
"device",
",",
"minor",
")",
":",
"# pylint: disable=C0103",
"_validate_device",
"(",
"device",
")",
"try",
":",
"int",
"(",
"minor",
")",
"except",
"Exception",
":",
"raise",
"CommandExecutionError",
"(",
"'Invalid minor number passed to partition... | Removes the partition with number <minor>.
CLI Example:
.. code-block:: bash
salt '*' partition.rm /dev/sda 5 | [
"Removes",
"the",
"partition",
"with",
"number",
"<minor",
">",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L621-L642 | train |
saltstack/salt | salt/modules/parted_partition.py | set_ | def set_(device, minor, flag, state):
'''
Changes a flag on the partition with number <minor>.
A flag can be either "on" or "off" (make sure to use proper quoting, see
:ref:`YAML Idiosyncrasies <yaml-idiosyncrasies>`). Some or all of these
flags will be available, depending on what disk label you are using.
Valid flags are:
* boot
* root
* swap
* hidden
* raid
* lvm
* lba
* hp-service
* palo
* prep
* msftres
* bios_grub
* atvrecv
* diag
* legacy_boot
* msftdata
* irst
* esp
* type
CLI Example:
.. code-block:: bash
salt '*' partition.set /dev/sda 1 boot '"on"'
'''
_validate_device(device)
try:
int(minor)
except Exception:
raise CommandExecutionError(
'Invalid minor number passed to partition.set'
)
if flag not in VALID_PARTITION_FLAGS:
raise CommandExecutionError('Invalid flag passed to partition.set')
if state not in set(['on', 'off']):
raise CommandExecutionError('Invalid state passed to partition.set')
cmd = 'parted -m -s {0} set {1} {2} {3}'.format(device, minor, flag, state)
out = __salt__['cmd.run'](cmd).splitlines()
return out | python | def set_(device, minor, flag, state):
'''
Changes a flag on the partition with number <minor>.
A flag can be either "on" or "off" (make sure to use proper quoting, see
:ref:`YAML Idiosyncrasies <yaml-idiosyncrasies>`). Some or all of these
flags will be available, depending on what disk label you are using.
Valid flags are:
* boot
* root
* swap
* hidden
* raid
* lvm
* lba
* hp-service
* palo
* prep
* msftres
* bios_grub
* atvrecv
* diag
* legacy_boot
* msftdata
* irst
* esp
* type
CLI Example:
.. code-block:: bash
salt '*' partition.set /dev/sda 1 boot '"on"'
'''
_validate_device(device)
try:
int(minor)
except Exception:
raise CommandExecutionError(
'Invalid minor number passed to partition.set'
)
if flag not in VALID_PARTITION_FLAGS:
raise CommandExecutionError('Invalid flag passed to partition.set')
if state not in set(['on', 'off']):
raise CommandExecutionError('Invalid state passed to partition.set')
cmd = 'parted -m -s {0} set {1} {2} {3}'.format(device, minor, flag, state)
out = __salt__['cmd.run'](cmd).splitlines()
return out | [
"def",
"set_",
"(",
"device",
",",
"minor",
",",
"flag",
",",
"state",
")",
":",
"_validate_device",
"(",
"device",
")",
"try",
":",
"int",
"(",
"minor",
")",
"except",
"Exception",
":",
"raise",
"CommandExecutionError",
"(",
"'Invalid minor number passed to p... | Changes a flag on the partition with number <minor>.
A flag can be either "on" or "off" (make sure to use proper quoting, see
:ref:`YAML Idiosyncrasies <yaml-idiosyncrasies>`). Some or all of these
flags will be available, depending on what disk label you are using.
Valid flags are:
* boot
* root
* swap
* hidden
* raid
* lvm
* lba
* hp-service
* palo
* prep
* msftres
* bios_grub
* atvrecv
* diag
* legacy_boot
* msftdata
* irst
* esp
* type
CLI Example:
.. code-block:: bash
salt '*' partition.set /dev/sda 1 boot '"on"' | [
"Changes",
"a",
"flag",
"on",
"the",
"partition",
"with",
"number",
"<minor",
">",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L645-L697 | train |
saltstack/salt | salt/modules/parted_partition.py | toggle | def toggle(device, partition, flag):
'''
Toggle the state of <flag> on <partition>. Valid flags are the same as
the set command.
CLI Example:
.. code-block:: bash
salt '*' partition.toggle /dev/sda 1 boot
'''
_validate_device(device)
try:
int(partition)
except Exception:
raise CommandExecutionError(
'Invalid partition number passed to partition.toggle'
)
if flag not in VALID_PARTITION_FLAGS:
raise CommandExecutionError('Invalid flag passed to partition.toggle')
cmd = 'parted -m -s {0} toggle {1} {2}'.format(device, partition, flag)
out = __salt__['cmd.run'](cmd).splitlines()
return out | python | def toggle(device, partition, flag):
'''
Toggle the state of <flag> on <partition>. Valid flags are the same as
the set command.
CLI Example:
.. code-block:: bash
salt '*' partition.toggle /dev/sda 1 boot
'''
_validate_device(device)
try:
int(partition)
except Exception:
raise CommandExecutionError(
'Invalid partition number passed to partition.toggle'
)
if flag not in VALID_PARTITION_FLAGS:
raise CommandExecutionError('Invalid flag passed to partition.toggle')
cmd = 'parted -m -s {0} toggle {1} {2}'.format(device, partition, flag)
out = __salt__['cmd.run'](cmd).splitlines()
return out | [
"def",
"toggle",
"(",
"device",
",",
"partition",
",",
"flag",
")",
":",
"_validate_device",
"(",
"device",
")",
"try",
":",
"int",
"(",
"partition",
")",
"except",
"Exception",
":",
"raise",
"CommandExecutionError",
"(",
"'Invalid partition number passed to parti... | Toggle the state of <flag> on <partition>. Valid flags are the same as
the set command.
CLI Example:
.. code-block:: bash
salt '*' partition.toggle /dev/sda 1 boot | [
"Toggle",
"the",
"state",
"of",
"<flag",
">",
"on",
"<partition",
">",
".",
"Valid",
"flags",
"are",
"the",
"same",
"as",
"the",
"set",
"command",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L700-L725 | train |
saltstack/salt | salt/modules/parted_partition.py | disk_set | def disk_set(device, flag, state):
'''
Changes a flag on selected device.
A flag can be either "on" or "off" (make sure to use proper
quoting, see :ref:`YAML Idiosyncrasies
<yaml-idiosyncrasies>`). Some or all of these flags will be
available, depending on what disk label you are using.
Valid flags are:
* cylinder_alignment
* pmbr_boot
* implicit_partition_table
CLI Example:
.. code-block:: bash
salt '*' partition.disk_set /dev/sda pmbr_boot '"on"'
'''
_validate_device(device)
if flag not in VALID_DISK_FLAGS:
raise CommandExecutionError('Invalid flag passed to partition.disk_set')
if state not in set(['on', 'off']):
raise CommandExecutionError('Invalid state passed to partition.disk_set')
cmd = ['parted', '-m', '-s', device, 'disk_set', flag, state]
out = __salt__['cmd.run'](cmd).splitlines()
return out | python | def disk_set(device, flag, state):
'''
Changes a flag on selected device.
A flag can be either "on" or "off" (make sure to use proper
quoting, see :ref:`YAML Idiosyncrasies
<yaml-idiosyncrasies>`). Some or all of these flags will be
available, depending on what disk label you are using.
Valid flags are:
* cylinder_alignment
* pmbr_boot
* implicit_partition_table
CLI Example:
.. code-block:: bash
salt '*' partition.disk_set /dev/sda pmbr_boot '"on"'
'''
_validate_device(device)
if flag not in VALID_DISK_FLAGS:
raise CommandExecutionError('Invalid flag passed to partition.disk_set')
if state not in set(['on', 'off']):
raise CommandExecutionError('Invalid state passed to partition.disk_set')
cmd = ['parted', '-m', '-s', device, 'disk_set', flag, state]
out = __salt__['cmd.run'](cmd).splitlines()
return out | [
"def",
"disk_set",
"(",
"device",
",",
"flag",
",",
"state",
")",
":",
"_validate_device",
"(",
"device",
")",
"if",
"flag",
"not",
"in",
"VALID_DISK_FLAGS",
":",
"raise",
"CommandExecutionError",
"(",
"'Invalid flag passed to partition.disk_set'",
")",
"if",
"sta... | Changes a flag on selected device.
A flag can be either "on" or "off" (make sure to use proper
quoting, see :ref:`YAML Idiosyncrasies
<yaml-idiosyncrasies>`). Some or all of these flags will be
available, depending on what disk label you are using.
Valid flags are:
* cylinder_alignment
* pmbr_boot
* implicit_partition_table
CLI Example:
.. code-block:: bash
salt '*' partition.disk_set /dev/sda pmbr_boot '"on"' | [
"Changes",
"a",
"flag",
"on",
"selected",
"device",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L728-L758 | train |
saltstack/salt | salt/modules/parted_partition.py | disk_toggle | def disk_toggle(device, flag):
'''
Toggle the state of <flag> on <device>. Valid flags are the same
as the disk_set command.
CLI Example:
.. code-block:: bash
salt '*' partition.disk_toggle /dev/sda pmbr_boot
'''
_validate_device(device)
if flag not in VALID_DISK_FLAGS:
raise CommandExecutionError('Invalid flag passed to partition.disk_toggle')
cmd = ['parted', '-m', '-s', device, 'disk_toggle', flag]
out = __salt__['cmd.run'](cmd).splitlines()
return out | python | def disk_toggle(device, flag):
'''
Toggle the state of <flag> on <device>. Valid flags are the same
as the disk_set command.
CLI Example:
.. code-block:: bash
salt '*' partition.disk_toggle /dev/sda pmbr_boot
'''
_validate_device(device)
if flag not in VALID_DISK_FLAGS:
raise CommandExecutionError('Invalid flag passed to partition.disk_toggle')
cmd = ['parted', '-m', '-s', device, 'disk_toggle', flag]
out = __salt__['cmd.run'](cmd).splitlines()
return out | [
"def",
"disk_toggle",
"(",
"device",
",",
"flag",
")",
":",
"_validate_device",
"(",
"device",
")",
"if",
"flag",
"not",
"in",
"VALID_DISK_FLAGS",
":",
"raise",
"CommandExecutionError",
"(",
"'Invalid flag passed to partition.disk_toggle'",
")",
"cmd",
"=",
"[",
"... | Toggle the state of <flag> on <device>. Valid flags are the same
as the disk_set command.
CLI Example:
.. code-block:: bash
salt '*' partition.disk_toggle /dev/sda pmbr_boot | [
"Toggle",
"the",
"state",
"of",
"<flag",
">",
"on",
"<device",
">",
".",
"Valid",
"flags",
"are",
"the",
"same",
"as",
"the",
"disk_set",
"command",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L761-L779 | train |
saltstack/salt | salt/modules/parted_partition.py | exists | def exists(device=''):
'''
Check to see if the partition exists
CLI Example:
.. code-block:: bash
salt '*' partition.exists /dev/sdb1
'''
if os.path.exists(device):
dev = os.stat(device).st_mode
if stat.S_ISBLK(dev):
return True
return False | python | def exists(device=''):
'''
Check to see if the partition exists
CLI Example:
.. code-block:: bash
salt '*' partition.exists /dev/sdb1
'''
if os.path.exists(device):
dev = os.stat(device).st_mode
if stat.S_ISBLK(dev):
return True
return False | [
"def",
"exists",
"(",
"device",
"=",
"''",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"device",
")",
":",
"dev",
"=",
"os",
".",
"stat",
"(",
"device",
")",
".",
"st_mode",
"if",
"stat",
".",
"S_ISBLK",
"(",
"dev",
")",
":",
"return... | Check to see if the partition exists
CLI Example:
.. code-block:: bash
salt '*' partition.exists /dev/sdb1 | [
"Check",
"to",
"see",
"if",
"the",
"partition",
"exists"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L782-L798 | train |
saltstack/salt | salt/modules/freezer.py | _paths | def _paths(name=None):
'''
Return the full path for the packages and repository freezer
files.
'''
name = 'freezer' if not name else name
states_path = _states_path()
return (
os.path.join(states_path, '{}-pkgs.yml'.format(name)),
os.path.join(states_path, '{}-reps.yml'.format(name)),
) | python | def _paths(name=None):
'''
Return the full path for the packages and repository freezer
files.
'''
name = 'freezer' if not name else name
states_path = _states_path()
return (
os.path.join(states_path, '{}-pkgs.yml'.format(name)),
os.path.join(states_path, '{}-reps.yml'.format(name)),
) | [
"def",
"_paths",
"(",
"name",
"=",
"None",
")",
":",
"name",
"=",
"'freezer'",
"if",
"not",
"name",
"else",
"name",
"states_path",
"=",
"_states_path",
"(",
")",
"return",
"(",
"os",
".",
"path",
".",
"join",
"(",
"states_path",
",",
"'{}-pkgs.yml'",
"... | Return the full path for the packages and repository freezer
files. | [
"Return",
"the",
"full",
"path",
"for",
"the",
"packages",
"and",
"repository",
"freezer",
"files",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freezer.py#L65-L76 | train |
saltstack/salt | salt/modules/freezer.py | status | def status(name=None):
'''
Return True if there is already a frozen state.
A frozen state is merely a list of packages (including the
version) in a specific time. This information can be used to
compare with the current list of packages, and revert the
installation of some extra packages that are in the system.
name
Name of the frozen state. Optional.
CLI Example:
.. code-block:: bash
salt '*' freezer.status
salt '*' freezer.status pre_install
'''
name = 'freezer' if not name else name
return all(os.path.isfile(i) for i in _paths(name)) | python | def status(name=None):
'''
Return True if there is already a frozen state.
A frozen state is merely a list of packages (including the
version) in a specific time. This information can be used to
compare with the current list of packages, and revert the
installation of some extra packages that are in the system.
name
Name of the frozen state. Optional.
CLI Example:
.. code-block:: bash
salt '*' freezer.status
salt '*' freezer.status pre_install
'''
name = 'freezer' if not name else name
return all(os.path.isfile(i) for i in _paths(name)) | [
"def",
"status",
"(",
"name",
"=",
"None",
")",
":",
"name",
"=",
"'freezer'",
"if",
"not",
"name",
"else",
"name",
"return",
"all",
"(",
"os",
".",
"path",
".",
"isfile",
"(",
"i",
")",
"for",
"i",
"in",
"_paths",
"(",
"name",
")",
")"
] | Return True if there is already a frozen state.
A frozen state is merely a list of packages (including the
version) in a specific time. This information can be used to
compare with the current list of packages, and revert the
installation of some extra packages that are in the system.
name
Name of the frozen state. Optional.
CLI Example:
.. code-block:: bash
salt '*' freezer.status
salt '*' freezer.status pre_install | [
"Return",
"True",
"if",
"there",
"is",
"already",
"a",
"frozen",
"state",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freezer.py#L79-L100 | train |
saltstack/salt | salt/modules/freezer.py | list_ | def list_():
'''
Return the list of frozen states.
CLI Example:
.. code-block:: bash
salt '*' freezer.list
'''
ret = []
states_path = _states_path()
if not os.path.isdir(states_path):
return ret
for state in os.listdir(states_path):
if state.endswith(('-pkgs.yml', '-reps.yml')):
# Remove the suffix, as both share the same size
ret.append(state[:-9])
return sorted(set(ret)) | python | def list_():
'''
Return the list of frozen states.
CLI Example:
.. code-block:: bash
salt '*' freezer.list
'''
ret = []
states_path = _states_path()
if not os.path.isdir(states_path):
return ret
for state in os.listdir(states_path):
if state.endswith(('-pkgs.yml', '-reps.yml')):
# Remove the suffix, as both share the same size
ret.append(state[:-9])
return sorted(set(ret)) | [
"def",
"list_",
"(",
")",
":",
"ret",
"=",
"[",
"]",
"states_path",
"=",
"_states_path",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"states_path",
")",
":",
"return",
"ret",
"for",
"state",
"in",
"os",
".",
"listdir",
"(",
"states... | Return the list of frozen states.
CLI Example:
.. code-block:: bash
salt '*' freezer.list | [
"Return",
"the",
"list",
"of",
"frozen",
"states",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freezer.py#L103-L123 | train |
saltstack/salt | salt/modules/freezer.py | freeze | def freeze(name=None, force=False, **kwargs):
'''
Save the list of package and repos in a freeze file.
As this module is build on top of the pkg module, the user can
send extra attributes to the underlying pkg module via kwargs.
This function will call ``pkg.list_pkgs`` and ``pkg.list_repos``,
and any additional arguments will be passed through to those
functions.
name
Name of the frozen state. Optional.
force
If true, overwrite the state. Optional.
CLI Example:
.. code-block:: bash
salt '*' freezer.freeze
salt '*' freezer.freeze pre_install
salt '*' freezer.freeze force=True root=/chroot
'''
states_path = _states_path()
try:
os.makedirs(states_path)
except OSError as e:
msg = 'Error when trying to create the freezer storage %s: %s'
log.error(msg, states_path, e)
raise CommandExecutionError(msg % (states_path, e))
if status(name) and not force:
raise CommandExecutionError('The state is already present. Use '
'force parameter to overwrite.')
safe_kwargs = clean_kwargs(**kwargs)
pkgs = __salt__['pkg.list_pkgs'](**safe_kwargs)
repos = __salt__['pkg.list_repos'](**safe_kwargs)
for name, content in zip(_paths(name), (pkgs, repos)):
with fopen(name, 'w') as fp:
json.dump(content, fp)
return True | python | def freeze(name=None, force=False, **kwargs):
'''
Save the list of package and repos in a freeze file.
As this module is build on top of the pkg module, the user can
send extra attributes to the underlying pkg module via kwargs.
This function will call ``pkg.list_pkgs`` and ``pkg.list_repos``,
and any additional arguments will be passed through to those
functions.
name
Name of the frozen state. Optional.
force
If true, overwrite the state. Optional.
CLI Example:
.. code-block:: bash
salt '*' freezer.freeze
salt '*' freezer.freeze pre_install
salt '*' freezer.freeze force=True root=/chroot
'''
states_path = _states_path()
try:
os.makedirs(states_path)
except OSError as e:
msg = 'Error when trying to create the freezer storage %s: %s'
log.error(msg, states_path, e)
raise CommandExecutionError(msg % (states_path, e))
if status(name) and not force:
raise CommandExecutionError('The state is already present. Use '
'force parameter to overwrite.')
safe_kwargs = clean_kwargs(**kwargs)
pkgs = __salt__['pkg.list_pkgs'](**safe_kwargs)
repos = __salt__['pkg.list_repos'](**safe_kwargs)
for name, content in zip(_paths(name), (pkgs, repos)):
with fopen(name, 'w') as fp:
json.dump(content, fp)
return True | [
"def",
"freeze",
"(",
"name",
"=",
"None",
",",
"force",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"states_path",
"=",
"_states_path",
"(",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"states_path",
")",
"except",
"OSError",
"as",
"e",
":",
... | Save the list of package and repos in a freeze file.
As this module is build on top of the pkg module, the user can
send extra attributes to the underlying pkg module via kwargs.
This function will call ``pkg.list_pkgs`` and ``pkg.list_repos``,
and any additional arguments will be passed through to those
functions.
name
Name of the frozen state. Optional.
force
If true, overwrite the state. Optional.
CLI Example:
.. code-block:: bash
salt '*' freezer.freeze
salt '*' freezer.freeze pre_install
salt '*' freezer.freeze force=True root=/chroot | [
"Save",
"the",
"list",
"of",
"package",
"and",
"repos",
"in",
"a",
"freeze",
"file",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freezer.py#L126-L169 | train |
saltstack/salt | salt/modules/freezer.py | restore | def restore(name=None, **kwargs):
'''
Make sure that the system contains the packages and repos from a
frozen state.
Read the list of packages and repositories from the freeze file,
and compare it with the current list of packages and repos. If
there is any difference, all the missing packages are repos will
be installed, and all the extra packages and repos will be
removed.
As this module is build on top of the pkg module, the user can
send extra attributes to the underlying pkg module via kwargs.
This function will call ``pkg.list_repos``, ``pkg.mod_repo``,
``pkg.list_pkgs``, ``pkg.install``, ``pkg.remove`` and
``pkg.del_repo``, and any additional arguments will be passed
through to those functions.
name
Name of the frozen state. Optional.
CLI Example:
.. code-block:: bash
salt '*' freezer.restore
salt '*' freezer.restore root=/chroot
'''
if not status(name):
raise CommandExecutionError('Frozen state not found.')
frozen_pkgs = {}
frozen_repos = {}
for name, content in zip(_paths(name), (frozen_pkgs, frozen_repos)):
with fopen(name) as fp:
content.update(json.load(fp))
# The ordering of removing or adding packages and repos can be
# relevant, as maybe some missing package comes from a repo that
# is also missing, so it cannot be installed. But can also happend
# that a missing package comes from a repo that is present, but
# will be removed.
#
# So the proposed order is;
# - Add missing repos
# - Add missing packages
# - Remove extra packages
# - Remove extra repos
safe_kwargs = clean_kwargs(**kwargs)
# Note that we expect that the information stored in list_XXX
# match with the mod_XXX counterpart. If this is not the case the
# recovery will be partial.
res = {
'pkgs': {'add': [], 'remove': []},
'repos': {'add': [], 'remove': []},
'comment': [],
}
# Add missing repositories
repos = __salt__['pkg.list_repos'](**safe_kwargs)
missing_repos = set(frozen_repos) - set(repos)
for repo in missing_repos:
try:
# In Python 2 we cannot do advance destructuring, so we
# need to create a temporary dictionary that will merge
# all the parameters
_tmp_kwargs = frozen_repos[repo].copy()
_tmp_kwargs.update(safe_kwargs)
__salt__['pkg.mod_repo'](repo, **_tmp_kwargs)
res['repos']['add'].append(repo)
log.info('Added missing repository %s', repo)
except Exception as e:
msg = 'Error adding %s repository: %s'
log.error(msg, repo, e)
res['comment'].append(msg % (repo, e))
# Add missing packages
# NOTE: we can remove the `for` using `pkgs`. This will improve
# performance, but I want to have a more detalied report of what
# packages are installed or failled.
pkgs = __salt__['pkg.list_pkgs'](**safe_kwargs)
missing_pkgs = set(frozen_pkgs) - set(pkgs)
for pkg in missing_pkgs:
try:
__salt__['pkg.install'](name=pkg, **safe_kwargs)
res['pkgs']['add'].append(pkg)
log.info('Added missing package %s', pkg)
except Exception as e:
msg = 'Error adding %s package: %s'
log.error(msg, pkg, e)
res['comment'].append(msg % (pkg, e))
# Remove extra packages
pkgs = __salt__['pkg.list_pkgs'](**safe_kwargs)
extra_pkgs = set(pkgs) - set(frozen_pkgs)
for pkg in extra_pkgs:
try:
__salt__['pkg.remove'](name=pkg, **safe_kwargs)
res['pkgs']['remove'].append(pkg)
log.info('Removed extra package %s', pkg)
except Exception as e:
msg = 'Error removing %s package: %s'
log.error(msg, pkg, e)
res['comment'].append(msg % (pkg, e))
# Remove extra repositories
repos = __salt__['pkg.list_repos'](**safe_kwargs)
extra_repos = set(repos) - set(frozen_repos)
for repo in extra_repos:
try:
__salt__['pkg.del_repo'](repo, **safe_kwargs)
res['repos']['remove'].append(repo)
log.info('Removed extra repository %s', repo)
except Exception as e:
msg = 'Error removing %s repository: %s'
log.error(msg, repo, e)
res['comment'].append(msg % (repo, e))
return res | python | def restore(name=None, **kwargs):
'''
Make sure that the system contains the packages and repos from a
frozen state.
Read the list of packages and repositories from the freeze file,
and compare it with the current list of packages and repos. If
there is any difference, all the missing packages are repos will
be installed, and all the extra packages and repos will be
removed.
As this module is build on top of the pkg module, the user can
send extra attributes to the underlying pkg module via kwargs.
This function will call ``pkg.list_repos``, ``pkg.mod_repo``,
``pkg.list_pkgs``, ``pkg.install``, ``pkg.remove`` and
``pkg.del_repo``, and any additional arguments will be passed
through to those functions.
name
Name of the frozen state. Optional.
CLI Example:
.. code-block:: bash
salt '*' freezer.restore
salt '*' freezer.restore root=/chroot
'''
if not status(name):
raise CommandExecutionError('Frozen state not found.')
frozen_pkgs = {}
frozen_repos = {}
for name, content in zip(_paths(name), (frozen_pkgs, frozen_repos)):
with fopen(name) as fp:
content.update(json.load(fp))
# The ordering of removing or adding packages and repos can be
# relevant, as maybe some missing package comes from a repo that
# is also missing, so it cannot be installed. But can also happend
# that a missing package comes from a repo that is present, but
# will be removed.
#
# So the proposed order is;
# - Add missing repos
# - Add missing packages
# - Remove extra packages
# - Remove extra repos
safe_kwargs = clean_kwargs(**kwargs)
# Note that we expect that the information stored in list_XXX
# match with the mod_XXX counterpart. If this is not the case the
# recovery will be partial.
res = {
'pkgs': {'add': [], 'remove': []},
'repos': {'add': [], 'remove': []},
'comment': [],
}
# Add missing repositories
repos = __salt__['pkg.list_repos'](**safe_kwargs)
missing_repos = set(frozen_repos) - set(repos)
for repo in missing_repos:
try:
# In Python 2 we cannot do advance destructuring, so we
# need to create a temporary dictionary that will merge
# all the parameters
_tmp_kwargs = frozen_repos[repo].copy()
_tmp_kwargs.update(safe_kwargs)
__salt__['pkg.mod_repo'](repo, **_tmp_kwargs)
res['repos']['add'].append(repo)
log.info('Added missing repository %s', repo)
except Exception as e:
msg = 'Error adding %s repository: %s'
log.error(msg, repo, e)
res['comment'].append(msg % (repo, e))
# Add missing packages
# NOTE: we can remove the `for` using `pkgs`. This will improve
# performance, but I want to have a more detalied report of what
# packages are installed or failled.
pkgs = __salt__['pkg.list_pkgs'](**safe_kwargs)
missing_pkgs = set(frozen_pkgs) - set(pkgs)
for pkg in missing_pkgs:
try:
__salt__['pkg.install'](name=pkg, **safe_kwargs)
res['pkgs']['add'].append(pkg)
log.info('Added missing package %s', pkg)
except Exception as e:
msg = 'Error adding %s package: %s'
log.error(msg, pkg, e)
res['comment'].append(msg % (pkg, e))
# Remove extra packages
pkgs = __salt__['pkg.list_pkgs'](**safe_kwargs)
extra_pkgs = set(pkgs) - set(frozen_pkgs)
for pkg in extra_pkgs:
try:
__salt__['pkg.remove'](name=pkg, **safe_kwargs)
res['pkgs']['remove'].append(pkg)
log.info('Removed extra package %s', pkg)
except Exception as e:
msg = 'Error removing %s package: %s'
log.error(msg, pkg, e)
res['comment'].append(msg % (pkg, e))
# Remove extra repositories
repos = __salt__['pkg.list_repos'](**safe_kwargs)
extra_repos = set(repos) - set(frozen_repos)
for repo in extra_repos:
try:
__salt__['pkg.del_repo'](repo, **safe_kwargs)
res['repos']['remove'].append(repo)
log.info('Removed extra repository %s', repo)
except Exception as e:
msg = 'Error removing %s repository: %s'
log.error(msg, repo, e)
res['comment'].append(msg % (repo, e))
return res | [
"def",
"restore",
"(",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"status",
"(",
"name",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'Frozen state not found.'",
")",
"frozen_pkgs",
"=",
"{",
"}",
"frozen_repos",
"=",
"{",
... | Make sure that the system contains the packages and repos from a
frozen state.
Read the list of packages and repositories from the freeze file,
and compare it with the current list of packages and repos. If
there is any difference, all the missing packages are repos will
be installed, and all the extra packages and repos will be
removed.
As this module is build on top of the pkg module, the user can
send extra attributes to the underlying pkg module via kwargs.
This function will call ``pkg.list_repos``, ``pkg.mod_repo``,
``pkg.list_pkgs``, ``pkg.install``, ``pkg.remove`` and
``pkg.del_repo``, and any additional arguments will be passed
through to those functions.
name
Name of the frozen state. Optional.
CLI Example:
.. code-block:: bash
salt '*' freezer.restore
salt '*' freezer.restore root=/chroot | [
"Make",
"sure",
"that",
"the",
"system",
"contains",
"the",
"packages",
"and",
"repos",
"from",
"a",
"frozen",
"state",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freezer.py#L172-L294 | train |
saltstack/salt | salt/modules/rabbitmq.py | _get_rabbitmq_plugin | def _get_rabbitmq_plugin():
'''
Returns the rabbitmq-plugin command path if we're running an OS that
doesn't put it in the standard /usr/bin or /usr/local/bin
This works by taking the rabbitmq-server version and looking for where it
seems to be hidden in /usr/lib.
'''
global RABBITMQ_PLUGINS
if RABBITMQ_PLUGINS is None:
version = __salt__['pkg.version']('rabbitmq-server').split('-')[0]
RABBITMQ_PLUGINS = ('/usr/lib/rabbitmq/lib/rabbitmq_server-{0}'
'/sbin/rabbitmq-plugins').format(version)
return RABBITMQ_PLUGINS | python | def _get_rabbitmq_plugin():
'''
Returns the rabbitmq-plugin command path if we're running an OS that
doesn't put it in the standard /usr/bin or /usr/local/bin
This works by taking the rabbitmq-server version and looking for where it
seems to be hidden in /usr/lib.
'''
global RABBITMQ_PLUGINS
if RABBITMQ_PLUGINS is None:
version = __salt__['pkg.version']('rabbitmq-server').split('-')[0]
RABBITMQ_PLUGINS = ('/usr/lib/rabbitmq/lib/rabbitmq_server-{0}'
'/sbin/rabbitmq-plugins').format(version)
return RABBITMQ_PLUGINS | [
"def",
"_get_rabbitmq_plugin",
"(",
")",
":",
"global",
"RABBITMQ_PLUGINS",
"if",
"RABBITMQ_PLUGINS",
"is",
"None",
":",
"version",
"=",
"__salt__",
"[",
"'pkg.version'",
"]",
"(",
"'rabbitmq-server'",
")",
".",
"split",
"(",
"'-'",
")",
"[",
"0",
"]",
"RABB... | Returns the rabbitmq-plugin command path if we're running an OS that
doesn't put it in the standard /usr/bin or /usr/local/bin
This works by taking the rabbitmq-server version and looking for where it
seems to be hidden in /usr/lib. | [
"Returns",
"the",
"rabbitmq",
"-",
"plugin",
"command",
"path",
"if",
"we",
"re",
"running",
"an",
"OS",
"that",
"doesn",
"t",
"put",
"it",
"in",
"the",
"standard",
"/",
"usr",
"/",
"bin",
"or",
"/",
"usr",
"/",
"local",
"/",
"bin",
"This",
"works",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rabbitmq.py#L115-L129 | train |
saltstack/salt | salt/modules/rabbitmq.py | _safe_output | def _safe_output(line):
'''
Looks for rabbitmqctl warning, or general formatting, strings that aren't
intended to be parsed as output.
Returns a boolean whether the line can be parsed as rabbitmqctl output.
'''
return not any([
line.startswith('Listing') and line.endswith('...'),
line.startswith('Listing') and '\t' not in line,
'...done' in line,
line.startswith('WARNING:')
]) | python | def _safe_output(line):
'''
Looks for rabbitmqctl warning, or general formatting, strings that aren't
intended to be parsed as output.
Returns a boolean whether the line can be parsed as rabbitmqctl output.
'''
return not any([
line.startswith('Listing') and line.endswith('...'),
line.startswith('Listing') and '\t' not in line,
'...done' in line,
line.startswith('WARNING:')
]) | [
"def",
"_safe_output",
"(",
"line",
")",
":",
"return",
"not",
"any",
"(",
"[",
"line",
".",
"startswith",
"(",
"'Listing'",
")",
"and",
"line",
".",
"endswith",
"(",
"'...'",
")",
",",
"line",
".",
"startswith",
"(",
"'Listing'",
")",
"and",
"'\\t'",
... | Looks for rabbitmqctl warning, or general formatting, strings that aren't
intended to be parsed as output.
Returns a boolean whether the line can be parsed as rabbitmqctl output. | [
"Looks",
"for",
"rabbitmqctl",
"warning",
"or",
"general",
"formatting",
"strings",
"that",
"aren",
"t",
"intended",
"to",
"be",
"parsed",
"as",
"output",
".",
"Returns",
"a",
"boolean",
"whether",
"the",
"line",
"can",
"be",
"parsed",
"as",
"rabbitmqctl",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rabbitmq.py#L132-L143 | train |
saltstack/salt | salt/modules/rabbitmq.py | _output_to_dict | def _output_to_dict(cmdoutput, values_mapper=None):
'''
Convert rabbitmqctl output to a dict of data
cmdoutput: string output of rabbitmqctl commands
values_mapper: function object to process the values part of each line
'''
if isinstance(cmdoutput, dict):
if cmdoutput['retcode'] != 0 or cmdoutput['stderr']:
raise CommandExecutionError(
'RabbitMQ command failed: {0}'.format(cmdoutput['stderr'])
)
cmdoutput = cmdoutput['stdout']
ret = {}
if values_mapper is None:
values_mapper = lambda string: string.split('\t')
# remove first and last line: Listing ... - ...done
data_rows = _strip_listing_to_done(cmdoutput.splitlines())
for row in data_rows:
try:
key, values = row.split('\t', 1)
except ValueError:
# If we have reached this far, we've hit an edge case where the row
# only has one item: the key. The key doesn't have any values, so we
# set it to an empty string to preserve rabbitmq reporting behavior.
# e.g. A user's permission string for '/' is set to ['', '', ''],
# Rabbitmq reports this only as '/' from the rabbitmqctl command.
log.debug('Could not find any values for key \'%s\'. '
'Setting to \'%s\' to an empty string.', row, row)
ret[row] = ''
continue
ret[key] = values_mapper(values)
return ret | python | def _output_to_dict(cmdoutput, values_mapper=None):
'''
Convert rabbitmqctl output to a dict of data
cmdoutput: string output of rabbitmqctl commands
values_mapper: function object to process the values part of each line
'''
if isinstance(cmdoutput, dict):
if cmdoutput['retcode'] != 0 or cmdoutput['stderr']:
raise CommandExecutionError(
'RabbitMQ command failed: {0}'.format(cmdoutput['stderr'])
)
cmdoutput = cmdoutput['stdout']
ret = {}
if values_mapper is None:
values_mapper = lambda string: string.split('\t')
# remove first and last line: Listing ... - ...done
data_rows = _strip_listing_to_done(cmdoutput.splitlines())
for row in data_rows:
try:
key, values = row.split('\t', 1)
except ValueError:
# If we have reached this far, we've hit an edge case where the row
# only has one item: the key. The key doesn't have any values, so we
# set it to an empty string to preserve rabbitmq reporting behavior.
# e.g. A user's permission string for '/' is set to ['', '', ''],
# Rabbitmq reports this only as '/' from the rabbitmqctl command.
log.debug('Could not find any values for key \'%s\'. '
'Setting to \'%s\' to an empty string.', row, row)
ret[row] = ''
continue
ret[key] = values_mapper(values)
return ret | [
"def",
"_output_to_dict",
"(",
"cmdoutput",
",",
"values_mapper",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"cmdoutput",
",",
"dict",
")",
":",
"if",
"cmdoutput",
"[",
"'retcode'",
"]",
"!=",
"0",
"or",
"cmdoutput",
"[",
"'stderr'",
"]",
":",
"rais... | Convert rabbitmqctl output to a dict of data
cmdoutput: string output of rabbitmqctl commands
values_mapper: function object to process the values part of each line | [
"Convert",
"rabbitmqctl",
"output",
"to",
"a",
"dict",
"of",
"data",
"cmdoutput",
":",
"string",
"output",
"of",
"rabbitmqctl",
"commands",
"values_mapper",
":",
"function",
"object",
"to",
"process",
"the",
"values",
"part",
"of",
"each",
"line"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rabbitmq.py#L156-L190 | train |
saltstack/salt | salt/modules/rabbitmq.py | _output_to_list | def _output_to_list(cmdoutput):
'''
Convert rabbitmqctl output to a list of strings (assuming whitespace-delimited output).
Ignores output lines that shouldn't be parsed, like warnings.
cmdoutput: string output of rabbitmqctl commands
'''
return [item for line in cmdoutput.splitlines() if _safe_output(line) for item in line.split()] | python | def _output_to_list(cmdoutput):
'''
Convert rabbitmqctl output to a list of strings (assuming whitespace-delimited output).
Ignores output lines that shouldn't be parsed, like warnings.
cmdoutput: string output of rabbitmqctl commands
'''
return [item for line in cmdoutput.splitlines() if _safe_output(line) for item in line.split()] | [
"def",
"_output_to_list",
"(",
"cmdoutput",
")",
":",
"return",
"[",
"item",
"for",
"line",
"in",
"cmdoutput",
".",
"splitlines",
"(",
")",
"if",
"_safe_output",
"(",
"line",
")",
"for",
"item",
"in",
"line",
".",
"split",
"(",
")",
"]"
] | Convert rabbitmqctl output to a list of strings (assuming whitespace-delimited output).
Ignores output lines that shouldn't be parsed, like warnings.
cmdoutput: string output of rabbitmqctl commands | [
"Convert",
"rabbitmqctl",
"output",
"to",
"a",
"list",
"of",
"strings",
"(",
"assuming",
"whitespace",
"-",
"delimited",
"output",
")",
".",
"Ignores",
"output",
"lines",
"that",
"shouldn",
"t",
"be",
"parsed",
"like",
"warnings",
".",
"cmdoutput",
":",
"str... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rabbitmq.py#L193-L199 | train |
saltstack/salt | salt/modules/rabbitmq.py | list_users | def list_users(runas=None):
'''
Return a list of users based off of rabbitmqctl user_list.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.list_users
'''
# Windows runas currently requires a password.
# Due to this, don't use a default value for
# runas in Windows.
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_user()
res = __salt__['cmd.run_all'](
[RABBITMQCTL, 'list_users', '-q'],
reset_system_locale=False,
runas=runas,
python_shell=False)
# func to get tags from string such as "[admin, monitoring]"
func = lambda string: [x.strip() for x in string[1:-1].split(',')] if ',' in string else [x for x in
string[1:-1].split(' ')]
return _output_to_dict(res, func) | python | def list_users(runas=None):
'''
Return a list of users based off of rabbitmqctl user_list.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.list_users
'''
# Windows runas currently requires a password.
# Due to this, don't use a default value for
# runas in Windows.
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_user()
res = __salt__['cmd.run_all'](
[RABBITMQCTL, 'list_users', '-q'],
reset_system_locale=False,
runas=runas,
python_shell=False)
# func to get tags from string such as "[admin, monitoring]"
func = lambda string: [x.strip() for x in string[1:-1].split(',')] if ',' in string else [x for x in
string[1:-1].split(' ')]
return _output_to_dict(res, func) | [
"def",
"list_users",
"(",
"runas",
"=",
"None",
")",
":",
"# Windows runas currently requires a password.",
"# Due to this, don't use a default value for",
"# runas in Windows.",
"if",
"runas",
"is",
"None",
"and",
"not",
"salt",
".",
"utils",
".",
"platform",
".",
"is_... | Return a list of users based off of rabbitmqctl user_list.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.list_users | [
"Return",
"a",
"list",
"of",
"users",
"based",
"off",
"of",
"rabbitmqctl",
"user_list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rabbitmq.py#L211-L235 | train |
saltstack/salt | salt/modules/rabbitmq.py | list_vhosts | def list_vhosts(runas=None):
'''
Return a list of vhost based on rabbitmqctl list_vhosts.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.list_vhosts
'''
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_user()
res = __salt__['cmd.run_all'](
[RABBITMQCTL, 'list_vhosts', '-q'],
reset_system_locale=False,
runas=runas,
python_shell=False)
_check_response(res)
return _output_to_list(res['stdout']) | python | def list_vhosts(runas=None):
'''
Return a list of vhost based on rabbitmqctl list_vhosts.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.list_vhosts
'''
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_user()
res = __salt__['cmd.run_all'](
[RABBITMQCTL, 'list_vhosts', '-q'],
reset_system_locale=False,
runas=runas,
python_shell=False)
_check_response(res)
return _output_to_list(res['stdout']) | [
"def",
"list_vhosts",
"(",
"runas",
"=",
"None",
")",
":",
"if",
"runas",
"is",
"None",
"and",
"not",
"salt",
".",
"utils",
".",
"platform",
".",
"is_windows",
"(",
")",
":",
"runas",
"=",
"salt",
".",
"utils",
".",
"user",
".",
"get_user",
"(",
")... | Return a list of vhost based on rabbitmqctl list_vhosts.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.list_vhosts | [
"Return",
"a",
"list",
"of",
"vhost",
"based",
"on",
"rabbitmqctl",
"list_vhosts",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rabbitmq.py#L238-L256 | train |
saltstack/salt | salt/modules/rabbitmq.py | user_exists | def user_exists(name, runas=None):
'''
Return whether the user exists based on rabbitmqctl list_users.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.user_exists rabbit_user
'''
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_user()
return name in list_users(runas=runas) | python | def user_exists(name, runas=None):
'''
Return whether the user exists based on rabbitmqctl list_users.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.user_exists rabbit_user
'''
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_user()
return name in list_users(runas=runas) | [
"def",
"user_exists",
"(",
"name",
",",
"runas",
"=",
"None",
")",
":",
"if",
"runas",
"is",
"None",
"and",
"not",
"salt",
".",
"utils",
".",
"platform",
".",
"is_windows",
"(",
")",
":",
"runas",
"=",
"salt",
".",
"utils",
".",
"user",
".",
"get_u... | Return whether the user exists based on rabbitmqctl list_users.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.user_exists rabbit_user | [
"Return",
"whether",
"the",
"user",
"exists",
"based",
"on",
"rabbitmqctl",
"list_users",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rabbitmq.py#L259-L271 | train |
saltstack/salt | salt/modules/rabbitmq.py | vhost_exists | def vhost_exists(name, runas=None):
'''
Return whether the vhost exists based on rabbitmqctl list_vhosts.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.vhost_exists rabbit_host
'''
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_user()
return name in list_vhosts(runas=runas) | python | def vhost_exists(name, runas=None):
'''
Return whether the vhost exists based on rabbitmqctl list_vhosts.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.vhost_exists rabbit_host
'''
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_user()
return name in list_vhosts(runas=runas) | [
"def",
"vhost_exists",
"(",
"name",
",",
"runas",
"=",
"None",
")",
":",
"if",
"runas",
"is",
"None",
"and",
"not",
"salt",
".",
"utils",
".",
"platform",
".",
"is_windows",
"(",
")",
":",
"runas",
"=",
"salt",
".",
"utils",
".",
"user",
".",
"get_... | Return whether the vhost exists based on rabbitmqctl list_vhosts.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.vhost_exists rabbit_host | [
"Return",
"whether",
"the",
"vhost",
"exists",
"based",
"on",
"rabbitmqctl",
"list_vhosts",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rabbitmq.py#L274-L286 | train |
saltstack/salt | salt/modules/rabbitmq.py | add_user | def add_user(name, password=None, runas=None):
'''
Add a rabbitMQ user via rabbitmqctl user_add <user> <password>
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.add_user rabbit_user password
'''
clear_pw = False
if password is None:
# Generate a random, temporary password. RabbitMQ requires one.
clear_pw = True
password = ''.join(random.SystemRandom().choice(
string.ascii_uppercase + string.digits) for x in range(15))
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_user()
if salt.utils.platform.is_windows():
# On Windows, if the password contains a special character
# such as '|', normal execution will fail. For example:
# cmd: rabbitmq.add_user abc "asdf|def"
# stderr: 'def' is not recognized as an internal or external
# command,\r\noperable program or batch file.
# Work around this by using a shell and a quoted command.
python_shell = True
cmd = '"{0}" add_user "{1}" "{2}"'.format(
RABBITMQCTL, name, password
)
else:
python_shell = False
cmd = [RABBITMQCTL, 'add_user', name, password]
res = __salt__['cmd.run_all'](
cmd,
reset_system_locale=False,
output_loglevel='quiet',
runas=runas,
python_shell=python_shell)
if clear_pw:
# Now, Clear the random password from the account, if necessary
try:
clear_password(name, runas)
except Exception:
# Clearing the password failed. We should try to cleanup
# and rerun and error.
delete_user(name, runas)
raise
msg = 'Added'
return _format_response(res, msg) | python | def add_user(name, password=None, runas=None):
'''
Add a rabbitMQ user via rabbitmqctl user_add <user> <password>
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.add_user rabbit_user password
'''
clear_pw = False
if password is None:
# Generate a random, temporary password. RabbitMQ requires one.
clear_pw = True
password = ''.join(random.SystemRandom().choice(
string.ascii_uppercase + string.digits) for x in range(15))
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_user()
if salt.utils.platform.is_windows():
# On Windows, if the password contains a special character
# such as '|', normal execution will fail. For example:
# cmd: rabbitmq.add_user abc "asdf|def"
# stderr: 'def' is not recognized as an internal or external
# command,\r\noperable program or batch file.
# Work around this by using a shell and a quoted command.
python_shell = True
cmd = '"{0}" add_user "{1}" "{2}"'.format(
RABBITMQCTL, name, password
)
else:
python_shell = False
cmd = [RABBITMQCTL, 'add_user', name, password]
res = __salt__['cmd.run_all'](
cmd,
reset_system_locale=False,
output_loglevel='quiet',
runas=runas,
python_shell=python_shell)
if clear_pw:
# Now, Clear the random password from the account, if necessary
try:
clear_password(name, runas)
except Exception:
# Clearing the password failed. We should try to cleanup
# and rerun and error.
delete_user(name, runas)
raise
msg = 'Added'
return _format_response(res, msg) | [
"def",
"add_user",
"(",
"name",
",",
"password",
"=",
"None",
",",
"runas",
"=",
"None",
")",
":",
"clear_pw",
"=",
"False",
"if",
"password",
"is",
"None",
":",
"# Generate a random, temporary password. RabbitMQ requires one.",
"clear_pw",
"=",
"True",
"password"... | Add a rabbitMQ user via rabbitmqctl user_add <user> <password>
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.add_user rabbit_user password | [
"Add",
"a",
"rabbitMQ",
"user",
"via",
"rabbitmqctl",
"user_add",
"<user",
">",
"<password",
">"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rabbitmq.py#L289-L343 | train |
saltstack/salt | salt/modules/rabbitmq.py | delete_user | def delete_user(name, runas=None):
'''
Deletes a user via rabbitmqctl delete_user.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.delete_user rabbit_user
'''
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_user()
res = __salt__['cmd.run_all'](
[RABBITMQCTL, 'delete_user', name],
reset_system_locale=False,
python_shell=False,
runas=runas)
msg = 'Deleted'
return _format_response(res, msg) | python | def delete_user(name, runas=None):
'''
Deletes a user via rabbitmqctl delete_user.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.delete_user rabbit_user
'''
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_user()
res = __salt__['cmd.run_all'](
[RABBITMQCTL, 'delete_user', name],
reset_system_locale=False,
python_shell=False,
runas=runas)
msg = 'Deleted'
return _format_response(res, msg) | [
"def",
"delete_user",
"(",
"name",
",",
"runas",
"=",
"None",
")",
":",
"if",
"runas",
"is",
"None",
"and",
"not",
"salt",
".",
"utils",
".",
"platform",
".",
"is_windows",
"(",
")",
":",
"runas",
"=",
"salt",
".",
"utils",
".",
"user",
".",
"get_u... | Deletes a user via rabbitmqctl delete_user.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.delete_user rabbit_user | [
"Deletes",
"a",
"user",
"via",
"rabbitmqctl",
"delete_user",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rabbitmq.py#L346-L365 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.